C++调用lua示例

2 篇文章 1 订阅

1. lua源码下载
去官网http://www.lua.org/download.html下载
2. 使用lua
a)解压包,将源码拷贝出来添加进vs工程
b)项目工程代码只需要包含lua.hpp即可,冲突的main函数更改个名字即可,所有的.c文件设置不使用预编译头
3. lua示例

mystr = "hello world"
my_table = {name = "yxli8", id = 123456}

function a_add_b(a,b)
	return a+b
end
  1. c++源码
#include <iostream>
#include "lua.hpp"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	//  初始化
	lua_State *L = luaL_newstate();
	if (L == nullptr)
	{
		return -1;
	}
	// 加载相关库文件
	luaL_openlibs(L);
	
	// 加载lua文件
	int bRet = luaL_loadfile(L, "test.lua");
	if (bRet)
	{
		cout << "load test.lua file failed" << endl;
		return -1;
	}
	
	// 执行lua文件
	bRet = lua_pcall(L, 0, 0, 0);
	if (bRet)
	{
		cout << "call test.lua file failed" << endl;
		return -1;
	}
	
	// 获取值
	lua_getglobal(L, "mystr");
	std::string str = lua_tostring(L, -1);
	cout << "str=" << str << endl;
	
	// 获取表中数据
	lua_getglobal(L, "my_table");
	lua_getfield(L, -1, "name");
	str = lua_tostring(L, -1);
	cout << "table:name=" << str << endl;
	
	// 获取表中数据
	lua_getglobal(L, "my_table");
	lua_getfield(L, -1, "id");
	int nNumber = lua_tonumber(L, -1);
	cout << "table:id=" << nNumber << endl;
	
	// 获取并调用函数
	lua_getglobal(L, "a_add_b");
	lua_pushnumber(L, 10);
	lua_pushnumber(L, 20);
	int iRet = lua_pcall(L, 2, 1, 0);
	if (iRet)
	{
		const char* pErrorMsg = lua_tostring(L, -1);
		cout << pErrorMsg << endl;
		lua_close(L);
		return -1;
	}
	
	// 获取结果
	if (lua_isnumber(L, -1))
	{
		double fValue = lua_tonumber(L, -1);
		cout << "a + b = " << fValue << endl;
	}
	
	lua_close(L);
	// waiting for console
	cin.get();
	return 0;
}
  1. 备注
    lua和c++是通过一个虚拟栈来交互的。
    c++调用lua实际上是:由c++先把数据放入栈中,由lua去栈中取数据,然后返回数据对应的值到栈顶,再由栈顶返回c++。
    lua调c++也一样:先编写自己的c模块,然后注册函数到lua解释器中,然后由lua去调用这个模块的函数。
    在lua中,lua堆栈就是一个struct,堆栈索引的方式可是是正数也可以是负数,区别是:正数索引1永远表示栈底,负数索引-1永远表示栈顶
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值