Lua: float to integer

GeeXLab 0.9.x.x is available with Lua 5.3 and one of the new features of Lua 5.3 is the native support of 64-bit integer numbers. In previous versions of Lua, only double precision floating numbers were available (fp64).

In some situations, it’s useful to convert a float to an integer. For example the number of GPU cores returned by gh_gml.get_gpu_cores() is a floating point number (even if the doc says it’s an int). To display it as an integer, Lua 5.3 requires some kind of conversion / casting otherwise you will end up with this error:

bad argument #2 to 'format' (number has no integer representation)

 
In the format() function of the string lib, you can use %.0f:

local cores = gh_gml.get_gpu_cores(0)
local str = string.format("GPU 0 cores: %.0f)", cores)

 
Now if you need an integer number, you can convert a floating point number to an integer with math.floor():

local cores_float = gh_gml.get_gpu_cores(0)
local cores_int = math.floor(cores_float)