根据lua源码,编译生成lua.lib,并在工程中使用lua静态库作为lua脚本的运行。
0.准备
使用的QT版本 Lua源码版本
1.根据lua编译Lua静态库
1.1 新建QT工程,将lua源码添加到工程中。
1.2 修改.pro文件,如下所示。
1.3 Release模式下编译
1.4 生成lib文件
在工程的Release文件夹下出现.lib文件。
到此,已经生成lua的静态库文件,可以在后续使用lua的程序中调用此库文件,切换为debug模式,重新编译,生成调试版的lib文件。
2. 工程中使用lua
2.1 工程中添加如下Lua文件,其中 libLua.lib和libLuad.lib分别为第一部分中在Release和Debug模式下编译的,为的是在工程中使用Lua的Release和Debug模式。
2.2 脚本文件初始化
/**
*
*/
Script::Script(QWidget *parent) : QWidget(parent), ui(new Ui::Script)
{
ui->setupUi(this);
//! 1. Init luaVM
this->InitLuaVM();
//! 2. Reg C API.
this->RegCAPI();
//! 3. Start time.
this->InitTimer();
}
2.3 初始胡Lua虚拟机
/**
* Initialize luaVM.
*
*/
void Script::InitLuaVM(void)
{
//! 1. Data intialize.
this->EnLuaVM = 1;
this->LuaRet = 0;
this->LuaChunkRef = 0;
//! 2. Open and LuaVM initialize.
this->LuaVM = luaL_newstate(); //! Ceate a lua machine.
luaL_openlibs(this->LuaVM); //! Load lua lib.
//! 3. Load Main.lua.
this->LoadMainLua();
}
2.4 设置exe调用的lua文件名和路径
/**
* Load main.lua.
* this->LuaVM must be created.
*
*/
void Script::LoadMainLua(void)
{
//! 1. Get mainlua file path.
QString MainLuaFilePath = QCoreApplication::applicationDirPath() + "/script/main.lua";
this->ui->textBrowserError_2->setText(MainLuaFilePath);
//! 2. Use GB18030 convert Luafilepath to localPath.
QTextCodec* codec = QTextCodec::codecForName("GB18030"); // Windows chinese code.
QByteArray GB18030MainLuaFilePath = codec->fromUnicode(MainLuaFilePath);
//! 3. Load file in path.
this->LuaRet = luaL_loadfile(this->LuaVM, GB18030MainLuaFilePath.constData());
if (this->LuaRet == 0)
{
this->LuaChunkRef = luaL_ref(this->LuaVM, LUA_REGISTRYINDEX);
}
}
2.5 注册Lua虚拟机中使用的C函数,也就是在.lua文件中使用的C实现的函数。
2.6 根据应用程序的逻辑,决定什么时间调用一次Lua文件,此处为间隔100ms调用一次。
/**
* Period timer, 100ms.
*
*/
void Script::TickProcess(void)
{
//! 1. Tick cnt.
this->TickCnt += 100;
//! 2. Run man.lua again.
lua_rawgeti(this->LuaVM, LUA_REGISTRYINDEX, this->LuaChunkRef);
this->LuaRet = lua_pcall(this->LuaVM, 0, LUA_MULTRET, 0);
//! 3.
if (this->LuaRet == 0)
{
this->ui->textBrowserError->clear();
}
else //Something error.
{
unsigned int ErrorLength = 0;
QString textBrowserMsg = this->ui->textBrowserError->toPlainText();
QString LuaVMError = lua_tolstring(this->LuaVM, -1, &ErrorLength);
if (textBrowserMsg != LuaVMError)
{
this->ui->textBrowserError->setText(LuaVMError);
}
}
}
2.7 编译,生成.exe文件,此时生成的exe文件可以调用lua脚本。
3 编写lua脚本
3.1 将lua文件和exe文件,根据程序中的路径放好。点击运行即可在exe中调用main.lua。