lua-users home
lua-l archive

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


Doug Currie wrote:
> On Wednesday, December 19, 2007 Mike Pall wrote:
> 
>> Doug Currie wrote:
>>> - use lua_replace(L, LUA_ENVIRONINDEX) followed by luaL_register()
>>> and then, if you are paranoid about leaking your environment, as I
>>> am, use lua_pushnil(L); lua_replace(L, LUA_ENVIRONINDEX) to hide it
> 
>> Wrong. The environment must be a valid table. You're storing random
>> data this way. Turn on assertions for the C API and it'll complain in
>> lua_replace at api_check(L, ttistable(L->top - 1)).
> 
> Yikes, thanks Mike. That's what I get for not looking at my code
> before posting. Instead of lua_pushnil(L) use lua_newtable(L). 

If your intent was to avoid a memory leak (as opposed to a security
leak), the only case where there is a leak is when the module gets
unloaded (and its table collected) while the module loader function is
still referenced somewhere (like in package.preload). With this
lua_newtable you have a new useless table, so you're actually using up
more memory than before (and arguably a little less once the module get
unloaded, but that empty tables stays there).

Instead you should save the original environment on the stack, do your
temporary environment replacing, and then restore the old environment,
which may be shared.