How do I check if an object already exists in this dictionary?


https://gyazo.com/700ad258fe1407f59615d993a9595937

I’m trying to check if “Province” already exists in that dictionary, but the if statement has yet to do anything

If you’re checking a table you could try table.find()

They can also do

if OrderOfBestProvincesTable[Province] ~= nil then

That should be the same as their

if OrderOfBestProvincesTable[Province] then

Maybe try something like this:

function InsertProvinceInTable(OrderOfBestProvincesTable, Index, Province, Value)
	if not OrderOfBestProvincesTable[Index] then
		Index += 1
		OrderOfBestProvincesTable[Index] = {
			Province = Province;
			ProvinceValue = Value;
		}
	end
	return OrderOfBestProvincesTable, Index
end

I’m pretty sure you have put it as:

if OrderOfBestProvincesTable[index] then

because you used the index argument to set the value.

Yes that’s probably it

function InsertProvinceInTable(OrderOfBestProvincesTable, Index, Province, Value)
	if not OrderOfBestProvincesTable[Index] then
		Index += 1
		OrderOfBestProvincesTable[Index] = {
			Province = Province;
			ProvinceValue = Value;
		}
	end
	return OrderOfBestProvincesTable, Index
end

This may seem redundant but you are absolutely sure the parameter Province absolutely does not exist as a key in the dictionary (ie spelling mistakes, string vs number, string vs object)? If it’s a value, and not a key, your only choice is to loop through and search for it.

Are you actually putting anything into the Dictionary part of the table? Because the only line adding to the table appears to be this:

OrderOfBestProvincesTable[Index] = { Province = Province, ProvinceValue = Value }

If “Index” is a natural number, and you initialize it to 1, then OrderOfBestProvincesTable is going to be an array, specifically an array of dictionaries, where each dictionary has 2 keys: “Province” and “ProvinceValue”.

OrderOfBestProvincesTable[Province], assuming Province is a string, is going to be looking for a string key in a dictionary that probably doesn’t exist, or even if it does, it has keys that are the values of Index, not Province.

I think you need to sort out whether you want a dictionary by Province, or an array by index, or both separately. If you’re intentionally trying to do both in one Lua table, I’d advise against that, because any small mistake managing the array part could put the entries keyed by Index into the dictionary part, which means pairs will loop over the lot (definitely not what you want).

1 Like