gpt4 book ai didi

c - 使用 Lua 注册一个闭包

转载 作者:太空狗 更新时间:2023-10-29 15:04:08 24 4
gpt4 key购买 nike

我不想使用 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);

我怎样才能做到这一点?

最佳答案

我终于明白了。我想这证明了橡皮鸭调试是多么有用。

我只是将基本函数与实际函数索引一起注册为上值。

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, base_function, 1);
lua_setglobal(state, "foo");

关于c - 使用 Lua 注册一个闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com