C++调用lua

来源:互联网 发布:cdrx8软件下载 免费 编辑:程序博客网 时间:2024/05/29 18:01

C++ 调用lua,下面是一个简单的例子更多请看参考。

我使用的是lua 5.3版本。lua 5.2 去掉了luaL_register功能,也就没弄lua调用C++函数。这个有时间在搞一下

参考: http://www.jellythink.com/archives/882 

用vs2013去搭建编译lua的工程稍微麻烦,我就选用了开源的codeblocks来调试整个工程。

新建一个console application,然后将lua 5.3的源码放到lua53目录下,main.cpp在src目录下。




下面的例子,是创建一个新的lua文件,并将代码写入到lua文件中。然后再从c++中读取这个lua文件,执行lua中的函数。

#include <iostream>#include <string.h>#include <fstream>extern "C"{    #include "../lua53/lua.h"    #include "../lua53/lauxlib.h"    #include "../lua53/lualib.h"}using namespace std;void writeCfg(){    ofstream examplefile("config.lua");    if (examplefile.is_open())    {        examplefile << "width = 200\n";        examplefile << "height = 3203\n";        examplefile << "function add(a, b)\n";        examplefile << "\treturn a+b\n";        examplefile << "end\n";        examplefile.close();    }}// C++ call luaint loadCfg(){    lua_State *L = luaL_newstate();    if(!L) return -1;    int bRet = luaL_loadfile(L, "config.lua");    if( bRet ) return -2;    bRet = lua_pcall(L, 0,0,0);    if( bRet ) return -3;    lua_getglobal(L, "width");lua_getglobal(L, "height");if (!lua_isnumber(L, -2)) return -4;if (!lua_isnumber(L, -1)) return -5;int iWindowHeight = lua_tointeger(L, -1);int iWindowWidth = lua_tointeger(L, -2);    cout<<iWindowHeight <<" " << iWindowWidth<<"\n";    return 1;}void loadFunc(){    lua_State *L = luaL_newstate();if (!L)return ;int iRet = luaL_loadfile(L, "config.lua");if (iRet){const char *pErrorMsg = lua_tostring(L, -1);cout << pErrorMsg << endl;lua_close(L);}luaL_openlibs(L);iRet = lua_pcall(L, 0, 0, 0);if (iRet){const char *pErrorMsg = lua_tostring(L, -1);cout << pErrorMsg << endl;lua_close(L);return ;}    lua_getglobal(L, "add"); // 获取函数,压入栈中    lua_pushnumber(L, 10); // 压入第一个参数    lua_pushnumber(L, 20); // 压入第二个参数    // 完成调用    iRet = lua_pcall(L, 2, 1, 0);    if (iRet)    {        const char *pErrorMsg = lua_tostring(L, -1);        cout << pErrorMsg << endl;        lua_close(L);        return;    }    // 获得计算结果    iRet = lua_isnumber(L, -1);    if (!iRet)    {        cout << "Error occured." << endl;        lua_close(L);        return;    }    double fValue = lua_tonumber(L, -1);    cout << "Result is " << fValue << endl;}int main(){    writeCfg();cout<<loadCfg()<<endl;    loadFunc();    return 0;}


工程中的样子



运行结果:

3203 200

1
Result is 30

0 0
原创粉丝点击