capture.love/mu.lua

76 lines
1.6 KiB
Lua
Raw Normal View History

2022-04-26 04:20:29 +01:00
curses = require 'curses'
local stdscr = curses.initscr()
2022-04-26 06:08:28 +01:00
curses.echo(false) -- unclear why implicit echo can't handle newlines, regardless of stdscr:nl()
2022-04-26 04:20:29 +01:00
stdscr:clear()
2022-04-26 06:08:28 +01:00
stdscr:scrollok(true)
local function readline()
local result = ''
while true do
local x = stdscr:getch()
stdscr:addch(x)
local c = string.char(x)
result = result .. c
if c == '\n' then break end
end
return result
end
2022-04-26 06:23:25 +01:00
-- based on https://github.com/hoelzro/lua-repl
2022-04-26 06:21:47 +01:00
function eval_print(f)
local success, results = gather_results(xpcall(f, function(...) return debug.traceback() end))
if success then
for i, result in ipairs(results) do
if i > 1 then
stdscr:addch('\t')
end
stdscr:addstr(tostring(result))
end
else
stdscr:addstr(tostring(result[1]))
end
stdscr:addch('\n')
end
2022-04-26 06:23:25 +01:00
local function gather_results(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
2022-04-26 06:08:28 +01:00
local new_expr = true
local buf = ''
while true do
if new_expr then
stdscr:addstr('> ')
else
stdscr:addstr('>> ')
end
buf = buf .. readline()
2022-04-26 06:23:25 +01:00
-- print value of expression the way Lua 5.3 does it: by prepending 'return' to the line
2022-04-26 06:21:47 +01:00
local f = load('return '..buf, 'REPL')
2022-04-26 06:08:28 +01:00
if f then
buf = ''
new_expr = true
2022-04-26 06:21:47 +01:00
eval_print(f)
2022-04-26 06:08:28 +01:00
else
local f, err = load(buf, 'REPL')
if f then
2022-04-26 06:08:28 +01:00
buf = ''
new_expr = true
2022-04-26 06:21:47 +01:00
eval_print(f)
else
if string.match(err, "'<eof>'$") or string.match(err, "<eof>$") then
buf = buf .. '\n'
new_expr = false
else
2022-04-26 06:21:47 +01:00
stdscr:addstr(err..'\n')
buf = ''
new_expr = true
end
2022-04-26 06:08:28 +01:00
end
end
end
2022-04-26 04:20:29 +01:00
curses.endwin()