加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

用Lua注册一个闭包

发布时间:2020-12-15 00:16:07 所属栏目:大数据 来源:网络整理
导读:我不想使用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.
我不想使用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");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读