Lua: converting from float to int
即使Lua不能区分浮点数和整数,但是在某些情况下,您仍想使用整数。如果您无法进行类似C的转换或没有类似Python的
例如,当为
中的数组计算索引时
idx = position / width
如何确保
1 2 3 4 5 6 7 8 9 | 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参考手册:
Returns the largest integer smaller than or equal to x.
Lua
表示
以下示例:
Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio
>12//5
2
更多信息可以在lua手册中找到
@Hofstad与
12.4 + 0.5 = 12.9, floored 12
12.5 + 0.5 = 13, floored 13
12.6 + 0.5 = 13.1, floored 13
1 2 3 | local round = function(a, prec) return math.floor(a + 0.5*prec) -- where prec is 10^n, starting at 0 end |
为什么不只使用