summaryrefslogtreecommitdiff
path: root/repl.lua
blob: 911e7c7a08494c65a83cf75026be7a48a99cf0d8 (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
54
55
56
57
58
59
local pprint=require"pprint"
pprint.setup{show_all=true,use_tostring=true}

local repl_env = {}

-- should use loadstring on 5.1
-- works on luajit though
local function load_chunk(s)
	return load(s,"repl","t")
end

local function prompt(p)
	io.write(p)
	return io.read()
end

local function read_chunk()
	-- try with return
	-- if that doesn't work try without return
	-- if error ends in <eof> try multiline

	local function try(text)
		local f, err = load_chunk("return "..text..";")
		if f then return f end

		local f, err = load_chunk(text)
		if f then return f end

		if err:sub(-5) == "<eof>" or err:sub(-7) == "'<eof>'" then
			local nt = text.."\n"..prompt("} ")
			return try(nt)
		end

		return f, err
	end
	return try(prompt("] "))
end

local function result(ok,...)
	if ok then
		pprint(...)
	else
		print("error: "..(...))
	end
end

local function msgh(e)
	return debug.traceback(e,1)
end

while true do
	local f,err = read_chunk()

	if not f then
		print("load error: "..err)
	else
		result(xpcall(f,msgh))
	end
end