Search code examples
luafloating-point

Lua: converting from float to int


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

Solution

  • You could use math.floor(x)

    From the Lua Reference Manual:

    Returns the largest integer smaller than or equal to x.