1.下载Lua源码,本文使用的是Lua-5.2.3,然后拷贝src下的源码,需要将lua.c、luac.c、Makefile文件删除。
2.将Lua源码引入C/C++项目中。
编译没有问题。在安卓平台编译错误的解决方法:找到Lua源码中的llex.c,将函数
static void trydecpoint (LexState *ls, SemInfo *seminfo) {
char old = ls->decpoint;
ls->decpoint = getlocaledecpoint();
buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
if (!buff2d(ls->buff, &seminfo->r)) {
/* format error with correct decimal point: no more options */
buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
lexerror(ls, "malformed number", TK_NUMBER);
}
}
中的
ls->decpoint = getlocaledecpoint();
改成
ls->decpoint = ‘.’;
3.创建Lua读取类
#ifndef __LuaAndCpp__LuaEngine__
#define __LuaAndCpp__LuaEngine__
#include <stdio.h>
#include <iostream>
#include "lua.hpp"
class LuaEngine {
public:
~LuaEngine();
static LuaEngine* getInstance();
static void destroyInstance();
private:
LuaEngine():m_pLuaState(NULL){};
void init();
std::string getFilePath(std::string fileName);
lua_State* m_pLuaState;
};
#endif /* defined(__LuaAndCpp__LuaEngine__) */
#include "LuaEngine.h"
LuaEngine::~LuaEngine(){
lua_close(m_pLuaState);
}
static LuaEngine* LuaEngine_instance = NULL;
LuaEngine* LuaEngine::getInstance(){
if (LuaEngine_instance == NULL) {
LuaEngine_instance = new LuaEngine();
LuaEngine_instance->init();
}
return LuaEngine_instance;
}
void LuaEngine::destroyInstance(){
if (LuaEngine_instance) {
delete LuaEngine_instance;
LuaEngine_instance = NULL;
}
}
void LuaEngine::init(){
m_pLuaState = luaL_newstate();
luaL_openlibs(m_pLuaState);
luaL_dofile(m_pLuaState, this->getFilePath("config.lua").c_str());
lua_pcall(m_pLuaState, 0, 0, 0);
}
std::string LuaEngine::getFilePath(std::string fileName){
return "/Users/Forest/Documents/LuaAndCpp/LuaAndCpp/scripts/" + fileName ;
}
4.测试Lua环境
创建scripts文件夹存放Lua文件
并导入项目,添加Lua文件。
在main.cpp中使用LuaEngine
#include <iostream>
#include "LuaEngine.h"
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
LuaEngine::getInstance();
LuaEngine::destroyInstance();
return 0;
}
运行结果
可见在这个C/C++项目中已经可以使用Lua了。
需要注意的是luaL_dofile()函数第二个参数需要的是Lua文件的完整路径。