gpt4 book ai didi

c - LUA C API - luaL_ref 的弱引用

转载 作者:行者123 更新时间:2023-12-02 22:57:15 30 4
gpt4 key购买 nike

使用以下示例:

int r = luaL_ref(L, LUA_REGISTRYINDEX);

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

是否可以获取对栈顶对象的弱引用?

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

有没有更简单的方法?

Lua 2.4 的文档中有此内容,但 luaL_ref 现在似乎工作方式有所不同。:

The function lua_ref creates a reference to the object which is on the top of the stack, and returns this reference. If lock is true, the object is locked: that means the object will not be garbage collected

最佳答案

这是我想出的解决方案:

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+元表用于弱引用)。

关于c - LUA C API - luaL_ref 的弱引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340662/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com