Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: converting from float to 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?

For example when calculating an index for an array in

idx = position / width

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 
like image 965
ddk Avatar asked Mar 11 '12 11:03

ddk


People also ask

How do you make an integer in Lua?

Lua has no integer type, as it does not need it. There is a widespread misconception about floating-point arithmetic errors and some people fear that even a simple increment can go weird with floating-point numbers.

How do you change a string to an int in Lua?

You can convert strings to numbers using the function tonumber() . This takes a string argument and returns a number.

What is a float in Lua?

03:08. A Number in Lua is a double precision floating point number (or just 'double'). Every Lua variable that is simply a number (not a Vector3, just a number) with or without decimal places, negative or positive, is a double.


2 Answers

You could use math.floor(x)

From the Lua Reference Manual:

Returns the largest integer smaller than or equal to x.

like image 143
Hofstad Avatar answered Sep 21 '22 15:09

Hofstad


Lua 5.3 introduced a new operator, called floor division and denoted by //

Example below:

Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio

>12//5

2

More info can be found in the lua manual

like image 44
Chaojun Zhong Avatar answered Sep 21 '22 15:09

Chaojun Zhong