Merge pull request #406 from chr15m/lib-alias-hacks
[jackhill/mal.git] / lua / utils.lua
CommitLineData
9d42904e
JM
1local M = {}
2
3function M.try(f, catch_f)
4 local status, exception = pcall(f)
5 if not status then
6 catch_f(exception)
7 end
8end
9
10function M.instanceOf(subject, super)
11 super = tostring(super)
12 local mt = getmetatable(subject)
13
14 while true do
15 if mt == nil then return false end
16 if tostring(mt) == super then return true end
17 mt = getmetatable(mt)
18 end
19end
20
21--[[
22function M.isArray(o)
23 local i = 0
24 for _ in pairs(o) do
25 i = i + 1
26 if o[i] == nil then return false end
27 end
28 return true
29end
30]]--
31
32function M.map(func, obj)
33 local new_obj = {}
34 for i,v in ipairs(obj) do
35 new_obj[i] = func(v)
36 end
37 return new_obj
38end
39
40function M.dump(o)
41 if type(o) == 'table' then
42 local s = '{ '
43 for k,v in pairs(o) do
44 if type(k) ~= 'number' then k = '"'..k..'"' end
45 s = s .. '['..k..'] = ' .. M.dump(v) .. ','
46 end
47 return s .. '} '
48 else
49 return tostring(o)
50 end
51end
52
53return M