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, #tableis 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,
#tablereturns0- so the
forloop isn’t executed at all
- so the
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