lua-users home
lua-l archive

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



On 09/09/2006, at 6:36 AM, Jose Luis Hidalgo wrote:


  I'm not sure if what I'm going to say it's correct, but from the
manual "The environment of the running C function is always at
pseudo-index LUA_ENVIRONINDEX" I think that the lua_environindex is
only accessible when your function gets called from lua, and not when
you are creating a new state. For example:

int test(lua_State *L) {
	lua_newtable(L);
	lua_replace(L, LUA_ENVIRONINDEX);
	return 0;
}
int main(int argc, char* argv[])
{
	lua_State * L = luaL_newstate();
	luaL_openlibs(L);
	luaL_dostring(L, "print(_VERSION)"); // Lua 5.1
	lua_pushcfunction(L,test);
	lua_setglobal(L, "test");
	luaL_dostring(L, "test()");
       lua_close(L);
       return 0;
}

I think you are partly right here. However the dostring is unnecessarily complicated. Try this:

lua_pushcfunction(L,test); // the function that uses the environment - now on the stack
lua_call (L, 0, 0);         // run it as a Lua function


I also had crashes using LUA_ENVIRONINDEX until I called my initialization code this way.

- Nick