I have a string like this:
local tempStr = "abcd"
and I want to send the variable which is named as "abcd" to a function like this:
local abcd = 3
print( tempStr ) -- not correct!!
and the result will be 3, not abcd.
You can do it with local variables if you use a table instead of a "plain" variable:
local tempStr = "abcd"
local t = {}
t[tempStr] = 3
print( t[tempStr]) -- will print 3
You can't do that with variables declared as local
. Such variables are just stack addresses; they don't have permanent storage.
What you're wanting to do is use the content of a variable to access an element of a table. Which can of course be the global table. To do that, you would do:
local tempStr = "abcd"
abcd = 3 --Sets a value in the global table.
print(_G[tempStr]) --Access the global table and print the value.
You cannot do that if you declare abcd
as local.
The function debug.getlocal
could help you.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.