lua-users home
lua-l archive

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

I am reading the docs over and over and I do not see how I am supposed
to see if the userdata has it's own environment table...

I see that "userdata and C functions are created sharing the environment
of the creating C function" and that "the environment of the running C
function is always at pseudo-index LUA_ENVIRONINDEX".

So my guess is to do this:

// ... <userdata>
lua_getfenv(L, -1);
// ... <userdata> <env>
if (lua_rawequal(L, -1, LUA_ENVIRONINDEX) {
   // does not have it's own env table

Is this ok ?

You're right in that *every* userdata in Lua has an environment table. If you want to compare it with LUA_ENVIRONINDEX you should make sure all your C functions share this same environment.

I solved this in my Lua/APR binding by initializing all userdata with a default environment (shared between all userdata created by Lua/APR). When I want a userdata to have a unique environment I check whether the current environment is the same table as the shared environment, if it is then I create a new table and set that as the environment:

This might not be the most efficient approach but it seemed the least error prone solution to me.

 - Peter Odding