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.
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: