Skip to content

Instantly share code, notes, and snippets.

@hoelzro
Created October 5, 2011 18:28
Show Gist options
  • Save hoelzro/1265250 to your computer and use it in GitHub Desktop.
Save hoelzro/1265250 to your computer and use it in GitHub Desktop.
A Lua REPL implemented in Lua
do
local buffer = ''
local function gather_results(success, ...)
local n = select('#', ...)
return success, { n = n, ... }
end
local function print_results(results)
local parts = {}
for i = 1, results.n do
parts[#parts + 1] = tostring(results[i])
end
print(table.concat(parts, ' '))
end
function evaluate_line(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 = gather_results(xpcall(f, debug.traceback))
if success then
-- successful call
if #results > 0 then
print_results(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)
end
end
return '>'
end
end
function display_prompt(prompt)
io.stdout:write(prompt .. ' ')
end
display_prompt '>'
for line in io.stdin:lines() do
local prompt = evaluate_line(line)
display_prompt(prompt)
end
@fmamud
Copy link

fmamud commented Aug 23, 2022

Your repl was useful for me on my side projects, thanks! 😄

Hint: Lua 5.2 changes deprecated loadstring and unpack, to load and table.unpack respectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment