You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Lua调用C++函数时正确接收多个返回值

问题修复方案

根因分析

Lua调用C/C++扩展函数时,C函数的整数返回值用于告知Lua运行时,当前栈顶有多少个元素需要作为返回值传递给Lua调用方。
你的代码中无论trans是否为空,都向Lua栈压入了3个浮点数,但最后只return 1,因此Lua只会取第一个压入的值作为返回结果,剩余两个栈上的值会被直接丢弃,导致Lua侧的y、z变量赋值为nil。

修改方法

只需将C++侧lua_GetPosition函数的返回值从1改为3即可:

int lua_GetPosition(lua_State* L)
{
    Entity e = static_cast<Entity>(lua_tointeger(L, 1));
    TransformComponent* trans = TransformComponentPool.GetComponentByEntity(e);
    if (trans != nullptr)
    {
        lua_pushnumber(L, trans->transform->position.x);
        lua_pushnumber(L, trans->transform->position.y);
        lua_pushnumber(L, trans->transform->position.z);
    }
    else
    {
        lua_pushnumber(L, 0);
        lua_pushnumber(L,0);
        lua_pushnumber(L, 0);
        LOG_ERROR("Transform not found");
    }
    // 原来返回1,现在改为返回3个栈值作为返回值
    return 3;
}

修改后重新编译C++侧代码,Lua侧即可正常接收到x、y、z三个返回值。


内容的提问来源于stack exchange,提问作者Nathan Weise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:15:03