Jump to content

Module:Ordered pairs

From Wikipedia, the free encyclopedia
This is the current revision of this page, as edited by Gonnym (talk | contribs) at 10:31, 23 December 2021 (Created page with 'local p = {} local function __genOrderedIndex(t) local orderedIndex = {} for key in pairs(t) do table.insert(orderedIndex, key) end table.sort(orderedIndex) return orderedIndex end local function orderedNext(t, state) -- Equivalent of the next function, but returns the keys in the alphabetic -- order. We use a temporary ordered key table that is stored in the -- table being iterated. local key = nil if stat...'). The present address (URL) is a permanent link to this version.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
local p = {}

local function __genOrderedIndex(t)
    local orderedIndex = {}
    for key in pairs(t) do
        table.insert(orderedIndex, key)
    end
    table.sort(orderedIndex)
    return orderedIndex
end

local function orderedNext(t, state)
    -- Equivalent of the next function, but returns the keys in the alphabetic
    -- order. We use a temporary ordered key table that is stored in the
    -- table being iterated.

    local key = nil
    if state == nil then
        -- the first time, generate the index
        t.__orderedIndex = __genOrderedIndex(t)
        key = t.__orderedIndex[1]
    else
        -- fetch the next value
        for i = 1, #(t.__orderedIndex) do
            if t.__orderedIndex[i] == state then
                key = t.__orderedIndex[i + 1]
            end
        end
    end

    if key then
        return key, t[key]
    end

    -- no more value to return, cleanup
    t.__orderedIndex = nil
    return
end

function p.orderedPairs(t)
    -- Equivalent of the pairs() function on tables. Allows to iterate in order.
    return orderedNext, t, nil
end

return p