我不想使用lua_CFunction签名来编写从Lua调用的方法,而是想使用我自己的函数签名来简化导出过程. void foo(call_t *call){ int a; char *b; char *c; table_t *d; /* reading arguments */ a = read_integer(call); b =
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, base_function, 1);
lua_setglobal(state, "foo");
