lua脚本调用 c/c++中的接口

脚本的使用

Lua 复制代码
local b,i,f,s = luascriptCallCpp(true,2,3.4,"hellocpp")
print("haha=",b,i,f,s)

脚本调用c/c++接口,脚本的第一个入参在栈底,最后一个入参在栈顶

c/c++接口的返回参数,第一个 入栈的参数为脚本中的第一个返回值,依次类推。

c/c++接口函数的返回值int,表示lua脚本端的返回参数个数。

在c/c++端,获取脚本传入的参数方式1:依次从栈底开始取。

cpp 复制代码
int exportLuascriptCallCpp1(lua_State* L)
{
    int iParams = lua_gettop(L); //获取参数个数
    if (lua_isboolean(L, 1)) {
        std::cout << 1 << "bool:" << std::boolalpha << lua_toboolean(L, 1) << '\n';
    }
    if (lua_type(L, 2) == LUA_TNUMBER && lua_isinteger(L, 2)) {
        std::cout << 2 << "int:" << lua_tointeger(L, 2) << '\n';
    }
    if (lua_type(L, 3) == LUA_TNUMBER && !lua_isinteger(L, 3)) {
        std::cout << 3 << "number:" << lua_tonumber(L, 3) << '\n';
    }
    if (lua_isstring(L, 4)) {
        std::cout << 4 << "string:" << lua_tostring(L, 4) << '\n';
    }

    lua_pushboolean(L, true);
    lua_pushinteger(L, 1);
    lua_pushnumber(L, 2.3);
    lua_pushstring(L, "returndata");

    return 4;
}

在c/c++端,获取脚本传入的参数方式1:依次从栈顶开始取,并且每次取出一个后lua_pop掉栈顶元素,所以获取下一个元素时依然是从栈顶开始。

cpp 复制代码
int exportLuascriptCallCpp(lua_State* L)
{
    if (lua_isstring(L, -1)) {
        std::cout << 1 << "string:" << lua_tostring(L, -1) << '\n';
    }
    lua_pop(L, 1);
    if (lua_type(L, -1) == LUA_TNUMBER && !lua_isinteger(L, -1)) {
        std::cout << 1 << "number:" << lua_tonumber(L, -1) << '\n';
    }
    lua_pop(L, 1);
    if (lua_type(L, -1) == LUA_TNUMBER && lua_isinteger(L, -1)) {
        std::cout << 1 << "int:" << lua_tointeger(L, -1) << '\n';
    }
    lua_pop(L, 1);
    if (lua_isboolean(L, -1)) {
        std::cout << 1 << "bool:" << std::boolalpha << lua_toboolean(L, -1) << '\n';
    }

    lua_pushboolean(L, true);
    lua_pushinteger(L, 1);
    lua_pushnumber(L, 2.3);
    lua_pushstring(L, "returndata");
    return 4;
}

最后别忘记了要导出(注册)c/c++接口到lua的环境变量中。

cpp 复制代码
static const luaL_Reg exportLib[] = {
    {"luascriptCallCpp",exportLuascriptCallCpp},
    {NULL, NULL}
};

for (const luaL_Reg*lib = exportLib; lib->func; ++lib)
{
    lua_register(L, lib->name, lib->func);
}
相关推荐
JANYI20184 小时前
C文件在C++平台编译时的注意事项
java·c语言·c++
先鱼鲨生5 小时前
【Qt】初识Qt
开发语言·qt
freyazzr5 小时前
Leetcode刷题 | Day51_图论03_岛屿问题02
数据结构·c++·算法·leetcode·深度优先·图论
2301_807611495 小时前
126. 单词接龙 II
c++·算法·leetcode·深度优先·广度优先·回溯
chao_7896 小时前
QT开发工具对比:Qt Creator、Qt Designer、Qt Design Studio
开发语言·qt
奋进的小暄7 小时前
数据结构(4) 堆
java·数据结构·c++·python·算法
feiyangqingyun7 小时前
Qt/C++源码/实时视音频通话示例/极低延迟/可外网通话/画中画/支持嵌入式板子
c++·qt·qt视音频通话
大飞pkz7 小时前
【Unity】使用XLua进行热修复
unity·c#·游戏引擎·lua·游戏开发·xlua·lua热修复
珊瑚里的鱼7 小时前
LeetCode 102题解 | 二叉树的层序遍历
开发语言·c++·笔记·算法·leetcode·职场和发展·stl
码上飞扬8 小时前
Java大师成长计划之第12天:性能调优与GC原理
java·开发语言