Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access local variable by name

Tags:

lua

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

If you have

-- module.lua
local var1
local var2

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?

like image 821
Oliver Avatar asked Mar 31 '14 01:03

Oliver


1 Answers

You can use debug.getlocal() 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

Test:

local var1
local var2
setLocal("var1", 42)
print(var1)

Output: 42

like image 80
Yu Hao Avatar answered Oct 23 '22 15:10

Yu Hao