Lua使用lua_type(lua_state, lua_gettop(lua_state)时将"string"返回给C++,而非"double",可能出了什么问题?

我试图从lua不断地调用返回值给C++的函数。大部分时间我得到类型为double的值,但有时它会将相同的double值作为string发送。例如=> 30.5作为"30.5"。

为什么lua会将它解释错误呢?

我尝试使用tonumber(return_value)lua中返回值,强制它转为数字,但有时它仍会给我字符串。

lua代码如下:

function getValue()

mValue = 30+ 0.5
return mValue

end

function init()

    print(" [lua]  Calling getValue")
    ret1 = getValue()
    return ret1  -- 尝试过tonumber(ret1)

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:应该每次都被执行,但有时它会进入case LUA_TSTRING:

点赞