lua/c开发:c-object for lua

c+lua开发中常见的实现:c库实现功能,供lua调用;

比如排行榜模块(跳表),实现方案可为:c库实现跳表(skip list)核心逻辑,提供接口供lua层中操作使用;
那么c库显然有以下的实现(伪码,演示用):

// skip list core
struct skiplist {
    // ...
};

struct skiplist * skiplist_create();
void skiplist_release(struct skiplist * instance);
// ...

// interface for lua
static int 
_new(lua_State *L) {
    struct skiplist *psl = skiplist_create(/* param */);
    struct skiplist **sl = (skiplist**) lua_newuserdata(L, sizeof(skiplist*));
    *sl = psl;
    lua_pushvalue(L, lua_upvalueindex(1));
    lua_setmetatable(L, -2);

    return 1;
}
static int
_release(lua_State *L) {
    struct skiplist **psl = lua_touserdata(L, 1);
    struct skiplist *sl = *psl;
    skiplist_release(sl);
    return 0;
}

// lib open func
int luaopen_skiplist(lua_State *L) {
    luaL_Reg l[] = {
        // ...
    };
    
    lua_createtable(L, 0, 2);

    luaL_newlib(L, l);
    lua_setfield(L, -2, "__index");
    lua_pushcfunction(L, _release);
    lua_setfield(L, -2, "__gc");

    lua_pushcclosure(L, _new, 1);
    return 1;
}

可以看到,对象在c库中创建,通过lua的full userdata保存c对象的指针,交由lua层使用,userdata设置gc元方法(调用c对象的销毁函数),在userdata被回收时正确地触发对象释放。

posted @ 2024-03-23 14:13  linxx-  阅读(12)  评论(0编辑  收藏  举报