首先你要安装lua的dev,安装很简单:
yum install lua-devel
即可,很多Linux系统自带Lua但是没有dev,有点小坑。
function add(a, b) return a + b end function hello() print(Hello Lua!!!) end
#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
看看结果:
大功告成
相关推荐:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。