Lua参数为字符串名称

时间:2011-08-12 07:13:31

标签: string lua arguments

我有一个这样的字符串:

local tempStr = "abcd"

我希望将名为“abcd”的变量发送到这样的函数:

local abcd = 3

print( tempStr ) -- not correct!!

,结果将是3,而不是abcd。

3 个答案:

答案 0 :(得分:2)

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

local tempStr = "abcd"

local t = {}

t[tempStr] = 3

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

答案 1 :(得分:1)

对于声明为local的变量,您无法做到这一点。这些变量只是堆栈地址;他们没有永久存储空间。

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

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

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

答案 2 :(得分:1)

函数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()