luaplus和c++之间的代码交互

来源:互联网 发布:论文引用格式网络文章 编辑:程序博客网 时间:2024/06/07 01:42

1.需求

最近在搞一个项目时需要在程序运行时进行其中环境的改变故采用luaplus作为动态引入,实现和c++代码之间的互调

2.解决

需要下载luaplus最新代码进行编译

3.代码

mymain.cpp

#include <iostream>#include "LuaPlus.h"using namespace std;using namespace LuaPlus;class MyTest{public:    int sum(int x, int y) {return x + y;}};int LS_PrintNumber(LuaState * state){    LuaStack args(state);    int ncount = args.Count();    cout<<ncount<<endl;    for (int n = 1; n<= ncount; ++n)        cout<<args[n].GetNumber()<<endl;    return 0;}int main(){    LuaStateOwner state;    MyTest test;    //lua调用c++中的普通函数    state->GetGlobals().Register("PrintNumber", LS_PrintNumber);    //lua调用c++中的类函数    state->GetGlobals().RegisterDirect("sum", test, &MyTest::sum);    int iret = state->DoFile("test.lua");    //c++调用lua中的变量    int mytest = state->GetGlobal("health").GetInteger();    cout<<mytest<<endl;    //c++调用lua中的函数    LuaFunction<float> Add = state->GetGlobal("Add");    cout<<Add(12.34, 23.45)<<endl;    cout<<state->GetGlobal("aa").GetInteger()<<endl;    std::system("pause");    return 0;}

test.lua

--c++调用lua中定义的变量health=200;--c++调用lua中定义的函数function Add(x,y)return x+yend--lua调用c++中定义的类函数--lua调用c++中定义的普通函数PrintNumber(10, 20);aa=sum(1000, 2000);

4.备注

1.在win7+vs2010+win32命令行下编译通过

2.完整代码http://download.csdn.net/detail/zhang_ruiqiang/9030679

0 0
原创粉丝点击