2016-04-13 5 views
2

私はLua C APIを使って自分のゲームエンジンを作っています。また、私はいくつかのC関数を持っLua C APIを使ってサブテーブル内に関数を挿入する

my_lib = { 
    system = { ... }, 
    keyboard = { ... }, 
    graphics = { ... }, 
    ... 
} 

、私は、そのような何かに登録したい:私はそのようなLuaのテーブルの階層を得たので、

inline static int lua_mylib_do_cool_things(lua_State *L) { 
    mylib_do_cool_things(luaL_checknumber(L, 1)); 
    return 0; 
} 

を、どのように私はmy_libサブのメンバーのようにそれを登録することができますテーブル、ちょうどそう?サブテーブルについて

inline void mylib_registerFuncAsTMem(const char *table, lua_CFunction func, const char *index) { 
    lua_getglobal(mylib_luaState, table); 
    lua_pushstring(mylib_luaState, index); 
    lua_pushcfunction(mylib_luaState, func); 
    lua_rawset(mylib_luaState, -3); 
} 

しかし、どのような:

my_lib = { 
    system = { do_cool_things, ... }, 
    keyboard = { ... } 
    graphics = { ...} 
} 

今、私は唯一のグローバルテーブルのメンバーを登録する方法を知っている、それはそのように動作しますか?

+0

[API関数が】あり(https://www.lua.org/manual/5.3/manual.html#:

int luaopen_game(lua_State *L) { lua_newtable(L); // create the module table lua_newtable(L); // create the graphics table luaL_register(L, NULL, module_graphics); // register functions into graphics table lua_setfield(L, -2, "graphics"); // add graphics table to module lua_newtable(L); // create the system table luaL_register(L, NULL, module_system); // register functions into system table lua_setfield(L, -2, "system"); // add system table to module // repeat the same process for other sub-tables return 1; // return module table } 

これは、以下の構造を有するモジュールテーブルをもたらすはずですluaL_setfuncs)は、テーブルに関数を登録する際に役立ちます。どのバージョンのLuaを使用していますか? – Adam

+0

お返事ありがとうございます。私はLua 5.1を使用しています。そこにはそのようなAPI関数がないように見えます。 –

+0

実際、この関数はLua 5.2で追加されましたが、代わりに[luaL_register](https://www.lua.org/manual/5.1/manual.html#luaL_register)を使用することができます。 – Adam

答えて

2

複数のLua C関数を(Lua 5.1を使用して)テーブルに登録する簡単な方法は、luaL_registerを使用することです。

まず、Lua関数を実装します。これらの関数は、lua_CFunctionの形式を取る必要があります。

static int graphics_draw(lua_State *L) { 
    return luaL_error(L, "graphics.draw unimplemented"); 
} 

static int system_wait(lua_State *L) { 
    return luaL_error(L, "system.wait unimplemented"); 
} 

次に、あなたのLuaの関数とその名(キー)と、各サブテーブルのluaL_Reg構造を作成します。

static const struct luaL_Reg module_graphics[] = { 
    {"draw", graphics_draw},   
    // add more graphic functions here.. 
    {NULL, NULL} // terminate the list with sentinel value 
}; 

static const struct luaL_Reg module_system[] = { 
    {"wait", system_wait},   
    {NULL, NULL} 
}; 

その後、あなたはモジュールテーブルは、各サブテーブルとregisterその機能を作成返す機能インチ

game = { 
    graphics = { 
     draw -- C function graphics_draw 
    }, 
    system = { 
     wait -- C function system_wait 
    } 
} 
+0

ありがとうございます。私が質問した後、私は解決策を自分で見つけましたが、あなたはずっと複雑です。 –

+1

あなたは大歓迎です。このパターンは、優れた[Programming in Lua](http://www.lua.org/pil/28.1.html)の本に示すように、C言語で書かれたLuaモジュールで一般的に使用されます。初版はオンラインで無料で入手できます。 – Adam

関連する問題