C++调用lua的基本环境建立

目的

  1. 在C++中建立lua运行环境,可以跑基本的lua脚本
  2. 执行以下lua代码
print("hello world")
  1. 输出结果

hello world

准备lua库

  1. 直接去lua.org 下lua源码
  2. 如果不用makefile转成vs工程话,也可以直接创建新vs项目,把文件拖进去就可以了,注意项目中声明宏LUA_BUILD_AS_DLL
  3. 在自己的工程里引lua.lib, 头文件目录也设置到src目录
  4. 由于lua是C生成了,为了不让其他文件引用麻烦,并为隐藏lua的调用,建议lua调用都在cpp文件中调用 。

Lua的调用流程

  1. 建立lua_State对象,例如调用 luaL_newstate
  2. 加载必要的lua库, 例如luaL_openlibs,可以加载所有的lua库
  3. 调用lua脚本,例如luaL_dofile,可以加载并执行文件
  4. 关闭lua, 调用lua_close

代码展示

lua_imp.cpp

#ifdef __cplusplus
extern "C" {
#endif
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef __cplusplus
}
#endif
#include <string>
#include <iostream>
#include <fstream>
#include <map>

static const char* lua_script_path = "../Scripts/";

static std::map<int, std::string> _E_ERR_STR = {
	std::make_pair(LUA_OK, "no errors"),
	std::make_pair(LUA_ERRRUN, "a runtime error"),
	std::make_pair(LUA_ERRMEM, "memory allocation error.For such errors, Lua does not call the message handler"),
	std::make_pair(LUA_ERRERR, "error while running the message handler"),
	std::make_pair(LUA_ERRSYNTAX, "syntax error during precompilation"),
	std::make_pair(LUA_YIELD, "the thread(coroutine) yields"),
	std::make_pair(LUA_ERRFILE, "a file - related error; e.g., it cannot open or read the file")
};


void test_lua() {

	lua_State* L = luaL_newstate();
	luaL_openlibs(L);
	std::string main_file = lua_script_path;

	main_file += "main.lua";
	int res = luaL_dofile(L, main_file.c_str());
	if (res != LUA_OK) {
		// 打印错误 
		auto it = _E_ERR_STR.find(res);
		if (it != _E_ERR_STR.end()) {
			std::cout << _E_ERR_STR[res] << std::endl;
		}else {
			std::cout << "Unknow error occurted!!!" << std::endl;
		}
	}

	lua_close(L);
	L = NULL;
}

main.cpp

int main()
{
    extern void test_lua();
    test_lua();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值