一直知道cocos2dx lua是經過tolua++導出lua接口的,但一直沒本身去導過,最近比較閒,試了下。java
個人環境是:ubuntu ,安裝好tolua++後就能夠在命令行下試用 tolua++ 工具導出。ios
MyClass.cpp文件:ubuntu
#include <iostream> #include "tolua++.h" class MyClass { public: void say() { std::cout << "Hello World!" << std::endl; } };
tolua++須要寫pkg文件,相似於C++的.h文件,當時要過去掉關鍵字,MyClass.pkg函數
#include "MyClass.h" class MyClass { MyClass(); ~MyClass(); void say(); };
在終端執行: 工具
tolua++ -o MyClass.cpp MyClass.pkg //-o MyClass.cpp 表示寫入MyClass.cpp 文件。
執行完後,會生成MyClass.cpp文件,打開會發現有好幾百行代碼,會有一個測試
TOLUA_API int luaopen_MyClass (lua_State* tolua_S)
的定義,而後在該文件中加入對MyClass.h文件的引用:lua
#include "string.h" #include "tolua++.h" ... #include "MyClass.h" ... TOLUA_API int luaopen_MyClass (lua_State* tolua_S) //該方法就是要導出到lua的方法
在MyClass.h文件中增長函數聲明:spa
/* Exported function */ TOLUA_API int tolua_MyClass_open (lua_State* tolua_S);
mytest.lua測試文件:命令行
local my = MyClass() my:say()
經過main.cpp 文件來執行lua。code
#include <iostream> #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "MyClass.h" TOLUA_API int tolua_MyClass_open (lua_State* tolua_S); int main() { lua_State* L = lua_open(); luaL_openlibs(L); tolua_MyClass_open(L); luaL_dofile(L, "mytest.lua"); // 執行lua腳本文件 lua_close(L); return 0; }
在終端輸入:
g++ main.cpp MyClass.cpp -llua -ldl -ltolua++ -o test_lua
-lxx爲g++的編譯規則,表示須要連接的庫文件。
結果就會打印出:hello world