Custom iterator help

local iter = function(tbl, callback)
    local ret = {}

    for k, v in pairs(tbl) do
        table.insert(ret, {key = k, value = v})
    end
    table.sort(ret, callback or function(a, b)
        return a.key < b.key
    end)

    local i = 1
    return function()
        local pair = ret[i]
        if pair then
            return pair.key, pair.value
        end
        i += 1
    end
end

for k,v in iter({a=1, b=2, c=3}) do
    print(k,v)
end

I’m getting an infinite loop, what this iteration function should do is it is it the same as pairs except that you can pass a callback function that iterates in sorted order on a dictionary.

Just a logic error. In the closure you will notice that the variable i is never incremented because return is before it. Typical is to initialize the control variable to zero and immediately increment it in the iteration.

    local i = 0
    return function()
        i += 1
        local pair = ret[i]
        if pair then
            return pair.key, pair.value
        end
    end