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
question from:
https://stackoverflow.com/questions/9654496/lua-converting-from-float-to-int 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…