]> git.lizzy.rs Git - metalua.git/blob - src/lib/metalua/base.lua
7b8ee5a8427e8364d60d6dcdbde8a2b585643b2b
[metalua.git] / src / lib / metalua / base.lua
1 ----------------------------------------------------------------------
2 ----------------------------------------------------------------------
3 --
4 -- Base library extension
5 --
6 ----------------------------------------------------------------------
7 ----------------------------------------------------------------------
8
9 if not metalua then rawset(getfenv(), 'metalua', { }) end
10 metalua.version             = "v-0.5"
11
12 if not rawpairs then
13    rawpairs, rawipairs, rawtype = pairs, ipairs, type
14 end
15
16 function pairs(x)
17    assert(type(x)=='table', 'pairs() expects a table')
18    local mt = getmetatable(x)
19    if mt then
20       local mtp = mt.__pairs
21       if mtp then return mtp(x) end
22    end
23    return rawpairs(x)
24 end
25
26 function ipairs(x)
27    assert(type(x)=='table', 'ipairs() expects a table')
28    local mt = getmetatable(x)
29    if mt then
30       local mti = mt.__ipairs
31       if mti then return mti(x) end
32    end
33    return rawipairs(x)
34 end
35
36 --[[
37 function type(x)
38    local mt = getmetatable(x)
39    if mt then
40       local mtt = mt.__type
41       if mtt then return mtt end
42    end
43    return rawtype(x)
44 end
45 ]]
46
47 function min (a, ...)
48    for n in values{...} do if n<a then a=n end end
49    return a
50 end
51
52 function max (a, ...)
53    for n in values{...} do if n>a then a=n end end
54    return a
55 end
56
57 function o (...)
58    local args = {...}
59    local function g (...)
60       local result = {...}
61       for i=#args, 1, -1 do result = {args[i](unpack(result))} end
62       return unpack (result)
63    end
64    return g
65 end
66
67 function id (...) return ... end
68 function const (k) return function () return k end end
69
70 function printf(...) return print(string.format(...)) end
71
72 function ivalues (x)
73    assert(type(x)=='table', 'ivalues() expects a table')
74    local i = 1
75    local function iterator ()
76       local r = x[i]; i=i+1; return r
77    end
78    return iterator
79 end
80
81
82 function values (x)
83    assert(type(x)=='table', 'values() expects a table')
84    local function iterator (state)
85       local it
86       state.content, it = next(state.list, state.content)
87       return it
88    end
89    return iterator, { list = x }
90 end
91
92 function keys (x)
93    assert(type(x)=='table', 'keys() expects a table')
94    local function iterator (state)
95       local it = next(state.list, state.content)
96       state.content = it
97       return it
98    end
99    return iterator, { list = x }
100 end
101