C/C++ 调用lua脚本

安装

  • 需要lua和luajit
yum install lua
yum install luajit-devel.x86_64 # luajit是嵌入lua脚本引擎
  • 示例
// fst.cc
#include 
#include 
#include 
#include 
#include 
extern "C" {
#include 
#include 
#include 
}

int main(int argc, char *argv[]) {
  std::string script_fname = __FILE__;
  script_fname = std::regex_replace(script_fname, std::regex("\\.cc"), ".lua");
  if (argc > 1) {
    script_fname = argv[1];
  }
  auto state = luaL_newstate();
  std::unique_ptr<lua_State, std::function<void(lua_State *)>> _feter(
      state, [](lua_State *s) { lua_close(s); });

  luaL_openlibs(state);
  auto err = luaL_loadfile(state, script_fname.c_str());
  if (err) {
    std::cerr << lua_tostring(state, -1) << std::endl;
    return -1;
  }
  lua_pcall(state, 0, 0, 0);
  auto s = lua_tostring(state, -1);
  std::cout << s << std::endl;
  return 0;
}

  • makefile
CC=g++
INC=/usr/include/luajit-2.1/
LIB=-lluajit-5.1

all:fst.exe

fst.exe:fst.cc
        $(CC) -o $@ -I${INC} -fPIC ${LIB} $<

clean:
        rm -f *.exe

你可能感兴趣的:(c++,lua,lua,c++)