lua-users home
lua-l archive

Re: how to get environment in which a C function was called?

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


Nevermind, I remember now. The environment of a C function is set at creation time. I'm calling back from C after the chunk has run. I can achieve what I need by lua_replace(L, LUA_GLOBALSINDEX) instead of lua_setfenv(L, -2) in the C code.
On Feb 27, 2007, at 1:44 AM, Graham Wakefield wrote:
I'm looking for the equivalent of getfenv(1) in the C API, to find out in what environment a function that in turn calls C was called.
say I have a function:
function test()
	print("my calling environment", getfenv(1))
	cprintenv()
end
cprintenv is a lua_CFunction:
int cprintenv(lua_State * L)
{
	printf("LUA_ENVIRONINDEX %p\n", lua_topointer(L, LUA_ENVIRONINDEX));
}
now if I call in C:
lua_getglobal(L, "test");
// create a new environment table
lua_newtable(L);
printf("new environment table %p\n", lua_topointer(L, LUA_ENVIRONINDEX));
lua_pushstring(L, "__index");
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_settable(L, -3);
// setfenv(test)
lua_setfenv(L, -2);
// call it
lua_pcall(L, 0, 0, 0);
The result is that the current environment as stated in C (LUA_ENVIRONINDEX) is the global table, not the current environment (the new table applied to the function test). If this is expected behaviour, then how can I get the current environment in which a lua_CFunction was called, the equivalent of getfenv(1) in the C API?
Thanks.

AltStyle によって変換されたページ (->オリジナル) /