本文介绍了按名称访问局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于全局变量,如果您有字符串name",您可以使用 _G[name]
访问全局变量 name
:
With globals you can use _G[name]
to access the global variable name
if you have a string "name":
function setGlobal(name, val)
_G[name] = val
end
如果你有
-- module.lua
local var1
local var2
没有 _L
可以让您为本地人做等效的事情:
there is no _L
that would allow you to do the equivalent for locals:
function setLocal(name, val)
_L[name] = val -- _L doesn't exist
end
是否有另一种方法可以通过表示其名称的字符串访问局部变量?
Is there another way that you could access a local variable by string representing its name?
推荐答案
您可以在 :
You can use debug.gelocal()
and debug.setlocal()
in the debug
library:
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
这篇关于按名称访问局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!