config.lua
test_table = {
name = 'app',
age = 13
}
//
// LuaEngine.h
// LuaAndCpp
//
#ifndef __LuaAndCpp__LuaEngine__
#define __LuaAndCpp__LuaEngine__
#include <stdio.h>
#include <iostream>
#include "lua.hpp"
class LuaEngine {
public:
~LuaEngine();
static LuaEngine* getInstance();
static void destroyInstance();
// 遍历table
void readTestTable();
// 得到table的key value
void getTableInfo();
private:
LuaEngine():m_pLuaState(NULL){};
void init();
std::string getFilePath(std::string fileName);
lua_State* m_pLuaState;
char* getFiled(lua_State* L,const char* key);
int table_next(int idx,char*& key,char*& value);
};
#endif /* defined(__LuaAndCpp__LuaEngine__) */
//
// LuaEngine.cpp
// LuaAndCpp
//
#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());
}
std::string LuaEngine::getFilePath(std::string fileName){
return "/Users/Forest/Documents/LuaAndCpp/LuaAndCpp/scripts/" + fileName ;
}
// 遍历table
void LuaEngine::readTestTable(){
lua_getglobal(m_pLuaState, "test_table");
if (lua_istable(m_pLuaState, -1)) {
char* name = this->getFiled(m_pLuaState, "name");
char* age = this->getFiled(m_pLuaState, "age");
int n_age = atoi(age);
std::cout << "name = " << name << "\n" << "age = " << n_age << std::endl;
}
}
char* LuaEngine::getFiled(lua_State *L, const char *key){
// char* rlt = NULL;
lua_pushstring(L , key);
lua_gettable(L, -2);
if (lua_isstring(L, -1)) {
char* rlt = (char*)lua_tostring(L, -1);
lua_pop(L, 1);
return rlt;
}
return NULL;
}
// 得到table的key value
void LuaEngine::getTableInfo(){
int t_idx = 0;
char* key = NULL;
char* value = NULL;
lua_getglobal(m_pLuaState, "test_table");
t_idx = lua_gettop(m_pLuaState);
lua_pushnil(m_pLuaState);
while (this->table_next(1,key,value) != 0) {
std::cout << "key = " << key << "\n" << "value = " << value << std::endl;
}
}
int LuaEngine::table_next(int idx,char*& key,char*& value){
if (lua_next(m_pLuaState, idx) != 0) {
key = (char*)lua_tostring(m_pLuaState, -2);
value = (char*)lua_tostring(m_pLuaState, -1);
lua_pop(m_pLuaState, 1);
return 1;
}
return 0;
}
//
// main.cpp
// LuaAndCpp
//
#include <iostream>
#include "LuaEngine.h"
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
LuaEngine* luaEngine = LuaEngine::getInstance();
luaEngine->readTestTable();
luaEngine->getTableInfo();
LuaEngine::destroyInstance();
return 0;
}
运行结果:
name = app
age = 13
key = name
value = app
key = age
value = 13