String Lua参数作为字符串名

String Lua参数作为字符串名,string,lua,arguments,String,Lua,Arguments,我有这样一个字符串: local tempStr = "abcd" local abcd = 3 print( tempStr ) -- not correct!! 我想将名为abcd的变量发送到如下函数: local tempStr = "abcd" local abcd = 3 print( tempStr ) -- not correct!! 结果将是3,而不是abcd。如果变量声明为本地变量,则不能这样做。这些变量只是堆栈地址;它们没有永久存储空间 您要做的是使用变量的内容访

我有这样一个字符串:

local tempStr = "abcd"
local abcd = 3

print( tempStr ) -- not correct!!
我想将名为abcd的变量发送到如下函数:

local tempStr = "abcd"
local abcd = 3

print( tempStr ) -- not correct!!

结果将是3,而不是abcd。

如果变量声明为本地变量,则不能这样做。这些变量只是堆栈地址;它们没有永久存储空间

您要做的是使用变量的内容访问表的元素。当然可以是全局表。要做到这一点,您需要:

local tempStr = "abcd"
abcd = 3 --Sets a value in the global table.
print(_G[tempStr]) --Access the global table and print the value.

如果将abcd声明为本地变量,则无法执行此操作。

如果将变量声明为本地变量,则无法执行此操作。这些变量只是堆栈地址;它们没有永久存储空间

您要做的是使用变量的内容访问表的元素。当然可以是全局表。要做到这一点,您需要:

local tempStr = "abcd"
abcd = 3 --Sets a value in the global table.
print(_G[tempStr]) --Access the global table and print the value.

如果将abcd声明为本地变量,则无法执行此操作。

如果使用表而不是普通变量,则可以使用本地变量执行此操作:

local tempStr = "abcd"

local t = {}

t[tempStr] = 3

print( t[tempStr]) -- will print 3

如果使用表而不是普通变量,则可以使用局部变量:

local tempStr = "abcd"

local t = {}

t[tempStr] = 3

print( t[tempStr]) -- will print 3
函数debug.getlocal可以帮助您

function f(name)
    local index = 1
    while true do
        local name_,value = debug.getlocal(2,index)
        if not name_ then break end
        if name_ == name then return value end
        index = index + 1
    end 
end

function g()
    local a = "a!"
    local b = "b!"
    local c = "c!"
    print (f("b")) -- will print "b!"
end

g()
函数debug.getlocal可以帮助您

function f(name)
    local index = 1
    while true do
        local name_,value = debug.getlocal(2,index)
        if not name_ then break end
        if name_ == name then return value end
        index = index + 1
    end 
end

function g()
    local a = "a!"
    local b = "b!"
    local c = "c!"
    print (f("b")) -- will print "b!"
end

g()

最后一句话不应该是,如果您将abcd声明为本地,您就不能这样做吗?如果您将abcd声明为本地,您就不能这样做吗?