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?
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:The pattern above is not against the rules of Lua's design.
You can use
debug.gelocal()
anddebug.setlocal()
in thedebug
library:Test:
Output:
42