Lets say i have at least two lua script files.
test1.lua test2.lua
both define an init function and other functions with similar names.
How can i load each script file using c++/c into a separate environment using Lua 5.2 so that the same function names will not clash - i found a sample code for 5.1 which does not work for me (because setenv is gone and lua_setuservalue does not seem to work)
Sample here Calling lua functions from .lua's using handles?
Basically if i replace setenv with setuservalue - i get an access violation.
First of all, why are those functions global? They should be local to the script. If you're going to
require
them in other files, they should create and return a table containing the functions that they wish to expose.The modern idiom when requiring these files is to do something like this:
Thus, you do not pollute the global Lua namespace. You use local variables.
However, if you insist on using globals like this, you can do exactly what the documentation said: change the first upvalue of the compiled chunk.
Of course you do. That's not what
lua_setuservalue
does. It's for setting values associated with userdata. What you want is appropriately calledlua_setupvalue
.Using the sample code you cite, the correct answer would be:
The unofficial Lua FAQ has an entry about sandboxing in Lua. My guess is that you can transpose that logic easily enough to your C/C++ code.
See also LuaFiveTo on the lua-users wiki.
Correction
It's indeed not as trivial as it seemed. But in the end the point is simple: load your chunk, push the _ENV table, use
lua_setupvalue(L,-2,1)
. The important is that the table should be at the top of the stack.As a small example, using 2 environments defaulting to _G for reading stuff via metatables:
And for the 2 Lua files: