Created
October 5, 2011 18:28
-
-
Save hoelzro/1265250 to your computer and use it in GitHub Desktop.
A Lua REPL implemented in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
I think this piece is wrong.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.