52

Although I always use LuaLaTeX to compile my documents, I don't really use Lua that often. Sometimes I even forget about it.

In my last document I used it to write a random word generator, which picks a word from a pool of words. Which can be really helpful in many different documents and circumstances. I came up with this code in another question, but I will repost it here, if someone wants to use it.

So today I asked myself, what are some other good uses for Lua in TeX documents? And here we go, now it's your turn to post your ideas.


Thanks for all the great answers. There are some great ideas, and I certainly can put them to good use in my own documents (and other users aswell, I guess :) ). In my opinion, every answer deserves the check mark, so I guess I will let the community decide and choose the one with the most upvotes.

That of course doesn't mean you have to stop posting your awesome ideas ;)

  • 5
    Lua is a Turing-complete programming language, so it's usage is... everything. – m0nhawk Aug 22 '14 at 12:49
  • Yes of course, but I wanted to know when and why you use it in your documents. Not when you just use lua... – Benutzer193 Aug 22 '14 at 12:54
  • 5
    Not a direct answer, but just take a look on the book by Herbert Voss: LuaLaTeX, with many examples. –  Aug 22 '14 at 13:02
  • @ChristianHupfer thanks, I didn't know this one. – Benutzer193 Aug 22 '14 at 13:17
  • 2
    See http://tex.stackexchange.com/questions/70. Also, not sure if these two count as 'good', but I'll mention them anyway: http://tex.stackexchange.com/questions/35676/using-command-to-compute-sum/35694#35694 http://tex.stackexchange.com/questions/36572/parse-simple-arithmetics-and-return-the-result/36735#36735 – Torbjørn T. Aug 22 '14 at 13:30
  • 4
    I think the greatest benefit of using LuaLaTeX from a user perspective is having packages like selnolig or impnattypo – cgnieder Aug 22 '14 at 15:17
  • @ChristianHupfer can you provide a link to the book on amazon or whatever? I can't seem to find it! – Vishesh Aug 22 '14 at 15:19
  • 1
    @Vishesh: I'll try, but I am unsure, whether the book is available so far only in German... http://www.amazon.de/Einf%C3%BChrung-LuaTeX-LuaLaTeX-Herbert-Vo%C3%9F/dp/386541530X/ref=sr_1_4?ie=UTF8&qid=1408720984&sr=8-4&keywords=Herbert+Voss... so far in German only –  Aug 22 '14 at 15:21
  • 4
    @m0nhawk TeX is a Turing-complete language on his own. – Michaël Le Barbier Aug 22 '14 at 15:42
  • @MichaelGrünewald Yes, but not a very useful in this role. – m0nhawk Aug 22 '14 at 15:45
  • 1
    @m0nhawk Well, you based your argumentation on Lua being Turing-complete, not I. :) Interesting aspects of Lua may well lie somewhere else. – Michaël Le Barbier Aug 22 '14 at 15:48
  • @MichaelGrünewald but some of them are more Turing-complete, than other. Some of them more applicable than the others. – m0nhawk Aug 22 '14 at 15:51
  • 2
    @m0nhawk Your initial argument is not that Lua is more Turing-complete than TeX is. Lua is a generalist extension language whose imperative paradigm is common and well understood while TeX is a specialised language focused on typesetting, which strange programming paradigm sits somewhere between M4 and machine language. If this is what you mean, nothing prevents you to put it this way. This would look like useful bits of information. – Michaël Le Barbier Aug 22 '14 at 16:04
  • 1
    I'd like to link to the Sieve of Erasthones question: http://tex.stackexchange.com/a/44748/86 The lua answer works far, far faster than a TeX version would do. – Andrew Stacey Aug 23 '14 at 12:50
  • @TorbjørnT.: May I suggest the SE Comment Link Helper? :-) – Martin Schröder Aug 25 '14 at 14:11

5 Answers5

36

LaTeX can not do all things you might want to typeset. Sometimes you might need the power of another (scripting) language. You are free to use Perl, PHP, bash scripts or what ever. But the main advantage of Lua is very simple - it's available. On all supported platforms. No need for the user to install anything else!

In my getmap package, I use a Lua script to connect web servers to download maps:

enter image description here

% compile with pdflatex -shell-escape
\documentclass{article}
\usepackage[latin1]{inputenc}
\usepackage{graphicx}
\usepackage{filecontents}
% use overwrite while optimizing the image
\usepackage[overwrite,mode=gm]{getmap}
\begin{document}
\begin{filecontents*}{berlin.epl}
&path=weight:5|color:purple|enc:_xq_IcgrpA?AFE@?^BFE@A^U@CLQXEZU?gCR?B?DBF@@?vA?D?D?BAHE@JBN@JLGFCG[DC~C?@?F?R?vA?p@iB@i@Fe@JWRSTOf@Gh@C^A?e@?gE?w@r@?lB@hA?`@??M?aA?]dI??O?O?Cn@cBfBeF|AeEHNVNBc@H@H_AEwA?OAMNA@N
\end{filecontents*}
\getmap[file=berlin, language=de, xsize=400, ysize=600,
        markers={&markers=size:mid|label:H|color:green|Berlin, Hbf
                 &markers=label:B|color:blue|Brandenburger Tor, Berlin},
        pathfile={berlin.epl}]{}
\includegraphics[width=6cm]{berlin}
\end{document}

The route was exported into a gpx file and converted to encoded polylines (Google's route format) by the very same Lua script:

getmapdl -m gpx2epl -G berlin.gpx

So, from my point of view, the embedded Lua interpreter opens new horizons!

Josef
  • 7,432
  • 4
    It looks a very nice package! – Claudio Fiandrino Aug 22 '14 at 15:19
  • compile with pdflatex? – marczellm Aug 23 '14 at 10:58
  • 4
    Why not? ;-) -shell-escape is the important part! If you want to use lua in your document, then it works only with lualatex. OTOH, getmap calls an external lua script, which means the script is executed with texlua. That's the lua interpreter of luatex. This works for all engines including pdflatex. But it needs the -shell-escape switch to allow the execution of external scripts. – Josef Aug 23 '14 at 11:09
  • Somewhat related, nowadays there's lt3luabridge to call Lua code from pdftex which wraps the manual write18. – user202729 Jul 13 '22 at 03:27
28

The latest version of Tikz supports automatic graph layout with LuaTeX. When the appropriate TikZ options are given, a selection of Lua scripts are invoked that receive the structure of the graph and compute the positions of the nodes. A variety of automatic graph layout algorithms are supported. The API for writing your own algorithm in Lua is also documented in the manual. C/C++ is also supported through the runtime dynamic linking feature of Lua itself.

Example from the manual (note the layered layout option):

graph example

\documentclass[tikz]{standalone}
\usetikzlibrary{arrows.spaced,graphdrawing,graphs}
\usegdlibrary{layered}
\begin{document}
\tikz [nodes={text height=.7em, text depth=.2em,
              draw=black!20, thick, fill=white, font=\footnotesize},
       >=spaced stealth', rounded corners, semithick]
  \graph [layered layout, level distance=1cm, sibling sep=.5em, sibling distance=1cm] {
    "5th Edition" -> { "6th Edition", "PWB 1.0" };
    "6th Edition" -> { "LSX" [>child anchor=45], "1 BSD", "Mini Unix", "Wollongong", "Interdata" };
    "Interdata" -> { "Unix/TS 3.0", "PWB 2.0", "7th Edition" };
    "7th Edition" -> { "8th Edition", "32V", "V7M", "Ultrix-11", "Xenix", "UniPlus+" };
    "V7M" -> "Ultrix-11";
    "8th Edition" -> "9th Edition";
    "1 BSD" -> "2 BSD" -> "2.8 BSD" -> { "Ultrix-11", "2.9 BSD" };
    "32V" -> "3 BSD" -> "4 BSD" -> "4.1 BSD" -> { "4.2 BSD", "2.8 BSD", "8th Edition" };
    "4.2 BSD" -> { "4.3 BSD", "Ultrix-32" };
    "PWB 1.0" -> { "PWB 1.2" -> "PWB 2.0", "USG 1.0" -> { "CB Unix 1", "USG 2.0" }};
    "CB Unix 1" -> "CB Unix 2" -> "CB Unix 3" -> { "Unix/TS++", "PDP-11 Sys V" };
    { "USG 2.0" -> "USG 3.0", "PWB 2.0", "Unix/TS 1.0" } -> "Unix/TS 3.0";
    { "Unix/TS++", "CB Unix 3", "Unix/TS 3.0" } -> "TS 4.0" -> "System V.0" -> "System V.2" -> "System V.3";
};
\end{document}
mvkorpel
  • 1,598
marczellm
  • 11,809
24

LuaTeX provides all kinds of new hooks into the innards of TeX's operations. The paragraph-building algorithm, for one, has been opened up in several, very useful ways. This functionality enables the creation of new packages that do all kinds of stuff that simply wasn't possible before.

For instance, the selnolig package -- which performs selective suppression of typographic ligatures, for both German and English language texts, without the need for either tedious hand mark-up or the running of a pre-processor -- depends crucially on various LuaTeX callbacks to do its job. Without LuaTeX, this package would simply not exist. (Full disclosure: I'm the main author of this package.)

Mico
  • 506,678
22

This may be thought of an extended comment to phg's answer. As an academic, I need to maintain multiple versions of my CV. For examples, one version of the CV must include all the publications, another should only include publications in the last five years, and another publications in the last six years! One should include a table that lists all grants and specify the amount of funding each year, the other only a list of grants with just the total amount mentioned. There are similar requirements for other fields of the CV.

In summary, the same data needs to be filtered differently and presented differently for each version. Manually maintaining multiple versions is an error-prone task. So, here is what I do (using ConTeXt):

  1. All the data goes into different XML files. One file for publications, one for grants, etc. The advantage is that validate the data using standard XML tools.

  2. Use the ConTeXt XML library to convert the XML file into Lua tables.

  3. Create Lua functions to filter data from the Lua tables. For example, one function discards all publications that is more than n years old, another adds the grant amount for each year to compute the total amount, etc.

  4. Create Lua functions to typeset according to each requirement. These are written in the CLD (ConTeXt Lua Document) format.

  5. Now each version of the CV is easy to maintain. For example one has

    \startluacode
       cv.list_of_publications("journal", "all")
    \stopluacode
    

    while the other has

    \startluacode
       cv.list_of_publications("journal", 6)
    \stopluacode
    

    and so on.

In principle, it is possible to do all this by programming in TeX as well. After all, TeX is Turing complete. But it is much easier to do this with XML + Lua.

It is also possible to use any standard programming language to do this task. After all, every language has an XML parser, and CLD interface is easy to replicate with a well thought out TeX library. However, with such an interface all communication between the library and TeX takes place through text files. If something goes wrong, then debugging can be a pain. Ask anyone who has tried to debug why TeX labels do not appear in MP files!

Aditya
  • 62,301
19

Taking the question seriously, here are a few examples from the Context sources†:

Note that much of the functionality is spread over multiple files. I only linked the entry points / main files in these cases.

  • 6
    Saying that is the new bibliography system is misleading (and possibly mischievous?) since biber and biblatex are also a new bibliography system. (Whether they make bibtex obsolete is another matter.) Neither of these (nor other alternatives) can be accurately described as the new system. They are each a new system. – cfr Aug 22 '14 at 23:31
  • 6
    @cfr neither Biber nor Biblatex work with Context, and Bibtex outside of Latex was always a hack. So, yes, it is in fact the new bibliography system, as far as Context is concerned. – Philipp Gesang Aug 22 '14 at 23:37
  • 3
    But the question is about Lua and not about ConTeXt specifically. Since we have LuaLaTeX, biber and biblatex is definitely a Lua-compatible system. I stand by the claim: it is inaccurate to claim that system is the new system in the context of this question. Indeed, since the question mentions LuaLaTeX, if anything, biber + biblatex is the new bibliographic system in this context. – cfr Aug 22 '14 at 23:39
  • @cfr -- The answer clearly uses the word ConTeXt in the first sentence. I think the "context" is pretty clear. (Though I'm not arguing against edits.) But Biber (Perl) and biblatex (LaTeX) have no necessary tie to Lua, so they should not be mentioned. – jon Aug 23 '14 at 03:48
  • 1
    @jon I'm not suggesting they should be mentioned. I'm only disagreeing with the use of the definite article in the answer and, to me, that use combined with the comment about bibTeX clearly suggests that the link is the new bibliography system (and that this is one of the listed advantages of conTeXt). – cfr Aug 23 '14 at 15:28
  • Some of the links are broken. Maybe a check is in order. – Faheem Mitha Aug 15 '21 at 16:01