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
@glyh
Copy link

glyh commented Jan 2, 2022

I think this piece is wrong.

    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 

For example, I have some codes "f()" to evaluate, where f will through error, no matter what happens. it also change the internal state of lua. The above scripts will cause the internal state to change twice, which is obviously not correct.

Do you have some tips on how to fix this? Thanks a lot!

(BTW I know you have designed a REPL library, but because of some technical reasons I don't want to use it)

Nevermind, I found I was wrong.

@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