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

How do you compare a number to a value in a table?

Started by tsjb, 13 March 2014 - 04:26 PM
tsjb #1
Posted 13 March 2014 - 05:26 PM

local tArgs = { ... }
local number = tArgs[1]
print(number)
print(number == 5)

I'm having a lot of trouble understanding tables, I have looked at a lot of tutorials but there's something about them that goes right over my head. The code above is a test program a made after my main program wasn't working properly and I'm really confused at the results. I run the program by typing "test 5" which I thought would set "tArgs[1]" to 5 and that assumption seems to be correct because the "print(number) line returns 5, but then the "print(number == 5)" line returns false, meaning it isn't 5.

I first come across this problem while trying to make a simple block placer program. I set up these variables at the start of the program:

local tArgs = { ... }
local totalX = tArgs[1]
local totalY = tArgs[2]
local currentX = 0
local currentY = 0
And then the plan was to have the turtle place a block, move forward and then +1 to the currentX value until currentX == totalX but I found that totalX doesn't actually show up as a number when you compare them so they were never equalling each other and the turtle was going forward forever.

I'm really sorry if this is a stupid/obvious question, I have looked all over for information on tables but even though I picked up the other basics of LUA quite quickly tables are giving me so much trouble, I think I must be looking at them the wrong way.
Lyqyd #2
Posted 13 March 2014 - 05:32 PM
This is mainly a type issue. The arguments a program is given are always given as strings. You are then comparing the string "5" to the number 5. They appear identical when you print them. In order to change the string that your program is given into a number, you should use the tonumber() function.

Try this code:


local tArgs = { ... }
local number = tArgs[1]
print(number)
print(type(number)) --# will print what type of variable it is
print(number == 5)
number = tonumber(number) --# convert the string to a number
print(number == 5)
tsjb #3
Posted 13 March 2014 - 05:52 PM
Thanks so much that works perfectly, the explanation of why it was happening is also really helpful for me :)/>