基於 Cocos2d-x 3.2 + Lua 5.3 環境,深度剖析 tolua++ 將 C++ 類導出至 Lua 的完整流程:從 lua_State 初始化、模組/類表建立、元表設定、繼承鏈構建、函數綁定、垃圾回收閉包,到型別轉換與 .isclass 標記機制。
// 棧頂為模組表/元表 lua_pushstring(L, name); // key lua_pushcfunction(L, func); // value lua_rawset(L, -3); // table[key] = value, 彈出 key/value
lua_register_moonton_CGameFunc步驟 1:
tolua_usertype- 建立雙元表步驟 2:
tolua_newmetatable- 元表建立與初始化// 關鍵棧操作: lua_newtable(L); // 新建類表 luaL_getmetatable(L, name); // 取得元表 lua_setmetatable(L, -2); // 類表.setmetatable(元表) // 標記 .isclass = true lua_pushliteral(L, ".isclass"); lua_pushboolean(L, 1); lua_rawset(L, -3); // 存入模組:module[name] = 類表 lua_pushstring(L, lname); lua_rawset(L, -3);步驟 5:
tolua_beginmodule("CGameFunc")- 進入類模組因
.isclass == true,推入的是類表的元表,後續tolua_function綁定的方法將寫入元表 → 實例透過__index可存取。Lua 端使用效果