LUA C API - 使用luaL_ref的弱引用

时间:2013-10-13 00:42:46

标签: c lua lua-table

使用以下示例:

int r = luaL_ref(L, LUA_REGISTRYINDEX);

r将强烈引用堆栈顶部的对象。

是否可以获得对堆栈顶部对象的弱引用?

我正在考虑的方法之一是创建一个具有弱值的表并将其存储在全局注册表中。然后在需要弱值时使用它。

有更简单的方法吗?

Lua 2.4在文档中有这个,但luaL_ref现在似乎有所不同。:

  

函数lua_ref创建对该对象的引用   堆栈顶部,并返回此引用。如果锁定为真,那么   对象被锁定:这意味着对象不会被垃圾回收

1 个答案:

答案 0 :(得分:1)

这是我提出的解决方案:

int create_ref(bool weak_ref)
{
    lua_newtable(L); // new_table={}

    if (weak_ref) {
        lua_newtable(L); // metatable={}            

        lua_pushliteral(L, "__mode");
        lua_pushliteral(L, "v");
        lua_rawset(L, -3); // metatable._mode='v'

        lua_setmetatable(L, -2); // setmetatable(new_table,metatable)
    }

    lua_pushvalue(L,-2); // push the previous top of stack
    lua_rawseti(L,-2,1); // new_table[1]=original value on top of the stack

    //Now new_table is on top of the stack, rest is up to you
    //Here is how you would store the reference:
    return luaL_ref(L, LUA_REGISTRYINDEX); // this pops the new_table
}

使用此功能,我可以存储弱引用和强引用。只有一个额外的表作为开销(或1 + metatable用于弱引用)。