Last active
September 29, 2024 21:18
-
-
Save tarleb/fc6718bcfc74fd68f324d938cdb6f350 to your computer and use it in GitHub Desktop.
Helper function for interactive Lua filters
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
function interactive (it, env) | |
local has_readline, RL = pcall(require, 'readline') | |
if not has_readline then | |
RL = { | |
readline = function (prompt) | |
io.stdout:write(prompt) | |
return io.read() | |
end | |
} | |
end | |
-- setup environment in which the commands are run | |
env = env or {} | |
for k, v in pairs(_ENV) do | |
env[k] = v | |
end | |
env.it = it | |
local success, result | |
local line | |
while not env.STOP do | |
line = RL.readline('pandoc> ') | |
if not line or line == 'exit' or line == 'quit' then | |
break | |
end | |
-- Try to interpret the input as an expression. If that fails, | |
-- retry and treat it as a block. | |
success, result = pcall(load('return ' .. line, '<repl>', 't', env)) | |
if not success then | |
success, result = pcall(load(line, '<repl>', 't', env)) | |
end | |
if success then | |
io.stdout:write(tostring(result) .. '\n') | |
else | |
io.stderr:write(tostring(result) .. '\n') | |
end | |
end | |
return env.it | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use in pandoc Lua filter: