注册和Lua封闭 [英] Registering a closure with Lua

查看:140
本文介绍了注册和Lua封闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是使用写入方法lua_CFunction签名,以从Lua调用,我想用我自己的函数签名简化了出口程序。

Instead of using the lua_CFunction signature for writing methods to be called from Lua, I'd like to use my own function signature that simplifies the export process.

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中发挥作用的封闭一个Lua函数C函数和表索引关联。事情是这样的:

So far, all I can think of doing is having a single lua_CFunction that calls the wrapper function from a table. However, I don't know how to associate a Lua function with a C function and table index so as to effectively make the Lua function a closure. Something like this:

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

我怎样才能做到这一点?

How can I make this happen?

推荐答案

我想它毕竟。我想这证明了橡皮鸭子调试是多么有用。

I figured it out after all. I guess this proves how useful rubber duck debugging is.

我刚刚注册的基础功能与实际功能指标作为沿的upvalue

I just registered the base function along with the actual function index as an 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");

这篇关于注册和Lua封闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆