aboutsummaryrefslogtreecommitdiff
path: root/lua/utils.lua
blob: 1ed03e1121e61e8bc6c8e7ac54a86974ad9a1712 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
local M = {}

function M.try(f, catch_f)
    local status, exception = pcall(f)
    if not status then
        catch_f(exception)
    end
end

function M.instanceOf(subject, super)
    super = tostring(super)
    local mt = getmetatable(subject)

    while true do
        if mt == nil then return false end
        if tostring(mt) == super then return true end
        mt = getmetatable(mt)
    end
end

--[[
function M.isArray(o)
    local i = 0
    for _ in pairs(o) do
        i = i + 1
        if o[i] == nil then return false end
    end
    return true
end
]]--

function M.map(func, obj)
    local new_obj = {}
    for i,v in ipairs(obj) do
        new_obj[i] = func(v)
    end
    return new_obj
end

function M.dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. M.dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

return M