Skip to content

Instantly share code, notes, and snippets.

@tarleb
Last active October 21, 2022 11:02
Show Gist options
  • Save tarleb/fc6718bcfc74fd68f324d938cdb6f350 to your computer and use it in GitHub Desktop.
Save tarleb/fc6718bcfc74fd68f324d938cdb6f350 to your computer and use it in GitHub Desktop.
Helper function for interactive Lua filters
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
@tarleb
Copy link
Author

tarleb commented May 12, 2022

Example use in pandoc Lua filter:

-- Ensure that, if the REPL is quit via `STOP = true`,
-- processing is skipped for **all remaining** `Str` elements.
local Str_env = {STOP = false}
Str = function (str) return interactive(str, Str_env) end
Pandoc = interactive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment