Skip to content

Commit

Permalink
Remove long handling in LuaDouble.toString
Browse files Browse the repository at this point in the history
The conversion between longs and doubles is a bit confusing. For
instance, consider:

  double x = 900000000000001020d;
  long y = (double) x; // 900000000000001024
  assert x == y; // Is true!

This means that even if (long) x == x, it's not necessarily true that
Long.toString((long)x) == Double.toString(x)! So let's just delete this
special handling, and always use the double formatting code.
  • Loading branch information
SquidDev committed Oct 25, 2024
1 parent c21f49f commit 85e645f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
8 changes: 2 additions & 6 deletions src/main/java/org/squiddev/cobalt/LuaDouble.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,24 +126,20 @@ public boolean equals(Object o) {

@Override
public String toString() {
long l = (long) v;
if (l == v) return Long.toString(l);
if (Double.isNaN(v)) return JSTR_NAN;
if (Double.isInfinite(v)) return v < 0 ? JSTR_NEGINF : JSTR_POSINF;

Buffer buffer = new Buffer(4);
Buffer buffer = new Buffer(16);
NUMBER_FORMAT.format(buffer, v);
return buffer.toString();
}

@Override
public LuaString checkLuaString() {
long l = (long) v;
if (l == v) return ValueFactory.valueOf(Long.toString(l));
if (Double.isNaN(v)) return STR_NAN;
if (Double.isInfinite(v)) return v < 0 ? STR_NEGINF : STR_POSINF;

Buffer buffer = new Buffer(4);
Buffer buffer = new Buffer(16);
NUMBER_FORMAT.format(buffer, v);
return buffer.toLuaString();
}
Expand Down
9 changes: 8 additions & 1 deletion src/test/resources/spec/base_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,16 @@ describe("The base library", function()
expect(tostring(-32767)):eq("-32767")
end)

it("integers :lua>=5.3", function()
it("large numbers :lua<=5.2", function()
expect(tostring(4611686018427387904)):eq("4.6116860184274e+18")
expect(tostring(-4611686018427387904)):eq("-4.6116860184274e+18")
expect(tostring(9223372036854775807)):eq("9.2233720368548e+18")
end)

it("integers :lua>=5.3 :!cobalt", function()
expect(tostring(4611686018427387904)):eq("4611686018427387904")
expect(tostring(-4611686018427387904)):eq("-4611686018427387904")
expect(tostring(9223372036854775807)):eq("9223372036854775807")
end)

it("integer-compatible floats are preserved :lua>=5.3 :!cobalt", function()
Expand Down

0 comments on commit 85e645f

Please sign in to comment.