summaryrefslogtreecommitdiff
path: root/repl.lua
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2023-01-26 15:30:43 +0000
committerubq323 <ubq323@ubq323.website>2023-01-26 15:30:43 +0000
commit1a83a31a6012996afa5f5c62cab3aa5ec5d249f4 (patch)
tree6f2b61fc126665802945656a0bcba927e496d876 /repl.lua
first
Diffstat (limited to 'repl.lua')
-rw-r--r--repl.lua59
1 files changed, 59 insertions, 0 deletions
diff --git a/repl.lua b/repl.lua
new file mode 100644
index 0000000..911e7c7
--- /dev/null
+++ b/repl.lua
@@ -0,0 +1,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