]> git.lizzy.rs Git - minetest.git/commitdiff
Improve `MetaDataRef:{get,set}_float` precision (#13130)
authorJude Melton-Houghton <jwmhjwmh@gmail.com>
Thu, 12 Jan 2023 20:40:34 +0000 (15:40 -0500)
committerGitHub <noreply@github.com>
Thu, 12 Jan 2023 20:40:34 +0000 (15:40 -0500)
games/devtest/mods/unittests/metadata.lua
src/script/lua_api/l_metadata.cpp

index 2246469ed31fad7bda5c146a40f4081a12dc4add..6b0dcf04a3d70d95c45925579b9957fc3e392f82 100644 (file)
@@ -63,6 +63,13 @@ local function test_metadata(meta)
        assert(meta:get_float("h") > 1)
        assert(meta:get_string("i") == "${f}")
 
+       meta:set_float("j", 1.23456789)
+       assert(meta:get_float("j") == 1.23456789)
+       meta:set_float("j", -1 / 0)
+       assert(meta:get_float("j") == -1 / 0)
+       meta:set_float("j", 0 / 0)
+       assert(core.is_nan(meta:get_float("j")))
+
        meta:from_table()
        assert(next(meta:to_table().fields) == nil)
        assert(#meta:get_keys() == 0)
index 68b79331bc83e30bbf69e2f3d89702f0e0bb82d3..52d7617d1ce148496fc52da1a02dbc505e841e0a 100644 (file)
@@ -177,7 +177,9 @@ int MetaDataRef::l_get_float(lua_State *L)
 
        std::string str_;
        const std::string &str = meta->getString(name, &str_);
-       lua_pushnumber(L, stof(str));
+       // Convert with Lua, as is done in set_float.
+       lua_pushlstring(L, str.data(), str.size());
+       lua_pushnumber(L, lua_tonumber(L, -1));
        return 1;
 }
 
@@ -188,8 +190,9 @@ int MetaDataRef::l_set_float(lua_State *L)
 
        MetaDataRef *ref = checkAnyMetadata(L, 1);
        std::string name = luaL_checkstring(L, 2);
-       float a = readParam<float>(L, 3);
-       std::string str = ftos(a);
+       luaL_checknumber(L, 3);
+       // Convert number to string with Lua as it gives good precision.
+       std::string str = readParam<std::string>(L, 3);
 
        IMetadata *meta = ref->getmeta(true);
        if (meta != NULL && meta->setString(name, str))