笔记:vs2022 c++调用lua

一、编译lua静态库

可以看我的另一篇文章:笔记: vs2022 编译静态库

二、编译c++文件

(一)、创建项目
创建一个控制台项目(c/c++)
(二)、设置项目属性:
1。创建 test.cpp 源文件
2。配置属性->C/C++>预编译头->取消预编译
3。配置属性->C/C+±>常规->包含附加目录 : 设置include目录【./h文件目录。别导入,没用。。】
4。配置属性->C/C++>高级-> 编译为 c++代码
5。配置属性->C/C++>预处理器 中,前面加入 _CRT_SECURE_NO_DEPRECATE;
6.。配置属性-》常规-》项目类型-》应用程序

7。配置属性-》链接器-》常规-》附加库目录
【填入:静态库文件的目录】

(三)编写c++文件
test.cpp:

#include 
#include 
#include "lua.hpp"
using namespace std;
#pragma comment(lib, "luaLib.lib")	// 添加静态库,已经设置了库文件目录,这里只要文件名即可
int main()
{
    lua_State* L = luaL_newstate();		// 创建 lua_State对象【一个堆栈】

    if (!L) {
        cout << "error:luaL_newstate" << endl;
        return -1;
    }
    luaL_openlibs(L);	// 获取静态库函数
    int ret = luaL_dofile(L, "test.lua"); // 加载并运行 lua文件
    // 这里要注意两点:
    // 一、如果不在同一目录,需要相对或绝对地址【因为是调用lua文件,用不到#include包含目录】
    // 该函数和 luaL_loadfile();长得差不多,但是后者只加载不运行。不运行无法对lua变量进行操作
    if (ret) {
        cout << "error:luaL_dofile" << endl;
        return -1;
    }
    cout << "luaL_dofile success" << endl;

    lua_getglobal(L, "str");		// 获取全局变量【lua 8大类型都可以,只分全局和局部】
    string str = lua_tostring(L, -1);	// 将栈顶元素出栈,该元素是在lua中是string,所以需要用 lua_tostring(); 其余类型同理
    cout << "lua str=" << str.c_str() << endl;

    lua_getglobal(L, "table2");
    lua_getfield(L, -1, "name");	// 获取table2.name,并放入栈顶
    str = lua_tostring(L, -1);	
    cout << "lua table2.str=" << str.c_str() << endl;


    lua_getglobal(L, "addFunc");	// 获取一个函数
    lua_pushnumber(L, 10);	// 入栈一个数据
    lua_pushnumber(L, 52);
    lua_pcall(L, 2, 1, 0);	// 在栈中调用 函数,并将结果放入栈顶
    cout << "lua addFun res=" << lua_tonumber(L, - 1) << endl; // 取出结果


    std::cout << "Hello World!\n";
    return 0;
}

test.lua

str = "hello vs 2022"
table2 = {name = "vs"}
function addFunc(a, b)
	return a * b
end

(四)、运行
点击:
菜单栏:生成-》重新生成解决方案

你可能感兴趣的:(c++,vs,lua,lua,c++,开发语言)