Even though Lua does not differentiate between floating point numbers and integers, there are some cases when you want to use integers. What is the best way to covert a number to an integer if you cannot do a C-like cast or without something like Python's int
?
For example when calculating an index for an array in
idx = position / width
how can you ensure idx
is a valid array index? I have come up with a solution that uses string.find
, but maybe there is a method that uses arithmetic that would obviously be much faster. My solution:
function toint(n) local s = tostring(n) local i, j = s:find('%.') if i then return tonumber(s:sub(1, i-1)) else return n end end
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.
You can convert strings to numbers using the function tonumber() . This takes a string argument and returns a number.
03:08. A Number in Lua is a double precision floating point number (or just 'double'). Every Lua variable that is simply a number (not a Vector3, just a number) with or without decimal places, negative or positive, is a double.
You could use math.floor(x)
From the Lua Reference Manual:
Returns the largest integer smaller than or equal to x.
Lua 5.3
introduced a new operator, called floor division
and denoted by //
Example below:
Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio
>12//5
2
More info can be found in the lua manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With