使用全局变量,如果您有字符串“名称”,则可以使用_G[name]
访问全局变量name
:
function setGlobal(name, val)
_G[name] = val
end
如果你有
-- module.lua
local var1
local var2
没有
_L
可以让您对本地人做同样的事情:function setLocal(name, val)
_L[name] = val -- _L doesn't exist
end
您是否可以通过另一种方式通过表示其名称的字符串访问局部变量?
最佳答案
您可以在 debug.gelocal()
library中使用debug.setlocal()
和debug
:
function setLocal(name, val)
local index = 1
while true do
local var_name, var_value = debug.getlocal(2, index)
if not var_name then break end
if var_name == name then
debug.setlocal(2, index, val)
end
index = index + 1
end
end
测试:
local var1
local var2
setLocal("var1", 42)
print(var1)
输出:
42
关于lua - 通过名称访问局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752213/