C++与lua如何互相调用

2020年10月15日 4408点热度 4人点赞 0条评论

搭建lua开发环境

  • 下载lua的源代码 https://www.lua.org/
  • 下载好之后,将源代码直接加入自己的工程。

C++调用lua代码

在C++中调用lua代码主要有以下几个步骤

  1. 使用luaL_newstate()函数创建一个lua虚拟机。
  2. 使用luaL_openlib()函数载入lua基本库。
  3. 使用luaL _dostring()或者luaL_dofile()载入一个lua脚本。
  4. 使用lua_getglobal()将脚本中的全局变量压入栈,如果传入的是函数名那则相当于将函数指针压入栈顶。
  5. 调用栈中的数据。
  • C++代码
extern "C"{
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
}
#include <iostream>

int main(){
//初始化lua虚拟机
lua_State * L= nullptr;
L = luaL_newstate();

//载入lua基本库
luaL_openlibs(L);

//载入lua脚本
auto str = ui->textEdit->toPlainText();
std::string stdStr = str.toStdString();
luaL_dostring(L,stdStr.c_str());

//获取一个全局变量的值
lua_getglobal(L,"name");
std::string name = lua_tostring(L,-1);
std::cout << "name:" <

//调用一个无参数无返回的lua函数
lua_getglobal(L,"hello");
lua_call(L,0,0);

//调用一个有参数的lua函数
lua_getglobal(L,"say");
lua_pushstring(L,"C++ NB");
lua_call(L,1,0);

//调用一个有参数有返回的函数
lua_getglobal(L,"add");
//将参数从左到右依次压入栈
lua_pushinteger(L,7);
lua_pushinteger(L,3);
lua_call(L,2,1);

//获取返回值
int add = lua_tointeger(L,-1);
std::cout << "7 + 3 = " << add << std::endl;

lua_close(L);
return 0;
}
  • lua代码
name = "C++";
function hello()
print("hello world");
end

function say(str)
print(str);
end

function add(x,y)
return 8;
end
  • 运行结果
name:C++
hello world
C++ NB
7 + 3 = 8

这样我们就完成了在C++中调用lua了。这里用到的lua_call函数的最后两个参数分别是调用函数的参数个数以及返回值个数。

lua中调用C风格的函数

在lua中调用c风格的函数主要有两个步骤

  1. 按照格式编写c风格的函数。这个函数的返回值必须是int,表示在lua中调用时函数的返回值个数。函数的只有一个参数,这个参数是一个Lua_State的指针。
  2. 将函数注册到虚拟机中
  • c++代码
int add(lua_State *luaState){
//获取两个参数
int x = lua_tointeger(luaState,1);
int y = lua_tointeger(luaState,2);
std::cout << "x = " << x << ",y = " << y << std::endl;
//将返回值压入栈
lua_pushinteger(luaState,x + y);
//返回返回值个数
return 1;
}

先实现这样一个函数,然后在调用lua脚本之前将函数注册到lua虚拟机中。

//注册c函数
lua_register(L,"Cadd",add);

将这些代码增加到之前C++调用lua的示例中之后,再稍微修改一下lua代码

function add(x,y)
return Cadd(x,y);
end

然后再次运行程序,得到的结果是:

name:C++
hello world
C++ NB
x = 7,y = 3
7 + 3 = 10

nice!

大脸猫

这个人虽然很勤快,但什么也没有留下!

文章评论