This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Cakestory's profile picture

How to check variable for integer or float

Started by Cakestory, 04 January 2013 - 10:50 AM
Cakestory #1
Posted 04 January 2013 - 11:50 AM
Hi,
i tried to write a function where the user must enter an argument like this: function forward(amount).
Though this argument "amount" is used in a for loop it needs to be an integer variable.
My Question is:
How do i check wether the argument/variable is an integer (1,2,3,…) or a float (0.55,30.17,…) so i can force the user to type an integer?

greetings,
cakestory

p.s. i see that it actually works with float variable, but anyway i would like to tell the user that using float values is "less intelligent".
Doyle3694 #2
Posted 04 January 2013 - 11:56 AM
first of all, they are numbers. Not inttegers, and certainly not floats. Though

function(amount)
if amount ~= math.floor(amount) then
   -- amount has decimals
else
   -- amount doesn't have decimals
end
Should hook you up pretty good ;)/>
InputUsername #3
Posted 04 January 2013 - 12:01 PM
Here's is a really simple solution:
if math.round(variable) == variable then
  (code)
end
This code will round the variable and if the rounded variable matches the variable itself (which is only true when the variable is already rounded/an integer) then it runs the code.

I hope that can help.

~InputUsername

Dang, the guy above me was faster :)/>
Cakestory #4
Posted 04 January 2013 - 12:06 PM
Thank you Doyle3694 and InputUsername for your fast help.

@Doyle3694
The reason why i am talking of integers and floats is that i normaly code in Pascal (Delphi 7) and there is a big difference between int and float.
For me it is a bit strange to have only numbers in lua.

Edit:
@InputUsername
The math.round() function is not working (attempt to call nil). I used it the same way and tried it a few times before but round(number) does not seem to work in CC.
Or is it just me not doing it right?
InputUsername #5
Posted 04 January 2013 - 01:02 PM
I'm sorry, the function gives an attempt to call nil error because it doesn't exist at all. My bad. Just replace math.round with either the math.floor or math.ceil function and you should be fine.
RunasSudo-AWOLindefinitely #6
Posted 04 January 2013 - 03:29 PM
For an even shorter solution, try
return ((number % 1) == 0)
That should return "true" if the number is an integer and "false" if it isn't.

It just checks if the number is evenly divisible by 1.
remiX #7
Posted 04 January 2013 - 08:38 PM

var = 32.40
if string.find(tostring(var)), ".") then print("Decimal number") else print("Integer") end