-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_builtins.go
113 lines (95 loc) · 1.86 KB
/
write_builtins.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package lunar
import (
"io"
)
func WriteBuiltins(w io.Writer) (n int, err error) {
return w.Write([]byte(`
local builtins = _G.lunar_go_builtins or {}
_G.lunar_go_builtins = builtins
local err_meta = {__index={
Error = function(self)
return self.msg
end
}}
function builtins.create_error(msg)
return setmetatable({msg=msg}, err_meta)
end
function builtins.append(dst, ...)
if dst == nil then
dst = {}
end
for i=1, select('#', ...) do
local val = select(i, ...)
table.insert(dst, val)
end
return dst
end
function builtins.delete(map, key)
map[key] = nil
end
function builtins.length(obj)
if obj == nil then
return 0
end
return #obj
end
function builtins.mapLength(m)
local l = 0
for _ in pairs(m) do
l = l + 1
end
return l
end
function builtins.makeSlice(f, n)
local s = {}
if n == nil then
n = 0
end
for i = 1, n do
table.insert(s, f())
end
return s
end
local inits = {}
function builtins.add_init(f)
table.insert(inits, f)
end
function builtins.run_inits()
for _, f in ipairs(inits) do
f()
end
end
local function _slice_iter(tbl, i)
i = i + 1 -- zero-based
local v = tbl[i+1]
if v then
return i, v
end
end
function builtins.slice_iter(tbl)
return _slice_iter, tbl, -1
end
local closureCache = setmetatable({}, {__mode="k"}) -- weak keys
function builtins.create_closure(obj, funcName)
-- See if we have a closure cache for this object already
local objClosures = closureCache[obj]
if objClosures == nil then
-- No cache for this object; create one
objClosures = {}
closureCache[obj] = objClosures
end
-- See if we have a closure created for this obj+funcName already
local f = objClosures[funcName]
if f ~= nil then
return f
end
-- No closure created; create a new one
f = function(...)
return obj[funcName](obj, ...)
end
-- Store the new closure in the cache
objClosures[funcName] = f
return f
end
`))
}