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


module(..., package.seeall)

local function list(var)
   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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
end

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

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
36 37 38 39

function extend(tbl1, tbl2)
   for i, var in listpairs(tbl2) do table.insert(tbl1, var) end
end
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

function printtabular(tbl)
   local colwidth = {}
   for i, row in ipairs(tbl) do
      for j, col in ipairs(row) do
	 colwidth[j] = math.max(colwidth[j] or 0, string.len(col))
      end
   end
   for i, row in ipairs(tbl) do
      for j, col in ipairs(row) do
	 if j > 1 then io.write('  ') end
	 io.write(col)
	 for k = 1,colwidth[j] - string.len(col) do io.write(' ') end
      end
      io.write('\n')
   end
end