首先是准备工作:
1、下载一个tolua++和lua。
2、在VS中配置引用。
,
注意:以上配置的路径一定保证正确,这些只是我的路径。
接下来就是准备写代码了。
1、在win下创建一个bat文件,用于使用tolua++ 的exe,这个只是替代功能,酷爱命令行的朋友也可以通过命令行进入tolua++.ext执行。
..\..\tolua++-1.0.93\bin\tolua++ -n export -o ..\lua_opearation.cpp Opearation.pkg
pause
2、c++中类的声明和创建。(附上.h的代码)
#ifndef __TestClass___Operation__ #define __TestClass___Operation__ #include <iostream> int getValue(); class Opearation{ int num; public: static Opearation* getInstance(); int subNum; Opearation(); ~Opearation(); int Add(int a, int b); const char* Add(int a, const char* str); const char* Add(const char * str1, const char * str2); }; #endif /* defined(__TestClass___Operation__) */
3、接下来创建一个.pkg文件
#include "Operation.h" int getValue(); class Opearation { int subNum; Opearation(); ~Opearation(); int Add(int a, int b); const char* Add @ Add2(int a, const char* str); const char* Add @ Add3(const char * str1, const char * str2); static Opearation* getInstance(); };
4、执行上面创建好的.bat文件,一定要注意路径的问题,执行完之后会生成一个.cpp文件。就可以用了。
5、创建lua调用。
a = 1; print("goto lua"); -- local b = addN(2, 5, 7) -- print(b) print("result::" ..addN(1,2,3)) local exp = Opearation:new();--首先实例化一个全局对象。(这个new方法,之前我一直很困惑,但是你仔细研究的话就会发现我们通过tolua++生成的那个文件中已经帮我们创建好了这个new方法) function foo(a, b) return exp:Add(a,b); end function numAddStr(a, b) return exp:Add2(a,b); end
6、在main中进行测试。
extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" }; #include "Operation.h" #include "tolua++.h" #include "lua_call.hpp" //使用模板技术对C++调用lua函数进行包装,使用方法参见_tmain //对于自定义的数据类型,需要特化push_value,及value_extractor两个接口。 template<> void lua_function_base::push_value(TstNS::RECT rc) { void* tolua_obj = Mtolua_new((TstNS::RECT)(rc)); tolua_pushusertype(m_vm,tolua_obj,"TstNS::RECT"); tolua_register_gc(m_vm,lua_gettop(m_vm)); } template <> TstNS::RECT lua_function_base::value_extractor() { TstNS::RECT * val = (TstNS::RECT *) tolua_tousertype(m_vm, -1,0); lua_pop(m_vm, 1); return *val; } //以上是某位大神在博客中说的,我没仔细研究过。 void CallLua(lua_State * L) { lua_function<int> foo(L,"foo"); int sum=foo(5,6); printf("%d\n", sum); } int main(int argc, const char * argv[]) { // insert code here... lua_State * L= luaL_newstate(); if(! L) { perror("luaL_newstate failed"); return -1; } luaL_openlibs(L); tolua_export_open(L);//这个一定要注意,这个是之前我们不使用tolua++的时候将全局方法加载到表中的操作,不妨到时候点开看看。 if(luaL_dofile(L, "lua\\useClass.lua")) { perror("loadfile failed"); system("pause"); return -1; } CallLua(L); lua_close(L); printf("abc\n"); system("pause"); return 0; }
注意:L需用作全局变量,也就是lua_function析构的时候L必须存在。好奇的话可以试试把CallLua中的代码直接贴到main方法中试试。
以上是我的学习总结,有许多言辞不太恰当的地方,欢迎纠正,不喜勿喷。
文章来源: 使用tolua++实现lua和c++的互调