Reputation: 258
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.
Upvotes: 2
Views: 1217
Reputation: 143
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()
Upvotes: 1
Reputation: 473202
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.
Upvotes: 1
Reputation: 52621
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
Upvotes: 3