Skip to content

Commit 5355cb1

Browse files
authoredApr 22, 2020
minetest.serialize: Reversible number serialization (#9722)
* minetest.serialize: Reversible number to string conversion The %a format is not supported in Lua 5.1. This commit also adds two tests for number serialization.
1 parent 4361bfc commit 5355cb1

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed
 

Diff for: ‎builtin/common/serialize.lua

+2-9
Original file line numberDiff line numberDiff line change
@@ -120,15 +120,8 @@ function core.serialize(x)
120120
elseif tp == "function" then
121121
return string.format("loadstring(%q)", string.dump(x))
122122
elseif tp == "number" then
123-
-- Serialize integers with string.format to prevent
124-
-- scientific notation, which doesn't preserve
125-
-- precision and breaks things like node position
126-
-- hashes. Serialize floats normally.
127-
if math.floor(x) == x then
128-
return string.format("%d", x)
129-
else
130-
return tostring(x)
131-
end
123+
-- Serialize numbers reversibly with string.format
124+
return string.format("%.17g", x)
132125
elseif tp == "table" then
133126
local vals = {}
134127
local idx_dumped = {}

Diff for: ‎builtin/common/tests/serialize_spec.lua

+12
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ describe("serialize", function()
1818
assert.same(test_in, test_out)
1919
end)
2020

21+
it("handles precise numbers", function()
22+
local test_in = 0.2695949158945771
23+
local test_out = core.deserialize(core.serialize(test_in))
24+
assert.same(test_in, test_out)
25+
end)
26+
27+
it("handles big integers", function()
28+
local test_in = 269594915894577
29+
local test_out = core.deserialize(core.serialize(test_in))
30+
assert.same(test_in, test_out)
31+
end)
32+
2133
it("handles recursive structures", function()
2234
local test_in = { hello = "world" }
2335
test_in.foo = test_in

0 commit comments

Comments
 (0)