If I wanted to reference to bananas with indexes, how would I do that?
I have tried food[2][1]
but it just returns nil since 2 is not something in the table food
what if I want to index everything with numbers?
For example I do not know the names of tables inside food and i want to reference them with numbers like food[1] or food[2]
If youâre set on using numerical indices for accessing the sub-tables in the food table, there are a couple solutions you could use.
Option One
The first option is to create a âlookupâ table that assigns each sub-tableâs key name to an index.
--Create a key lookup table based on indices
local foodLookupTbl = {}
--Create an iterator
local foodIndex = 1
--Assign each key in the "food" table to a numerical index for access
for k, v in pairs(food) do
foodLookupTbl[foodIndex] = k
foodIndex += 1
end
However, this solution only works if you donât care about the ordering of the sub-tables assigned. The iteration function above wonât necessarily iterate the food table in-order. Ex.
--This could print "orange" or "grapes"
print(food[foodLookupTbl[1]][2])
That in-mind, youâd have to make sure your other accessing scripts know the order that the keys were assigned.
A work-around for this would be to manually create the lookup table, i.e.
foodLookupTbl = {
[1] = basket
[2] = desk
....
}
Option Two
You could also just use numbers for the keys of the sub-table directly, (if the name of the sub-table isnât important)
If you still wanted the names of each sub-table for this case, you could again use a lookup table that assigns each index to a string name for the sub-table, i.e. [1] = âbasketâ