这是我想出的解决方案:
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 用于弱引用)。