Why won't this work?

I’m sure this is just some weird lua table behavior that I forgot to account for, but why does this seem to skip some iterations? The print function I added while debugging this outputs “0, 20, 60, 120, 1000”. Why does it not loop over every item in the table, and instead skips some?

local netWorths = {
	[0] = "Broke straggler",
	[10] = "Poor networth",
	[20] = "Decent networth",
	[30] = "Average networth",
	[60] = "Above average networth",
	[120] = "Good networth",
	[200] = "High networth",
	[500] = "Goated networth",
	[1000] = "???? networth"
}

local function getClosestNetWorth(value)
	local prev = nil
	for i,v in pairs(netWorths) do
		print("ran "..i)
		if value < i then
			if prev ~= nil then
				return prev
			else
				return netWorths[0]
			end
		end
		prev = v
	end
end

That’s because unlike arrays, dictionaries don’t have order. You cannot loop through them from lowest to highest index (without making your own function)

A solution to this is by making a custom function or iterator that specifically loops dictionaries in order.

1 Like

I knew it was because of something like this! I ended up fixing this issue by making two separate arrays (one for net worth, the other for the titles), so I could just access the related data in one with the index from the other. Thanks for explaining this table behavior!

You made a table … why not use the table sort?

local netWorths = {
	[0] = "Broke straggler",
	[60] = "Above average networth",	
	[10] = "Poor networth",
	[20] = "Decent networth",
	[30] = "Average networth",
	[120] = "Good networth",
	[500] = "Goated networth",
	[200] = "High networth",
	[1000] = "???? networth"
}

table.sort(netWorths, function(one,two)
	return tonumber(string.sub(one.Name, 10)) < tonumber(string.sub(two.Name, 10))
end)

print(netWorths)

You’re creating a function for built in command.

Didn’t know this existed to be honest.

1 Like