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);
}
相关推荐
saltymilk11 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥11 小时前
C++ lambda 匿名函数
c++
沐怡旸17 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥18 小时前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++