2013-04-16 104 views
0

比方說,我有一個回叫函數,當指定玩家死亡時執行該函數。將C函數轉換爲Lua函數

function OnPlayerDeath(playerid) 

end 

我想被稱爲Lua的C模塊中內部此功能,而不把它LUA腳本里面:

static int l_OnPlayerConnect (lua_State * L) { 
    enum { lc_nformalargs = 1 }; 
    lua_settop(L,1); 

    // so here I can use playerid argument - 1 arg 

    return 0; 
} 

這在某種程度上可以接收C這個回調參數?

#define LUA extern "C" __declspec(dllexport) int __cdecl 

LUA luaopen_mymodule(lua_State *L) 
{ 
    /* function OnPlayerConnect(playerid) 
    *  
    * end */ 
    lua_pushcfunction(L,l_OnPlayerConnect); 
    lua_setfield(L,LUA_GLOBALSINDEX,"OnPlayerConnect"); //there's already OnPlayerConnect I just want to also call it here but I don't know how. 
    assert(lua_gettop(L) - lc_nextra == 0); 

    return 1; 
} 

我不想把這個函數推到lua棧上,因爲這個func已經存在。 我只是希望它已經是現有的Lua功能。

回答

0

已解決。這可能是W.B.

解決方案:從C調用負載字符串。

+0

正確,但是推動堆棧上的函數/塊... –

1

如果您想從C API的Lua中運行它,您需要以某種方式將它推到堆棧上。如果它已經存在於全局表中某處,可以通過調用lua_getglobal來進行推送。 lua_call(lua_pcall)要求在調用之前調用函數並將其參數存放在堆棧頂部。

如果你喜歡它,你可以檢查LuaJIT ffi回調功能,但它不是簡單的Lua。