3

使用以下示例:

int r = luaL_ref(L, LUA_REGISTRYINDEX);

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

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

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

有没有更简单的方法?

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

函数 lua_ref 创建一个对栈顶对象的引用,并返回这个引用。如果 lock 为真,则对象被锁定:这意味着对象不会被垃圾回收

4

1 回答 1

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 个额外的表作为开销(或 1+metatable 用于弱引用)。

于 2013-10-13T01:18:03.640 回答