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);
}
相关推荐
zzx_blog5 分钟前
c++函数工厂实现两种方式:lambda和function
c++
mit6.8245 分钟前
[pilot智驾系统] 自动驾驶守护进程(selfdrived)
linux·c++·自动驾驶
jokr_14 分钟前
C++ STL 顶层设计与安全:迭代器、失效与线程安全
java·c++·安全
爬虫程序猿22 分钟前
利用 Java 爬虫按关键字搜索 1688 商品详情 API 返回值说明实战指南
java·开发语言·爬虫
Bling_Bling_126 分钟前
ES6新语法特性(第二篇)
开发语言·前端·es6
jokr_1 小时前
C++ 指针与引用面试深度解析
java·c++·面试
乘风归趣1 小时前
spire.doc在word中生成公式
java·开发语言·word
土拨鼠不是老鼠1 小时前
windows 下 使用C++ 集成 zenoh
开发语言·c++
大得3691 小时前
nginx结合lua做转发,负载均衡
nginx·junit·lua
smilejingwei1 小时前
数据分析编程第五步:数据准备与整理
大数据·开发语言·数据分析·esprocspl