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);
}
相关推荐
bst@微胖子16 分钟前
Python高级语法之selenium
开发语言·python·selenium
Paddi93019 分钟前
Codeforces Round 1004 (Div. 1) C. Bitwise Slides
c++·算法
王小义笔记21 分钟前
Postman如何流畅使用DeepSeek
开发语言·测试工具·lua·postman·deepseek
java1234_小锋2 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
流星白龙5 小时前
【C++】36.C++IO流
开发语言·c++
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
靡不有初1116 小时前
CCF-CSP第31次认证第二题——坐标变换(其二)【NA!前缀和思想的细节,输出为0的常见原因】
c++·学习·ccfcsp
nbsaas-boot7 小时前
Go 自动升级依赖版本
开发语言·后端·golang
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
不只会拍照的程序猿7 小时前
从插入排序到希尔排序
java·开发语言·数据结构·算法·排序算法