Referencing to this with index?

for example

local food = {
   basket = {
      "apple",
      "orange"
   },
   desk = {
      "bananas",
      "grapes"
   }
}

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

These are the same things:

local tbl = {
    key = 1
}
local tbl = {
    ["key"] = 1
}

You need to index them with their string:

print(tbl.key)
print(tbl["key"]) --both is possible

In your case:

food.desk[1]

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]

1 Like

You can’t.

The reason you can do that with arrays (or dictionaries with numbered indexes) is specifically because they have numerical indexes.

To access ‘bananas’, you would have to use

desk["desk"][1]

You may ask, why can you index a number on the second ‘[]’ and not the first one? Well that’s because inside ‘desk’ is an array.

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)

local food = {
	[1] = {
		"apple",
		"orange"
	},
	[2] = {
		"bananas",
		"grapes"
	}
}

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”