2014-02-23 58 views
5

而不是使用lua_CFunction簽名寫入方法從Lua調用,我想使用我自己的函數簽名,簡化了導出過程。註冊與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); 

我該如何做到這一點?

回答

4

我想通了。我想這證明橡皮鴨調試是多麼有用。

我只是將基函數和實際函數索引一起註冊爲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"); 
+2

您可以通過推送實際數據來消除'table':lua_pushlightuserdata(L,(const void *)foo)'。然後用'function_t foo = lua_topointer(L,i)'取回它。 – user3125367

+0

+1好的解決方案謝謝發佈 – Schollii