简体   繁体   中英

lua_unref on object being used in Lua

In the Lua manual we read:

A reference is a unique integer key. As long as you do not manually add integer keys into table t, luaL_ref ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r by calling lua_rawgeti(L, t, r). Function luaL_unref frees a reference and its associated object .

Suppose I create a reference to an object, push it onto the API stack, save it under a global variable, and then call luaL_unref .... does it get freed despite being pointed to in Lua?

Example code:

lua_newtable( L );
int index = luaL_ref( L, LUA_REGISTRYINDEX );
lua_rawgeti( L, LUA_REGISTRYINDEX, index );
lua_setglobal( L, "test" );
luaL_unref( L, LUA_REGISTRYINDEX, index );   
lua_getglobal( L, "test" ); // ...?

It would be.

Lua Registry is merely a table. No magic here.

So, your code is roughly equivalent to following (with exception of how lua_ref works with indices):

local t = { }
local index = #_R + 1 -- Assume that fictional _R is registry
_R[index] = t
_G["test"] = t -- Non-fictional _G is a global environment
_R[index] = nil

Also, note that your example does not make much sense. (I assume that it is oversimplified.) You don't need to put table into a registry before saving it as a global variable.

For your "unreferenced" table to be destroyed, you need GC to kick in. It cannot kick in between lua_newtable and lua_setglobal , if you call them one after another without returning control to Lua inbetween. Until you return control to Lua, your table is "referenced" in the Lua stack.

No, it is not explicitly freed.

I think there may be some confusion between the question and the previous answer. The luaL_unref function merely unreferences the object, it does not actually perform a free operation. So if a variable still references the object it remains alive and is not freed.

The problem is with the wording of the reference. The associated object is "freed from the registry" but it is not "freed from the memory system".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM