C++与Lua交互
lua作为一门动态语言,可用来当做配置文件和实现经常变化的业务功能,很方便的实现热更新。同时lua作为一门胶水语言,配合强大的C++作逻辑支撑,程序性能高、开发效率快,犹如珠帘合璧,所向无敌。C++与lua的交互主要通过lua的虚拟栈实现,本文不打算深入讲解其中原理,只是简单记录下C++与lua的调用关系。
环境搭建
mac、linux系统:
$ wget http://www.lua.org/ftp/lua-5.2.3.tar.gz
$ tar zxf lua-5.2.3.tar.gz
$ cd lua-5.2.3
$ make posix
$ make posix install
windows系统:略
1.C++调用lua
假如当前文件夹为demo1。先创建一个lua脚本, 路径为:demo1/scripts/test.lua。脚本内容如下:
-- 全局变量
id = 666
title = "this is a test"
array = {r = 2,g = 3,b = 4}
array_1d = {2,5,26,8}
array_2d = {
{2,5},{15,18},{25,26,28},{0,5,4}}
-- 无参函数
function ruler_func()
print("[lua]: this is some thing need to tell you!!!");
end
-- 有参函数
function add_func(a,b)
print("[lua]: a("..a..") + b("..b..") ="..a+b.."!");
return a+b;
end
在当前文件夹创建C++文件demo1/demo.cpp,用来测试调用lua脚本。文件内容如下:
/*
* demo.cpp
* demo
*
* Created by Jevstein on 2018/10/16 11:30.
* Copyright @ 2018year Jevstein. All rights reserved.
*
*/
#include <iostream>
#include <string>
using namespace std;
//0.包含lua头文件
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
void call_lua_test()
{
//1.创建lua环境
lua_State *L = luaL_newstate(); //lua_open()
if (L == NULL)
{
std::cout << "[C++]: Failed to create Lua State!" << std::endl;
return;
}