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?

  • 1
    You can directly do the computation with Lua. – egreg May 18 '13 at 12:35
  • @dıʞsdoʇ What about os.exec in LuaTeX? Is it practical? – egreg May 18 '13 at 13:09
  • @egreg os.exec() is perfect for that task – topskip May 18 '13 at 13:14
  • @egreg meybe not. os.exec not include data to lualatex – Pankracy May 18 '13 at 13:53
  • 1
    LaTeX solution is explained here. – g.kov May 18 '13 at 14:29

With LuaTeX you can do something like this:



and the file runfunc.lua is this:

local i,j = io.popen([[echo "100.83*4.53" | bc]])
if not i then

run with

lualatex --shell-escape ‹filename.tex›

to allow io.popen().

  • 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 1:03
  • 1
    I found 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 1:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.