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

Table printing contents in random order

Started by axel.codeFail(), 21 March 2016 - 02:16 AM
axel.codeFail() #1
Posted 21 March 2016 - 03:16 AM
I am using computercraft version 1.78 for minecraft 1.8.9

When I tried to print the contents of the table it would print the key and the corresponding value together, but it would chose a key at random to print.


  local table = {January=31, February=28, March=31, April=30, May=31, June=30, July=31, August=31, September=30, October=31, November=30, December=31

  for key,value in pairs(table) do

	print(key)
	print(value)

  end


The result from running the program is as follows


December
31
May
31
April
30
January
31
August
31
July
31
September
30
February
28
October
31
June
30
March
31
November
30
Dragon53535 #2
Posted 21 March 2016 - 04:05 AM
String key's aren't stored numerically like numerical indexes are. When pairs is used on them they're sorted by the memory address and not the actual string.
axel.codeFail() #3
Posted 21 March 2016 - 05:16 AM
How would I print them numerically then? ipairs doesn't return anything.
Dragon53535 #4
Posted 21 March 2016 - 05:30 AM
You could set it up as a table with 12 tables inside of them with each of the days and names inside of that set with static keys.


local months = { { name = "January", days = 31 } , { name = "February" , days = 28 } }
Then you could ipairs on the months table


for index,valueTable in ipairs(months) do
  print(index)
  print(valueTable.name)
  print(valueTable.days)
end
Edited on 21 March 2016 - 04:31 AM