Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

lua - Access local variable by 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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Test:

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

Output: 42


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...