-
Notifications
You must be signed in to change notification settings - Fork 4
/
repl.lua
72 lines (59 loc) · 1.39 KB
/
repl.lua
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
local utils = require('utils')
local uv = require('luv')
local buffer = ''
local prompt = '>'
io.stdin = uv.new_tty(0, 1)
io.stdout = uv.new_tty(1)
io.stderr = uv.new_tty(2)
io.stdout.write = uv.write
io.stderr.write = uv.write
local function gatherResults(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function printResults(results)
for i = 1, results.n do
results[i] = utils.dump(results[i])
end
print(table.concat(results, '\t'))
end
local function evaluateLine(line)
local chunk = buffer .. line
local f, err = loadstring('return ' .. chunk, 'REPL') -- first we prefix return
if not f then
f, err = loadstring(chunk, 'REPL') -- try again without return
end
if f then
buffer = ''
local success, results = gatherResults(xpcall(f, debug.traceback))
if success then
-- successful call
if results.n > 0 then
printResults(results)
end
else
-- error
print(results[1])
end
else
if err:match "'<eof>'$" then
-- Lua expects some more input; stow it away for next time
buffer = chunk .. '\n'
return '>>'
else
print(err)
buffer = ''
end
end
return '>'
end
uv.read_start(io.stdin)
io.stdout:write(prompt .. " ")
function io.stdin:ondata(line)
evaluateLine(line)
io.stdout:write(prompt .. " ")
end
function io.stdin:onend()
os.exit()
end
uv.run()