Lua:从float转换为int

即使Lua不区分浮点数和整数,有些情况下要使用整数。如果你不能做一个像C的转换或没有像Python的int这样的东西,那么将数字隐藏成一个整数的最好方法是什么?

例如计算一个数组的索引时

idx = position / width

你如何确保idx是一个有效的数组索引?我已经提出了一个使用string.find的解决方案,但也许有一种使用明显快得多的算术的方法。我的解决方案:

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 Reference Manual

Returns the largest integer smaller than or equal to x.

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...