首页 > 解决方案 > Lua 使用 lua_type(lua_state, lua_gettop(lua_state) 将“string”返回给 C++ 而不是“double”,这可能是什么问题?

问题描述

我正在尝试lua重复调用该函数,该函数将值返回给 C++。double我大部分时间都得到 type ,但有时它发送的double值与string. 例如=> 30.5 为“30.5”。

为什么lua解释它是错误的方式?

我试图从luausing中返回值tonumber(return_value),以强制它编号,但string有时它仍然给我。

lua侧面:

function getValue()

mValue = 30+ 0.5  
return mValue

end

function init()

    print(" [lua]  Calling getValue")
    ret1 = getValue()
    return ret1  -- tried tonumber(ret1) also

end

对于 C++ 端:

while (lua_gettop(lua_state) >= 1)

{

                str_buf.str(std::string());
        str_buf << " ";
    switch (lua_type(lua_state, lua_gettop(lua_state)))
    {
    case LUA_TNUMBER:
        {
            str_buf << "script returned the number: "
                << lua_tonumber(lua_state, lua_gettop(lua_state));
        }
        break;
    case LUA_TTABLE:
       str_buf << "script returned a table";
    break;
    case LUA_TSTRING:
        {
            std::string temp = lua_tostring(lua_state, lua_gettop(lua_state));
            str_buf << "script returned the string: "
                << temp;
        }
        break;
    case LUA_TBOOLEAN:
        {   
            str_buf << "script returned the boolean: "
            << lua_toboolean(lua_state, lua_gettop(lua_state));
        }
        break;
        default:
    str_buf << "script returned an unknown-type value";     
}

我一直希望在 C++ 中获得 30.5 并且case LUA_TNUMBER:应该每次都执行,但LUA_TSTRING:有时会发生这种情况。

标签: c++lua

解决方案


推荐阅读