Access local variable by name

后端 未结 2 1874
北荒
北荒 2020-12-20 15:05

With globals you can use _G[name] to access the global variable name if you have a string \"name\":

function setGlobal(name, val)
          


        
相关标签:
2条回答
  • 2020-12-20 15:21

    I strongly recommend not using getLocal, it's a function in the debug library which should never be used in official commercial uses because it affects performance and opens huge vulnerabilities for hackers to exploit! Never depend on debug functions for your logic. If you really need this, then why not define a dictionary _L, then:

    local _L = {}
    _L.var1 = ...
    _L.var2 = ...
    

    The pattern above is not against the rules of Lua's design.

    0 讨论(0)
  • 2020-12-20 15:34

    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

    0 讨论(0)
提交回复
热议问题