Global Variables with Dynamic Names?

MapModData should give you the same effect, see TableSaverLoader for example(s)
 
Even _G isn't global in that sense. It's just another label that gets assigned to a table containing the state environment, which is going to be a different table in each state. Since Firaxis sandboxed that (in all states except Main), I assume that there is no way to get to the state environment where variable names are held.

There may be some solution for you in debug library, but that would be frowned upon.
 
It seems clear that my question was not clearly stated :lol:
I am not asking about sandboxing, there are ways around that (LuaEvents, MapModData, getmetatable...). My question was: within a given LuaContext, how can I create global variables named by a procedure/function ? Lua allows to do that with _G: _G[myVariableName] = something creates a global variable whose name is defined by myVariableName, but since we don't have _G ...
 
I see (maybe).

Perhaps loadstring will work for you (assuming execution time during your naming function isn't an issue). I played around with this a while back. IIRC, variables names in the loadstring always reference globals of the same name in the environment where the loadstring was run. This can be tricky. For example, if you have iPlayer in the Lua string you are compiling, it will look for a global of that name and ignore any locally defined iPlayer. I'm not sure if you can define a new global this way (that is later referenced by Lua code outside the loadstring). I think it would work though, since Lua doesn't try to decide the scope of a particular label in the code until run time.

Edit: "The environment of the returned function is the global environment" (from the 5.1 manual). From that, I think you could assign to an unused label in the loadstring. Lua would then do what it normally does, which is to create a new global variable using that name.
 
Back
Top Bottom