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?

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

1 Answer 1

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().

3
  • 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, 2013 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? Sep 18, 2016 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. Sep 18, 2016 at 1:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .