How do I get the index of a dictionary item?

So I wanted to know how to get the index of a dictionary item. I’ve tried this code:

local testDict = {
	["Item"] = {
		-- this should equal 1 as a returned index
	},
	["OtherItem"] = {
		-- this should equal 2 as a returned index
	}
}

for i, v in pairs(testDict) do
	local returnedIdx = table.find(testDict, i)
	print(returnedIdx)
end

but all values returned were nil… Any alternatives? Or am I using table.find() wrong?

2 Likes

In Lua, dictionaries aren’t ordered, meaning key/value pairs have no numerical order or association. The “i” variable gives you the current step of the loop, but it’s not related to the key/value pair.

1 Like

dictionaries dont have number indexes because the strings (words) are the indexes

you could put the index in the dictionary value like this

local exampleDict = {
  ["item"] = {
    index = 1
  },
}

or turn the dictionary into an array and keep the key names in the values

local exampleDict = {
  {
    name = "item"
  },
  {
    name = "otherItem"
  }
}

also if you loop through a dictionary the i, the first variable, will be the key name and v, the second variable, will be the value

2 Likes

Your suggestion did work (I changed the script to convert it to an array)

local testDict = {
	["Item"] = {
		-- this should equal 1 as a returned index
	},
	["OtherItem"] = {
		-- this should equal 2 as a returned index
	}
}

local testArr = {}

for i, v in pairs(testDict) do
	table.insert(testArr, i)
end

print(testArr)

for i=1, #testArr do
	-- Do stuff?
end

Printed the indexes and it worked

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.