Loop Through Ordered Dictionary

I wrote up this script for a plugin and thought it may be useful to anyone who needs to do the same.

This function is meant to be used as the ipairs of dictionaries.

Function
function opairs(Table)
	table.sort(Table)
	local data = {}
	for k, _ in pairs(Table) do
		table.insert(data, k)
	end
	table.sort(data)
	local number = 1
	return function()
		local key, value = data[number], Table[data[number]]
		number += 1
		if key ~= nil and value ~= nil then
			return key, value
		end
	end
end
Usage
for key, value in opairs({C=9, Z=8, J=0}) do
    print(key, value)
    -- C 9
    -- J 0
    -- Z 8
end

One use case could be:

  • Creating ordered Settings lists, since the data could be stored in the format of {SettingName = PlayerChoice}
7 Likes

Doesnt work
char char char char

I might be wrong but you could do

local setting = {settings = "AMOGOS"}

for i,v in pairs(settings) do
print(i,v)
end

No, the order can be wrong, plus i returns the key.

oh yeah I totally forgot that ipairs exists, that’s why we have opairs