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

Split an array into multiple after predetermined length

Started by MatazaNz, 30 July 2014 - 08:49 PM
MatazaNz #1
Posted 30 July 2014 - 10:49 PM
So, pretty much what I want to do is split an array into a second array if it becomes too long when listing files. For example, I want the page length to be 15, so if the table is longer than 15, it then limits the table to 15, and the next 15 are dumped into a new table, and so on. If anyone knows how I could do this, that would be fantastic.

Alternatively, I could stick with the one table, and only print a certain amount per page. Any help would be greatly appreciated.
KingofGamesYami #2
Posted 30 July 2014 - 11:19 PM
Assuming it is numerically indexed…

local tables = {} --#store the tables
for i = 1, #tbl, 15 do --#iterates through the table, adding 15 to i each time
  tables[ #tables + 1 ] = {}
  for x = i, i + 15 do --#iterates from i to i + 15
   tables[ #tables ][ x ] = tbl[ x ]
  end
end
hilburn #3
Posted 31 July 2014 - 01:16 AM
Assuming it is numerically indexed…

local tables = {} --#store the tables
for i = 1, #tbl, 15 do --#iterates through the table, adding 15 to i each time
  tables[ #tables + 1 ] = {}
  for x = i, i + 15 do --#iterates from i to i + 15
   tables[ #tables ][ x ] = tbl[ x ]
  end
end

Could be:

 tables[ #tables][ x%15+1] = tbl[ x ]
to make the split tables indexed from 1 to 15 which will probably be a bit more useful. If they aren't numerically indexed you can do pretty much exactly the same thing with a while loop, a couple of counters and next
theoriginalbit #4
Posted 31 July 2014 - 01:35 AM
Could be:

tables[ #tables][ x%15+1] = tbl[ x ]
to make the split tables indexed from 1 to 15 which will probably be a bit more useful. If they aren't numerically indexed you can do pretty much exactly the same thing with a while loop, a couple of counters and next
that will skip index 1
hilburn #5
Posted 31 July 2014 - 02:22 AM
doh, true, or rather it would shuffle what should be at 15 to 1, this is why I like using arrays that start at 0…


local splitIndex=x%15
if splitIndex == 0 then splitIndex=15 end
tables[#tables][splitIndex] = tbl[x]

there you go