You are currently using arrays, which contain dictionaries. What is the difference between a dictionary and an array?
Array
local fruits = {"apples", "passion fruit", "strawberries"}
print(fruits[1]) --> apples
print(fruits[2]) --> passion fruit
print(fruits["apples"]) --> nil
print(fruits[apples]) --> nil
Tables have indexes (keys) and elements. A key sort of represents the position in that table. If index of an array is equal to 1, apples will be printed.
Why doesn’t the last two examples work? Because There is no “apples” index, so the table returns nil.
Strings need to be wrapped in brackets, so the last example results in nil as well, because apples doesn’t exist. You can, however, write the following:
local fruits = {"apples", "passion fruit", "strawberries"}
local apples = "apples"
print(fruits[apples]) -->> nil, there is no apples index
Dictionary
As opposed to tables, dictionaries have different indexes. They are named that way because their structure is dictionary-like.
local cars = {
["BMW"] = "black";
["Lexus"] = "blue";
["Ferrari"] = "red";
}
print(cars["BMW"]) -->> black
print(cars[1]) --> nil
print(cars[Ferrari]) --> nil
Indexes are strings, but they can be numbers as well. There is no index 1 in this dictionary, so it prints nil. The last option returns nil too again, because Ferrari (not a string, but a variable) is not defined.
You could do the same as above:
local Ferrari = "Ferrari"
print(cars[Ferrari]) --> red
Dictionaries can also have numbers as indexes:
local cars = {
[10] = "black";
[100] = "blue";
[1000] = "red";
}
print(cars[1000]) -->> red
Your examples
students = {
{name = "Miles Davis", instrument = "trumpet"},
{name= "John Coltrane", instrument = "saxophone"},
{name= "Bill Evans", instrument = "piano"},
{name= "Wynton Kelly", instrument = "piano"}
}
for i, v in pairs(students) do
print(i, v)
end
-- OUTPUT:
-->> 1 {...} --> because elements are arrays
-->> ... and so on ...
for i, array in pairs(students) do
print(array["name"], array["instrument"])
end
-- OUTPUT:
-->> Miles Davis trumpet
-->> ... and so on ...
What about the second option?
print(students[1]["name"], students[1]["instrument"])
-- OUTPUT
-->> Miles Davis trumpet
--[[
table: STUDENTS
index: 1
element with index: ARRAY
array[1]: nil --> no index one in that aray
array["name"]: Miles Davis
array["instrument"]: trumpet
]]
Hopefully you find this post useful. I will update it a little bit later.