Zhonghui

每个不曾起舞的日子,都是对生命的辜负

User Tools

Site Tools


程序:lua:cpp调用lua

Table of Contents

C++调用Lua(进阶)

C++

#include <algorithm>
#include <cstdio>
 
extern "C"
{
#include "LuaSource/lua.h"
#include "LuaSource/lualib.h"
#include "LuaSource/lauxlib.h"
}
 
const char* LuaFileName = "Lua/Hello.lua";
 
lua_State* L = nullptr; // 一个全局的Lua虚拟机
 
int luaSum(int x, int y)
{
    int Sum = 0;
 
    lua_getglobal(L, "get_sum"); // 把Lua的函数压到栈顶
    // 把两个参数压到栈顶
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
 
    // 调用函数,2个参数,1个返回值
    // 函数的返回值会自动被压到栈顶
    lua_call(L, 2, 1);
 
    // 取栈顶的值,就是结果
    Sum = (int)lua_tonumber(L, -1);
    // -1表示栈顶,也就是pop的位置,1表示栈底
 
    // 从栈顶弹出1个元素
    lua_pop(L, 1);
 
    return Sum;
}
 
int luaMin(int x, int y)
{
    int Min = 0, Max = 0;
 
    lua_getglobal(L, "get_min_max");
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    // 有2个返回值,注意顺序
    lua_call(L, 2, 2);
 
    Min = (int)lua_tonumber(L, -2);
    Max = (int)lua_tonumber(L, -1);
    lua_pop(L, 2);
 
    return Min;
 
}
 
int luaMax(int x, int y)
{
    int Min = 0, Max = 0;
 
    lua_getglobal(L, "get_min_max");
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    // 有2个返回值,注意顺序
    lua_call(L, 2, 2);
 
    Min = (int)lua_tonumber(L, -2);
    Max = (int)lua_tonumber(L, -1);
    lua_pop(L, 2);
 
    return Max;
}
 
void luaReadValues()
{
    lua_getglobal(L, "lua_value_number");
    printf("lua_value_number = %d\n", (int)lua_tonumber(L, -1));
 
    lua_getglobal(L, "lua_value_string");
    printf("lua_value_string = %s\n", lua_tostring(L, -1));
 
    // 把一个Table放到栈顶
    lua_getglobal(L, "lua_value_table");
    int TableIndex = lua_gettop(L); // 保存Table的位置,不能总是通过-1访问
 
    lua_getfield(L, TableIndex, "x");
    lua_getfield(L, TableIndex, "y");
 
    // x是先进栈的,所以x是-2
    printf("x = %d, y = %d\n", (int)lua_tonumber(L, -2), (int)lua_tonumber(L, -1));
}
 
int main()
{
    L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L, LuaFileName);
 
    printf("10 + 5 = %d\n", luaSum(10, 5));
    printf("Min(10, 5) = %d\n", luaMin(10, 5));
    printf("Max(10, 5) = %d\n", luaMax(10, 5));
    luaReadValues();
 
    lua_close(L);
 
    return 0;
}

Lua

print('Loading Lua File...')
 
lua_value_number = 10
lua_value_string = "Ten"
lua_value_table = {
    x = 1,
    y = 2,
}
 
-- 2个参数,1个返回值
function get_sum(x, y)
    return x + y
end
 
-- 2个参数,2个返回值
function get_min_max(x, y)
    return math.min(x, y), math.max(x, y) -- 第二个返回值后返回,所以后压入,所以在栈顶
end

Output

Loading Lua File...
10 + 5 = 15
Min(10, 5) = 5
Max(10, 5) = 10
lua_value_number = 10
lua_value_string = Ten
x = 1, y = 2
/var/www/DokuWikiStick/dokuwiki/data/pages/程序/lua/cpp调用lua.txt · Last modified: 2022/10/08 09:09 by zh