Lua odd MIN Integer number

Viewed 94

Problem (Tested on Lua 5.3 and 5.4):

a = -9223372036854775807 - 1 ==> -9223372036854775808  (lua_integer)
b = -9223372036854775808     ==> -9.2233720368548e+018 (lua_number)

Question:

Is it possible to get "-9223372036854775808" without modify "luaconf.h" or write "-9223372036854775807 - 1"?

1 Answers

When you write b = -9223372036854775808 in your program, the Lua parser treats this as "apply negation operator to positive integer constant", but positive constant is beyond integer range, so it's treated as float, and negation is applied to the float number, and the final result is float.

There are two solutions to get minimal integer:

  1. Bitwise operators convert floats to integers (bitwise OR has lower priority then negation):
b = -9223372036854775808|0
  1. Use the special constant from math library:
b = math.mininteger

P.S.
Please note that additional OR in the expression b = -9223372036854775808|0 does not make your program slower. Actually, all calculations (negation and OR) are done at compile time, and the bytecode contains only the final constant you need:

$ luac53 -l -l -p -
b = -9223372036854775808|0

main <stdin:0,0> (2 instructions at 0x244f780)
0+ params, 2 slots, 1 upvalue, 0 locals, 2 constants, 0 functions
    1   [1] SETTABUP    0 -1 -2 ; _ENV "b" -9223372036854775808
    2   [1] RETURN      0 1
constants (2) for 0x244f780:
    1   "b"
    2   -9223372036854775808
locals (0) for 0x244f780:
upvalues (1) for 0x244f780:
    0   _ENV    1   0
Related