【发布时间】:2011-10-25 14:10:33
【问题描述】:
我有一个这样的字符串:
local tempStr = "abcd"
我想将名为“abcd”的变量发送到这样的函数:
local abcd = 3
print( tempStr ) -- not correct!!
结果将是 3,而不是 abcd。
【问题讨论】:
我有一个这样的字符串:
local tempStr = "abcd"
我想将名为“abcd”的变量发送到这样的函数:
local abcd = 3
print( tempStr ) -- not correct!!
结果将是 3,而不是 abcd。
【问题讨论】:
如果您使用表格而不是“普通”变量,则可以使用局部变量:
local tempStr = "abcd"
local t = {}
t[tempStr] = 3
print( t[tempStr]) -- will print 3
【讨论】:
对于声明为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 声明为本地,则不能这样做。
【讨论】:
abcd声明为本地,你就不能这样做”?
函数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()
【讨论】: