用Lua注册一个闭包

我不想使用lua_CFunction签名来编写从Lua调用方法,而是想使用我自己的函数签名来简化导出过程.
void foo(call_t *call)
{
    int a;
    char *b;
    char *c;
    table_t *d;

    /* reading arguments */
    a = read_integer(call);
    b = read_string(call);

    /* do something... */

    /* writing arguments */
    write_string(call,c);
    write_table(call,d);
}

/* export to Lua */
export("foo",foo);

到目前为止,我能想到的只有一个lua_CFunction,它从表中调用包装函数.但是,我不知道如何将Lua函数与C函数和表索引相关联,以便有效地使Lua函数成为闭包.像这样的东西:

lua_register_with_data(state,"foo",base_function,FOO_INDEX);

我怎样才能做到这一点?

解决方法

毕竟我想通了.我想这证明了橡皮鸭调试的有用性.

我刚刚将基函数与实际函数索引一起注册为upvalue.

function_t table[FUNCTION_COUNT];

/* lookup function using upvalue */
int base_function(lua_State *state)
{
    int index;
    call_t call;

    call.state = state;
    call.argument_index = 1;
    call.return_count = 0;

    index = lua_tointeger(state,lua_upvalueindex(1));
    table[index](&call);

    /* return_count is incremented by write_* functions */
    return(call.return_count);

}

/* register function as closure */
table[FOO_INDEX] = foo;
lua_pushinteger(state,FOO_INDEX);
lua_pushcclosure(state,1);
lua_setglobal(state,"foo");

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...