util.lua 1.88 KB
Newer Older
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
1 2 3 4 5 6 7 8 9
--[[
Utility module for Alpine Wall
Copyright (C) 2012 Kaarle Ritvanen
Licensed under the terms of GPL2
]]--


module(..., package.seeall)

10
function list(var)
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
11
   if not var then return {} end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
12 13 14
   if type(var) ~= 'table' then return {var} end
   if not next(var) then return {} end
   return var[1] and var or {var}
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
15 16 17 18 19 20
end

function listpairs(var)
   return ipairs(list(var))
end

21 22 23 24 25 26
function filter(var, func)
   local res = {}
   for i, v in ipairs(var) do if func(v) then table.insert(res, v) end end
   return res
end

Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
function map(var, func)
   local res = {}
   for k, v in pairs(var) do res[k] = func(v) end
   return res
end

function maplist(var, func)
   if not var then return var end
   return map(list(var), func)
end

function contains(tbl, value)
   for k, v in pairs(tbl) do if v == value then return true end end
   return false
end
Kaarle Ritvanen's avatar
Kaarle Ritvanen committed
42 43 44 45

function extend(tbl1, tbl2)
   for i, var in listpairs(tbl2) do table.insert(tbl1, var) end
end
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
function compare(a, b)
   local t = type(a)
   if t ~= type(b) then return false end
   if t ~= 'table' then return a == b end

   local keys = {}
   for k, v in pairs(a) do
      if not compare(v, b[k]) then return false end
      table.insert(keys, k)
   end
   for k, v in pairs(b) do
      if not contains(keys, k) then return false end
   end
   return true
end

function printtabulars(tables)
64
   local colwidth = {}
65 66 67 68 69
   for i, tbl in ipairs(tables) do
      for j, row in ipairs(tbl) do
	 for k, col in ipairs(row) do
	    colwidth[k] = math.max(colwidth[k] or 0, string.len(col))
	 end
70 71
      end
   end
72 73 74 75 76 77 78 79 80 81
   for i, tbl in ipairs(tables) do
      for j, row in ipairs(tbl) do
	 for k = 1,#row do
	    if k > 1 then io.write('  ') end
	    io.write(row[k])
	    if k < #row then
	       for l = 1,colwidth[k] - string.len(row[k]) do io.write(' ') end
	    end
	 end
	 io.write('\n')
82 83 84 85
      end
      io.write('\n')
   end
end
86 87

function printtabular(tbl) printtabulars({tbl}) end