lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Nodir Temirhodzhaev wrote:
> I needed to choose numeric indexes from array in the sorted order.
> How can I do this? (In PHP - ksort) Size of array is unknown, indexes
> are rarefied (range: 1-32000) and using lua_next().

You must extract and sort the keys into a separate table and iterate over
that one to access the first.  The generator function "spairs" defined below
handles sparse arrays in this way.  As you see it takes a little more than a
lua_next call.

local function sorted_keys(t)
    local keys = {}

    -- make sure to handle sparse arrays
    -- (using ipairs or table.foreachi won't do...)
    for i, _ in pairs(t) do
        if type(i) == "number" then table.insert(keys, i) end
    end

    table.sort(keys)
    return keys
end

function spairs(t)
    local i, k = 1, sorted_keys(t)
    return function()
        local j = k[i]
        if j then
            i = i + 1
            return j, t[j]
        end
    end
end

local x = {[10]="aap", [5]="noot", [18]="mies", [-5]="vuur"}

for i, v in spairs(x) do print(i, v) end


Bye,
Wim