Created
January 16, 2016 16:56
-
-
Save cezarguimaraes/74b8a2dfc6fe94cb8b8b to your computer and use it in GitHub Desktop.
Interactive console for Lua 5.1
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
--[[ | |
Usage: | |
-- Start a console instance, holds its own environment | |
local console = InteractiveConsole { | |
sum = function(a, b) | |
return a + b | |
end | |
} | |
-- First call: define output and error functions | |
console(print, error) | |
-- Following calls: whatever the user types in | |
console 'a = {' | |
console ' 5, 6 | |
console '}' | |
console 'print(sum(unpack(a)))' --> 11 | |
]] | |
local function InteractiveConsole(env) | |
return coroutine.wrap(function(out, err) | |
local sandbox = setmetatable({ }, | |
{ | |
__index = function(t, index) | |
return rawget(t, index) or env[index] or _G[index] | |
end | |
} | |
) | |
sandbox._G = sandbox | |
sandbox.os = { } | |
sandbox.io = { } | |
sandbox.debug = { } | |
sandbox.error = err | |
sandbox.print = function(...) | |
local r = {} | |
for _, v in ipairs({...}) do | |
table.insert(r, tostring(v)) | |
end | |
local s = table.concat(r, string.rep(' ', 4)) | |
return out(#s > 0 and s or 'nil') | |
end | |
local chunks = {} | |
local level = 1 | |
while true do | |
table.insert(chunks, coroutine.yield()) | |
local func, e = loadstring(table.concat(chunks, ' '), 'console') | |
if func then | |
setfenv(func, sandbox) | |
out(string.rep('>', level) .. ' ' .. chunks[#chunks]) | |
local s, e = pcall(func) | |
if not s then | |
err(e) | |
end | |
chunks = { } | |
level = 1 | |
else | |
if not e:find('near \'<eof>\'$') then | |
chunks = { } | |
level = 1 | |
err(e) | |
else | |
out(string.rep('>', level) .. ' ' .. chunks[#chunks]) | |
level = 2 | |
end | |
end | |
end | |
end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Missing trailing
'
at line 15.