lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2007/1/21, Zé Pedro <zarroba@gmail.com>:
I've seen a similar question already answered in the list but I'm not sure
it applies to my problem.
In my program I'm executing lua code made by users and I have no control
over it. What I'm doing now is setting the variables the code needs by
doing:
                     lua_pushinteger(pLuaState, (int)atoi(value.c_str()));
                     lua_setglobal(pLuaState, name.c_str());

and then executing the script doing:
                     luaL_dostring (pLuaState, script.c_str())

the thing is that the script has no functions or anything, just calls to
methods and declaration of variables. Once a script is executed the
variables should be cleared but this must be made in C after the
luaL_dostring call. Is there any way to do this or do I have to create a new
LuaState for each time I execute a script?

You can set an environment table to your code snippet containing your
variables, and with an index metamethod pointing to globals to still
have access to globals. This will also prevent your snippets from
creating new globals. Example (not tested):

// Create a table holding your variables
lua_newtable(pLuaState);
// Put your variables in it instead of global table
lua_pushinteger(pLuaState, (int)atoi(value.c_str()));
lua_setfield(pLuaState, -2, name.c_str());
// Repeat last two steps for each variable

// Optionnal: make your variable table point to globals to be able to
// access globals from your scripts.
// Create a metatable
lua_newtable(pLuaState);
// Push a reference to globals
lua_pushvalue(pLuaState, LUA_GLOBALSINDEX);
// Set it as index metamethod
lua_setfield(pLuaState, -2, "__index");
// Set it as metatable of your variable table
lua_setmetatable(pLuaState, -2);

// Load the script without executing it
luaL_loadstring(pLuaState, script.c_str());
// Swap variable table and script
lua_insert(pLuaState, -2);
// Affect table as script environment
lua_setfenv(pLuaState, -2);
// Execute the script
lua_pcall(L, 0, LUA_MULTRET, 0);

// To clean things up just removes references to the compiled script on
// the stack, which will remove references to its environment table and
// then release your variable table to the GC.