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);
}
相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)4 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
ox00805 小时前
C++ 设计模式-命令模式
c++·设计模式·命令模式
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http