Created
August 14, 2015 20:33
-
-
Save Maxs1789/41a846896d9fe50803dc to your computer and use it in GitHub Desktop.
Lua console coded in Lua.
This file contains 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
-- Print a prompt an read an input line | |
local function getline(line) | |
if line ~= "" then | |
io.write(">> ") | |
return line .. "\n" .. io.read() | |
end | |
io.write("> ") | |
return io.read() | |
end | |
-- Print an error message | |
local function printerr(error_msg) | |
error_msg = error_msg:gsub("%[.*%]:", "") | |
print(error_msg) | |
end | |
-- Load code from string | |
local function getcode(line) | |
local code, error_msg = loadstring(line) -- try to load the code | |
if code == nil then -- if syntax error | |
code = loadstring("print(" .. line .. ")") -- try auto print | |
else -- else | |
local retcode, err = loadstring("return " .. line) -- try auto return | |
if not err then | |
code = retcode | |
end | |
end | |
return code, error_msg | |
end | |
-- main | |
print(_VERSION) | |
local line = getline("") | |
while line ~= nil do | |
local code, error_msg = getcode(line) -- load code from line | |
if code ~= nil then -- if code is valid | |
local results = table.pack(pcall(code)) -- execute the code | |
local success = table.remove(results, 1) | |
line = "" -- clear the line | |
if not success then -- if failure | |
printerr(results[1]) -- print error | |
elseif #results > 0 then -- else if has results | |
print(table.unpack(results)) -- print results | |
end | |
elseif error_msg:sub(-5) ~= "<eof>" then -- else if not incomplete | |
line = "" -- clear the line | |
printerr(error_msg) -- print error | |
end | |
line = getline(line) -- read next line | |
end | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment