Homokozó/TG/Utils[mi ez?] • [dokumentáció: mutat, szerkeszt] • [tesztek: létrehozás]

-- maps all elements of an array through a function
function map(func, array)
  local new_array = {}
  for k,v in pairs(array) do
    new_array[k] = func(v)
  end
  return new_array
end

-- turns a frame object into a table
function unpackFrame(frame, ...)
    local arguments = {}
    for i, v in ipairs({...}) do
        arguments[i] = frame.args[v]
    end
    return unpack(arguments)
end

-- returns a new table which is the reverse of the original
function table.reverse(tbl)
    local newTable = {}
    for k,v in pairs(tbl) do
        newTable[v] = k
    end
    return newTable
end

-- returns a new table created by merging two tables
-- the second table overwrites the first for equal keys
function table.merge(tbl1, tbl2)
    local newTable = {}
    for k,v in pairs(tbl1) do
        newTable[k] = v
    end    
    for k,v in pairs(tbl2) do
        newTable[k] = v
    end
    return newTable
end

function table.dump(tbl, recursive)
    if type(tbl) ~= 'table' then
        return '<not a table!>'
    end
    local s = '{ '
    for k,v in pairs(tbl) do
        if type(k) ~= 'number' then 
            k = '"'..k..'"' 
        end
        if type(v) == 'table' then
            if recursive then
                v = table.dump(v, true)
            else
                v = 'table'
            end
        elseif type(v) == 'boolean' then -- no boolean -> string autoconversion in Lua
            if v then
                v = 'true'
            else
                v = 'false'
            end
        end
        s = s .. '['..k..'] = ' .. v .. ','
    end
    return s .. '} '
end

SetMeta = {
    __index = {
        has = function(tbl, key)
            return tbl[key] ~= nil
        end
    },
    __add = function(set1, set2)
        local set = table.merge(set1, set2)
        setmetatable(set, SetMeta)
        return set
    end,
}

function Set(list)
    local set = {}
    setmetatable(set, SetMeta)
    for _, l in ipairs(list) do 
        set[l] = true
    end
    return set
end

local Test = {
    testMerge = function(frame)
        local a,b,c,d,e,f = unpackFrame(frame, 1, 2, 3, 4, 5, 6)
        local s1, s2, s3 = Set{a,b,c}, Set{d,e,f}, Set{a,b,e,f}
        return table.dump(s1 + s2) .. '|' .. table.dump(s1 + s3)
    end
}

local Utils = {
    map = map,
    unpackFrame = unpackFrame,
    table = {
        reverse = table.reverse,
        merge = table.merge,
        dump = table.dump,
    },
    Set = Set,
    Test = Test,
}

return Utils