在C/C++项目中集成Lua

11 篇文章 0 订阅

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文件的完整路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值