Reputation: 2757
I am really confused about numbers implementation in lua.
Documentation on lua website is quite clear (https://www.lua.org/pil/2.3.html) :
The number type represents real (double-precision floating-point) numbers. Lua has no integer type, as it does not need it. There is a widespread misconception about floating-point arithmetic errors and some people fear that even a simple increment can go weird with floating-point numbers. The fact is that, when you use a double to represent an integer, there is no rounding error at all (unless the number is greater than 100,000,000,000,000). Specifically, a Lua number can represent any long integer without rounding problems. Moreover, most modern CPUs do floating-point arithmetic as fast as (or even faster than) integer arithmetic.
That make perfect sense. But how come an integer owerflow happens in this simplest example?
$ lua
Lua 5.3.6 Copyright (C) 1994-2020 Lua.org, PUC-Rio
> 9223372036854775807 + 1
-9223372036854775808
Upvotes: 1
Views: 1765
Reputation: 11201
It's simple: You're reading "Programming in Lua" online. You're thus using an outdated version for Lua 5.0:
This is the online version of the first edition of the book Programming in Lua, a detailed and authoritative introduction to all aspects of Lua programming written by Lua's chief architect. The first edition was aimed at Lua 5.0. It remains largely relevant for later versions, but there are some differences. All corrections listed in the errata have been made in the online version.
Lua 5.3, which you have installed, adds a 64-bit signed integer type which behaves as described by Jorge Diaz (I'm not sure whether two's or one's complement representation is guaranteed though, technically it probably isn't). The Lua 5.3 reference manual properly documents integers. Note: The newest Lua version is 5.4.
In Lua 5.0, 5.1 and 5.2, you would indeed observe float behavior:
$ lua5.2
Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> return ("%.20g"):format(9223372036854775807 + 1)
9223372036854775808
Upvotes: 3
Reputation: 118
In Lua(also in others languages), integers are stored using 64 bits (which is the standard size for integers on most modern systems). When an integer exceeds the maximum value that can be stored in 64 bits (which is 2^63-1), it "wraps around" to the minimum value that can be stored in 64 bits (-2^63). This is known as an integer overflow.
In this parrticular example, you are adding 1 to the maximum representable value of Lua integers (9223372036854775807), which causes the value to overflow and "wrap around" to the minimum representable value (-9223372036854775808).
Upvotes: 0