lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


David Given wrote:
> Mike Pall wrote:
> >   local r = remaining % 256
> >   string.char(112 + (remaining-r)/256, r)
> 
> Is this the preferred approach to using math.floor() (which is what I
> usually end up with when converting things to integers)?

Sure, at least if you need both the remainder and the result of
floor-division. If you only need the latter, then math.floor(a/b)
is probably more common.

If you want to know about performance (lower numbers are better):

Time in seconds for | Lua    | LuaJIT |
1e8 iterations of:  | 5.1.4  | 1.1.4  |
--------------------+--------+--------+
r=a%b               |  2.09  |  0.70  |
d=floor(a/b)        |  6.22  |  1.10  |
r=a%b; d=(a-r)/b    |  3.76  |  0.84  |
r=a%b; d=floor(a/b) |  7.97  |  1.44  |

[Using locals and local floor = math.floor of course.]

Apparently the call overhead for floor() is the main factor here
because the '%' operator also uses floor() (the inlined C library
function).

Well ... maybe Lua needs a floor-division operator '//'?

--Mike