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

For loop table start to table end

Started by augustas656, 02 January 2014 - 11:01 AM
augustas656 #1
Posted 02 January 2014 - 12:01 PM
I used to use a for loop, where it would repeat the script in the loop by how many contents there are in the table, so a for loop that would repeat the script 3 times if the table had 3 variables. I'm sure it includes this text in the loop "in pairs". what is the script for it?

Also, I need a script that will check a tables contents in order until it finds it's first variable that doesn't exist, so an example table has three variables, and this script will check the table for the first variable that is nil and give the number of the variable in order from the start of the table and print it out, which will be 4 in this case, because the fourth variable is the first that doesn't exist. So a script that finds the first missing variable and prints it's number on your screen, script example.

table = {}
table[1] = "test"
table[2] = "bananas"
table[3] = 47
table[4] = true
table[5] = false
table[6] = "sky"
table[7] = 3
--SCRIPT
variable = 8
--Because 8 is the very first missing variable
--HOW DO I DO THIS? WHAT WILL BE THE "SCRIPT"?
And what will be the script for that.
Edited on 02 January 2014 - 11:17 AM
Lyqyd #2
Posted 02 January 2014 - 12:26 PM
Don't name variables "table".

You can use pairs, ipairs, or just a regular numeric for.


for i = 1, #myTable do
  print(myTable[i])
end

for key, value in ipairs(myTable) do
  print(value)
end

for key, value in pairs(myTable) do
  print(value)
end
augustas656 #3
Posted 02 January 2014 - 12:46 PM
What's the difference between pairs and ipairs, please explain simply if you may.
Bomb Bloke #4
Posted 02 January 2014 - 07:10 PM
pairs() hands you an iterator that returns the values in the table in the order it finds them, which may or may not be the order you expect.

ipairs() will specifically give your the values in numbered order, but values in a table do not need to be indexed with with numbers, so values indexed against eg strings won't be returned. It also trips over if there are "gaps" in your table, but in your case, it'll be the iterator you want for your "repeat this code once for every index in the table" loop.

To print the index of the first missing index in the table, you'd just do:

print(#myTable + 1)

Sticking a # in front of a variable returns its length - in the case of a table, you get the number of indexes before the first missing value.

If you want the highest index in the table before there are no more values, use table.maxn(myTable).