首先你要安装lua的dev,安装很简单:
yum install lua-devel
即可,很多linux系统自带lua但是没有dev,有点小坑。
下面是lua文件,里面就两个函数:
function add(a, b) return a + b endfunction hello() print("hello lua!!!")end
之后是cpp文件的调用代码:
#include<iostream>#include<string>using std::cout;using std::endl;using std::string;//extern的意义,将下面文件当成c风格文件使用extern "c"{ #include<lua.h> #include<lauxlib.h> #include<lualib.h>}int main(){ //创建环境 lua_state *l = lual_newstate(); if(l == null) { cout << "state error" << endl; return -1; } //加载库 lual_openlibs(l); const string file = "func.lua"; // 加载文件 int ret = lual_dofile(l, file.c_str()); if(ret) { cout << "dofile error" << endl; return -1; } //hello函数没有参数,直接调用 lua_getglobal(l, "hello"); lua_pcall(l, 0, 0, 0); //三个0含义,0实参,0返回值,0自定义错误处理 lua_getglobal(l, "add"); //向add函数传入两个参数,这里直接传了1和2,传变量也ok lua_pushnumber(l, 1); lua_pushnumber(l, 2); lua_pcall(l,2,1,0); //返回值被放在-1的位置上 cout << lua_tonumber(l, -1) << endl; lua_close(l); return 0;}
最后,还有很关键的一步,编译时,我们需要加上附加选项:
g++ main.cpp -o main -llua -ldl
看看结果:
大功告成
相关推荐:
记第一次lua和c互相调用的例子
lua与c语言互相调用
c++如何调用php的函数
以上就是一招搞定c++调用lua代码配置文件函数(附代码)的详细内容。
