Main Content

Lua - changes to how integers and floats are handled - 5.2 to 5.3

Archive - Originally posted on "The Horse's Mouth" - 2015-11-02 15:30:02 - Graham Ellis

Lua has historically worked internally with floats (actually doubles) even when given whole numbers. The logic was a good one - to keep the language small with a limited number of data types, and for the latest generation of hardware the speed of operations on floating points and doubles really wasn't a great deal different.

A piece of code such as
  g = 9
  h = 3
  print(g/h)
  j = 4
  print(g/j)

would produce results 3 from the first print (as you would expect from what looks like an integer division) but 2.25 from the second.

As from Lua 5.3, calculations have a new internal data type (an integer) has been introduced, with data being converted from integer to float where appropriate - for example when a division is done. The net result is that the formatter in print knows what's an integer and what's a float, and will now format as appropriate, rather following its previous behaviour of printing out whole number floating point results without a decimal point - so the program above will now produce results 3.0 from the first print and 2.25 from the second. Much more logical!

With other operations, performed on 2 integers you'll now get an integer result, but perfored on an integer and a float (or on two floats) the result will now float:

  WomanWithCat:course grahamellis$ lua
  Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio
  > h = 7.0
  > i = 5
  > print (h+i)
  12.0
  > h = 7
  > print (h+i)
  12


Although fundamental to Lua, its quite surprising that this change will make little if any difference to most code (thank goodness - compatabiity is important). The areas for you to watch are on the output formats if a program that reads back your data insists on numbers with (or without) decimals, and if you're using massive numbers that will burst integer limits on your system. Neither's likely to be a daily occurrence.

Lua Programming course starts tomorrow (get in touch quick if you would like to attend)! and again on 1st December (2015). If you've not programmed before, Learning to Program in Lua starts on 30th November. Both courses are also scheduled to run again in February 2016, and at later dates too - see [here] for the current schedule.