FANDOM


--[[--
    @author: User:Nanaki
    @license: PD
 
    Simple table that remembers the order in which keys were added
 
    Functions/methods:
    pairs(tab) - iterate keys in current order
 
    tab:sort([f]) - sorts elements by value.
        f - compare function like regular sort
            remember to adjust if you have different types as values
            default: function(a,b) return a<b end
 
    tab:ksort([f]) - sorts elements by keys.
        f - compare function like regular sort
            remember to adjust if you have both string and number keys
            default: function(a,b) return a<b end
 
    tab:keys() - returns the list of keys in current order
 
    It's VERY simple. It might explode if one tries to use it for merging and such.
 
    Installation:
 
    local xtab = require('Module:Xtable').new -- only one function is needed
 
    local tab = xtab() -- this creates an empty table
--]]--
 
 
local Xtable = {}
Xtable.__index = Xtable
function Xtable.__index(t, key)
    return t.t[key] or Xtable[key]
end
function Xtable.__newindex(t, key, val)
    if t.t[key] == nil then
        t.o[#t.o+1] = key
    elseif val == nil then
        for i,v in ipairs(t.o) do
            if key == v then table.remove(t.o, i) end
        end
    end
    t.t[key] = val
end
local function Xtable_next(t)
    local i, key = t.i, t.o[t.i]
    t.i = t.i+1
    return key, t.t[key]
end
function Xtable.__pairs(t)
    return Xtable_next, {t=t.t, o=t.o, i=1}
end
function Xtable.__ipairs(t)
    return iparis(t.t)
end
function Xtable:ksort(comp)
    table.sort(rawget(self, 'o'), comp)
    return t
end
function Xtable:sort(comp)
    comp = comp or function(a,b) return a<b end
    local tmp = {}
    for k,v in pairs(self.t) do
        tmp[#tmp+1] = {k=k,v=v}
    end
    table.sort(tmp, function(a,b) return comp(a.v, b.v) end)
    self.o = {}
    for i,v in ipairs(tmp) do
        self.o[#self.o+1] = v.k
    end
    return t
end
function Xtable:keys()
    local copy = {}
    for i,v in ipairs(self.o) do
        copy[#copy+1] = v
    end
    return copy
end
Xtable.new = function()
    return setmetatable({t={}, o={}}, Xtable)
end
return Xtable

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.