lua-users home
lua-l archive

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


D Burgess wrote:
> Can someone explain to me how one saves/restores the state
> of Lua Globals from within a C program (not via Lua script)?
> Assume I have one Lua VM executing and I wish to save the
> global state, execute a script then restore the state of
> globals to what was prior to the script execution.

In Lua 5 each closure maintains its own environment (globals.)  In
particular you can load a chunk, then set its environment to some prepared
table before execution:

    if (luaL_loadfile(L, my_script_file_name))  /* from lauxlib.h */
        lua_error(L);

    /* prepare environment */
    lua_newtable(L);
    /* add some data here ... */

    /* set it as the loaded chunk's environment
       (it will act as the chunk's table of globals) */
    lua_setfenv(L, -2);

    /* run chunk */
    lua_call(L, 0, 0);

Note that all closures that are created by the chunk will (by default)
inherit this environment and _hold on to it_ even if you store them
somewhere else.  You can read some more about environments in the manual
(see getfenv/setfenv and lua_getfenv/lua_setfenv.)

--
Wim