Find the number index of a dictionary

I have been search through the dev forum and I cannot find an answer to this.
I want to find the number index of a dictionary, not the index.

local t = {cheese, ham, lettuce}
for i,v in pairs (t) do
print(i)
end

This prints the number index (1, 2, 3).

local d = {
['cheese'] = 'cheese',
['ham'] = 'ham',
['lettuce'] = 'LETTUCE TASTES SO GOOD'
    }
for i,v in pairs (d) do
print(i)
end

This prints the index (‘cheese’, ‘ham’, ‘lettuce’), not then number index (1, 2, 3).
I’ve seen a script that can do that, but I forgot where I found it and I can’t find it. I’ve also tried using print(d[table.find(d, 'cheese')]) but apparently that doesn’t work on dictionaries or something, it just doesn’t work and returns nil.

1 Like

Dictionaries don’t have number indices. The table in your second code sample uses the strings ‘cheese’, ‘ham’, and ‘lettuce’ as the indices.

If you know the value but want to find the key you can use table.find if the table is an array, but if it’s a dictionary you have to implement your own search function:

local function find(dict, value)
	for k, v in pairs(dict) do
		if (v == value) then
			return k
		end
	end
end

local d = {
	['cheese'] = 'cheese',
	['ham'] = 'ham',
	['lettuce'] = 'LETTUCE TASTES SO GOOD'
}
print(find(d, 'LETTUCE TASTES SO GOOD')) --> lettuce
print(find(d, "Some Value That Doesn't Exist")) --> nil

If you need to use number indices but you only have a dictionary then you would need to build a new array and copy values over like @XxELECTROFUSIONxX demonstrates.

There’s no number index when there’s a string index.

You can still just change those indexes to numbers

local t = {}
local dict = {
    i = "v",
}
local insert = table.insert
for _, v in pairs(dict) do
    insert(t, v)
end -- table with numeric indexes
print(table.find(t, "v")) --> 1

These responses are really silly. Of course you can get the index number of dictionaries.

Like this:

	local i = 1
	for key, value in pairs(myDictionary) do
		print(key .. 'has index number: ' .. i) 
		-- 'foo has index number: 1'
		-- 'bar has index number: 2'
		i += 1
	end
3 Likes