how do for loop and table work in lua

tags: learning programming lua

content

local reading_scores = { teej_dv = 10, ThePrimeagen = "N/A" }
for index = 1, #reading_scores do
  print(reading_scores[index])
end
  • this code doesn’t print anything
  • because when for idx, #table is used, lua treats the table as an array
    • # operator gets the length of an array
  • if the table actually does not contain any array element, #table returns 0
    • so the for loop isn’t executed at all
local reading_scores = { teej_dv = 10, ThePrimeagen = "N/A", 3 }
for index = 1, #reading_scores do
  print(reading_scores[index])
end
  • in this code, the table contains an array element
  • this code prints out 3

up

down

reference