Lua:从浮点数转换为整数 [英] Lua: converting from float to int
问题描述
尽管 Lua 不区分浮点数和整数,但在某些情况下,您想使用整数.如果您不能进行类似 C 的强制转换或没有 Python 的 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
?
例如在计算
idx = 位置/宽度
idx = position / width
如何确保 idx
是有效的数组索引?我想出了一个使用 string.find
的解决方案,但也许有一种使用算术的方法显然会快得多.我的解决方案:
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
推荐答案
你可以使用 math.floor(x)
来自 Lua 参考手册:
返回小于或等于 x 的最大整数.
Returns the largest integer smaller than or equal to x.
这篇关于Lua:从浮点数转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!