2

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.

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Shouldn't the last sentence be "You cannot do that if you declare abcd as local"?
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.