前言
1 QT 编译器
2 LINUX
3 Lua 5.3.5
安装
官网下载最新版本
使用 yum 指令的 linux 版本 可以参考这篇
添加环境(针对 QT)
- Pro 环境中添加库
LIBS += /home/xx/liblua.a -ldl #我这里直接加到这里,makefile 请参考直接编译链接
INCLUDEPATH += /home/xx/lua-5.3.5/src
说明:
1 LIBS 指明 lua 库的位置,我放在 main.c 同一个文件夹
2 -ldl 这是 Linux 环境需要编译的时候添加
直接编译请参考 makefile
https://github.com/ejoy/ejoy2d/blob/master/Makefile#L107
直接编译 gcc -o a main.c -llua -lm -ldl
应对这个错误
PANIC: unprotected error in call to Lua API (attempt to call a nil value)
3 INCLUDEPATH 不一定需要如果能够检索到 lua.h 就不用加
例程
filePath: test.lua
#!/usr/local/bin/lua
function show_name()
printf("hello world!")
end
function count(a, b)
return a+b
end
filePath: main.c
#include <stdio.h>
#include <QtDebug>
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
int main() {
lua_State* L = luaL_newState();
luaL_openlibs(L);
luaL_loadfile(L, "qrc:/test.lua"); //文件路径一开始写绝对路径就好 /home/xx/test.lua
luaL_pcall(L, 0, 0, 0);// 这个很有趣,在实际测试中提前先使用这个函数,后面 lua 才能功能正常,可以自行尝试(暂只在 QT 测试并遇到该问题)
lua_getglobal(L, "show_name");
luaL_pcall(L, 0, 0, 0); //无返回,无输入得用这个
lua_getglobal(L, "count");
lua_pushnumber(L, 1);
lua_pushnumber(L, 2);
lua_call(L, 2, 1); //2 个参数, 1 个返回
qDebug() << lua_tonumber(L, -1);// 自行用其它打印也行
lua_pop(L, -1);//具体看文档
lua_close(L);
return 0;
}
输出 output:
hello world!
3