我将尝试使用C API将函数值存储在弱表中,以创建GC终结器。我开始先在纯Lua 5.2中编写了一个原型:
local function myfinalizer()
print 'Called finalizer'
end
function myfunc()
print 'Called myfunc'
end
local sentinels = setmetatable({}, { __mode='k' })
sentinels[myfunc] = setmetatable({}, { __gc=myfinalizer })
myfunc()
myfunc = nil
collectgarbage 'collect'
print 'Closing Lua'
输出结果:
Called myfunc
Called finalizer
Closing Lua
原型似乎按预期工作。以下是C版本:
#include <stdlib.h>
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
static int my_finalizer(lua_State *L)
{
puts("Called finalizer");
return 0;
}
static int my_func(lua_State *L)
{
puts("Called myfunc");
return 0;
}
int main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// create sentinels table (weak keys) in registry
lua_newtable(L); // t
lua_newtable(L); // t mt
lua_pushstring(L, "k"); // t mt v
lua_setfield(L, -2, "__mode"); // t mt
lua_setmetatable(L, -2); // t
lua_setfield(L, LUA_REGISTRYINDEX, "sentinels"); //
// push global function and register as sentinel
lua_pushcfunction(L, my_func); // f
lua_getfield(L, LUA_REGISTRYINDEX, "sentinels"); // f t
lua_pushvalue(L, 1); // f t k
lua_newuserdata(L, 0); // f t k v
lua_newtable(L); // f t k v mt
lua_pushcfunction(L, my_finalizer); // f t k v mt v
lua_setfield(L, -2, "__gc"); // f t k v mt
lua_setmetatable(L, -2); // f t k v
lua_settable(L, -3); // f t
lua_pop(L, 1); // f
lua_setglobal(L, "myfunc"); //
// execute test script and exit
if (luaL_dostring(L, "myfunc(); myfunc=nil; collectgarbage'collect'")) {
printf("Error: %s\n", lua_tostring(L, -1));
}
lua_gc(L, LUA_GCCOLLECT, 0); // suggestion: two full gc cycles
fflush(stdout); // suggestion: immediate flush
puts("Closing Lua");
lua_close(L);
fflush(stdout);
return EXIT_SUCCESS;
}
使用以下编译:
$ gcc -std=c99 -Wall -Werror -pedantic -O2 -o main main.c -ldl -llua52 -lm
输出结果:
Called myfunc
Closing Lua
Called finalizer
这个C语言版本有一些小的区别:
- 我将局部变量表
sentinels
存储在注册表中。 - 使用零大小的用户数据代替带有
__gc
元方法的表作为哨兵值。
我不明白为什么在运行完全收集周期后,C语言版本中的 myfunc
终结器没有执行。我做错了什么?
luaL_dostring
返回后添加了lua_gc(L, 0, LUA_GCCOLLECT)
,以及将 userdata 替换为 table,但结果仍然相同。 - Adam$ gcc -std=c99 -Wall -Werror -pedantic -O2 -o main main.c -llua52 -ldl -lm
,因为在较新版本的GCC中,链接参数的顺序很重要。 - Kamiccolo