Lua:从float转换为int [英] Lua: converting from float to int

查看:1272
本文介绍了Lua:从float转换为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:从float转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆