如何防止 C API 注册表中的 Lua 回调被垃圾回收?

How to prevent a Lua callback, in the C API's registry, from being garbage collected?

本文关键字:回调 Lua 何防止 API 注册表      更新时间:2023-10-16

我在我的C程序中使用了LUA 5.3回调系统。LUA脚本仅运行一次,以注册回调。我想防止回调为GC,而不会完全禁用GC。

回调代码:

LuaEventHandler* presentEvent = FindLuaEvent("present");
if (presentEvent != NULL) {
    lua_rawgeti(lState, LUA_REGISTRYINDEX, presentEvent->luaFuncRef);
    lua_pushvalue(lState, 1);
    lua_pcall(lState, 0, 0, 0);
    //presentEvent->luaFuncRef = luaL_ref(lState, LUA_REGISTRYINDEX);
}

回调添加代码:

LUACFUNCTION(RegisterCallbackLua) {
    int ref = luaL_ref(lState, LUA_REGISTRYINDEX);
    const char* name = luaL_checkstring(lState, 1);
    RegisterLuaEvent(ref, name);
    return 0;
}
LuaEventHandler* RegisterLuaEvent(int pLuaFuncRef, const char* pEventName) {
    LuaEventHandler* eventHandler = new LuaEventHandler();
    eventHandler->luaFuncRef = pLuaFuncRef;
    eventHandler->eventName = pEventName;
    printf("Callback registered: %sn", pEventName);
    for (int i = 0; i < 64; i++) {
        if (luaEventHandlerList[i] != 0)
            continue;
        luaEventHandlerList[i] = eventHandler;
        break;
    }
    return eventHandler;
}

问题是不良内存管理。

luaeventhandlerlist应该是VEC,我直接引用LUA字符串,等等