4
print(2^62)
print(2^63)
print(2^64)

In Lua 5.2, all numbers are doubles. The output of the above code is:

4.6116860184274e+18
9.2233720368548e+18
1.844674407371e+19

Lua 5.3 has support for integers and does automatic conversion between integer and float representation. The same code outputs:

4611686018427387904
-9223372036854775808
0

I want to get the float result. 2.0^64 works, but what if it's not a literal:

local n = io.read("*n")  --user input 2
print(n^64)

One possible solution is to divide the number by 1: (n/1)^64 because in / division , the operands are always converted to float, but I'm looking for a more elegant solution.

Tested on Lua 5.3.0 (work2).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    There are no more elegant solutions in Lua after splitting numbers to floats and integers :( You must **always** think carefully about number's datatype. No more easiness of programming... – Egor Skriptunoff Apr 03 '14 at 08:52
  • 2
    +1 The best "feature" of Lua was that the programmer needs minimal or no special casing when learning or using the language. I think that's marred by 5.3's introduction of 2 types of numbers :( – legends2k Apr 03 '14 at 08:54
  • That's a little bit disappointed, I wonder if they could consider a new way for representing numbers like `42i` or `42f`. – Yu Hao Apr 03 '14 at 09:09
  • 1
    In your above example change it so `n = 2.0`? – Paige DePol Apr 03 '14 at 10:13
  • @Eidola My example is not clear, I was trying to say `n` is not a literal, like a number from user input. Updated. – Yu Hao Apr 03 '14 at 12:26
  • @YuHao, 42i -> 42, 42f -> 42.0. – lhf Apr 03 '14 at 13:26

1 Answers1

4

io.read("*n") always returns a float. So no surprises there.

If you need to convert an integer to a float, add 0.0 to it.

lhf
  • 70,581
  • 9
  • 108
  • 149