For instance,
local Table = {"Pie", "Bacon", "Eggs", "Milk"} print(tostring(Table["Pie"]))
Would this print "1" or something else?
Your table doesn't have any specific key : value pairs. It's numerically sorted. For example, Pie
is the first element, Bacon
is the second element, and so on. Since no keys were assigned to those values, the key is automatically their position in the array.
You could make it easier to visualize by manually assigning the position as their key, though this is redundant in any applicable situation since it's done automatically.
local t = { [1] = "Pie"; [2] = "Bacon"; [3] = "Eggs"; [4] = "Milk"; }
The table above is the exact same as the one in your snippet, except we're just showing how the table really looks behind the scenes. If you wanted to index the table for Pie
, you'd just use it's position in the table like such t[1]
Likewise, you could create a new index by choosing the key in the table you want to overwrite. The syntax would be no different from creating any ordinary variable:
local t = {} t[1] = "Pie" t[2] = "Bacon" t[3] = "Eggs" t[4] = "Milk"
Again, the code above is no different than the table in your snippet apart from format.
Any non-numerically sorted keys in a table is automatically considered a hash table (or a mixed table, if both formats are being used). Hash tables would be indexed similarly, except you'd use the generic key associated with the value you want instead of a number representing that value's position. For instance...
local t = { ["Pie"] = 1; ["Bacon"] = 2; ["Eggs"] = 3; ["Milk"] = 4; }
The values in this table are no longer in order (not even the order you see them in). Therefore, attempting to use our previous solution for retrieving values from an array are no longer acceptable. Such an attempt like t[1]
would yield nil. This is where you could index the table with a generic key. For example, t["Pie"]
or t.Pie
would yield the value 1