10

Is it possible to run a simple script inside LuaLaTeX or LaTeX?

For example, I need to use the calculator from the terminal. I'd like to write

$echo "100.83*4.53" | bc

and obtain the result in LuaLaTeX or LaTeX. Is there a command (called \runscript, for instance) that runs a script from within LuaLaTeX or LaTeX and that I could use as follows:

\runscript{echo "100.83*4.53" | bc}

and get "456.7599" as result?

Is it possible, perhaps with some Perl or Python script?

jub0bs
  • 58,916
Pankracy
  • 319

1 Answers1

12

With LuaTeX you can do something like this:

\documentclass{article}
\usepackage{luacode}
\begin{document}

\def\foo{\directlua{dofile("runfunc.lua")}}
\foo
\end{document}

and the file runfunc.lua is this:

local i,j = io.popen([[echo "100.83*4.53" | bc]])
if not i then
  print(j)
  os.exit(-1)
end
tex.sprint(-2,string.gsub(i:read("*all"),"%s*$",""))
i:close()

run with

lualatex --shell-escape ‹filename.tex›

to allow io.popen().

topskip
  • 37,020
  • 1
    @Pankracy If it works for you, it would be nice to "accept" my answer by clicking on the checkmark right below the number of votes of that question. – topskip May 18 '13 at 18:29
  • @topskip This is brilliant, but is there a way to pass in echo "100.83*4.53" | bc as an argument to the \foo command from the LuaTeX document directly? – Linus Arver Sep 18 '16 at 01:03
  • 1
    I found http://stackoverflow.com/questions/9676113/lua-os-execute-return-value and basically did this: \newcommand\foo[1]{\directlua{ local handle = io.popen([[#1]]) local result = handle:read("*a") tex.print(result) handle:close() }} and then just \foo{some shell command}. I'm sure there will be quoting problems for anything involving special characters, but for now it works well enough. – Linus Arver Sep 18 '16 at 01:09