lua-users home
lua-l archive

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

On Wed, May 13, 2009 at 12:32:02PM -0700, Martin, Marcus wrote:
> My issue is that the globals I declare in C and push to the
> thread stack are always nil when used in the lua script, but
> have the correct value when I retrieve them from C methods. Can
> someone tell me what I am doing wrong?

All Lua functions have their own global environment. From
section 3.2 in the Lua manual:

| Non-nested Lua functions (created by loadfile, loadstring or
| load) are created sharing the environment of the creating
| thread. Nested Lua functions are created sharing the environment
| of the creating Lua function.

This means that when you loadfile(L,...) foo.lua, it gets thread
L's global environment, and every time you pcall the returned
function, it will create Main in L with L as global environment,
unless you call lua_setfenv to change its environment before the

So you will have to create a unique Main function for each
thread if they shall all have different global environments.

To do this you only need to call lua_loadfile once. Then you can
move the function to the new thread with lua_xmove (after
leaving a copy on the original stack), change its environment
with lua_setfenv, and run it with lua_pcall to create the Main
and other functions in the new environment.

Tommy Pettersson <>