Diferencia entre revisiones de «Módulo:Tablas»

permito nulos al ordenar (se colocarán al principio) y termino la parte de tostring
Hacer que la función tostring ordene las claves
Línea 1: Línea 1:
local z = {}
local z = {}
-- Código copiado de http://lua-users.org/wiki/SortedIteration
function __genOrderedIndex( t )
    local orderedIndex = {}
    for key in pairs(t) do
        table.insert( orderedIndex, key )
    end
    table.sort( orderedIndex )
    return orderedIndex
end
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
    --print("orderedNext: state = "..tostring(state) )
    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,table.getn(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 orderedPairs(t)
    -- Equivalent of the pairs() function on tables. Allows to iterate
    -- in order
    return orderedNext, t, nil
end


function z.tostring(tabla, identacion)
function z.tostring(tabla, identacion)
Línea 12: Línea 57:
     local k2, v2
     local k2, v2
   
   
     for k,v in pairs(tabla) do
     for k,v in orderedPairs(tabla) do
     if type(k) == 'string' then
     if type(k) == 'string' then
     k2 = '"' .. k .. '"'
     k2 = '"' .. k .. '"'