I’ve been putting together a table of items for a small project of mine, and noticed something odd when trying to get the Name of a table within a table by its index:
t = {
Front = {},
Back = {}
}
print(t[1])
I would expect this to print ‘Front’, however I’ve receiving a nil value in return.
It has been a while since I used Lua, but I really don’t understand what I’m missing.
Just a note reminder for myself when I revisit this tomorrow - When requiring and executing a function from a Module in the command bar, then changing the name of that function in the module and re-running the require > function call in the command bar, the output complains that the specific function doesn’t exist (still looks for the original function name).
It looks like you are trying to index a dictionary as an array, which is not possible. Tables cannot have two indexes that point to the same value unless you explicitly say so.
The appropriate way to index t would be using t.Front, or t["Front"], and if you wanted to index t with 1 to get t.Front, you would have to write it in your code:
t = {
Front = {},
Back = {}
}
t[1] = t.Front
print(t[1])
Also, this would print the table indexed by t.Front, not the string "Front"…
The usual way of circumventing this, since it’s a table, is using a Name field in Front's table:
t = {
Front = {Name = "Front"},
Back = {Name = "Back"}
}
t[1] = t.Front
print(t[1].Name)