Small example is given that generate Latex code on the fly. One uses Lua in which the Lua code is embedded inside the main Latex file itself using
and the other example uses Python to generate the complete Latex document to a file, which is then compiled using either pdflatex or lualatex.
When using the Lua method, the file has to be compiled using lualatex.
Python is one of the few dynamics languages that supports multi-line raw strings using the r""" .... """ construct. This feature allows any arbitrary content to be used as is inside this construct. It also allows one to concatenate Python variables with the string to build the final Latex output. Without this feature, using Python to generate Latex code would not be practical to do.
The example used (slightly modified) is an arbitrary one which builds small multiplication table taken from http://tex.stackexchange.com/questions/69164/why-does-luaexec-work-but-the-luacode-environment-doesnt answer by Herbert. There was no specific reason to pick this example, I just wanted to try to compare using Lua vs. Python to do this, and I was browsing and just saw this example there and it seemed like a good one to try to compare Lua with Python on. More examples will be added.
When the generated Latex code is compiled, it will generate this output:
The two methods are best contrasted and compared using the following diagram. The python script is first compiled using Python, then the generated Latex file is compiled using either lualatex or pdflatex.
Here is the Lua and the Python code, side by side, for comparison
num = 6
for i=1,num do
for j=1,num do
product = '$'..i..'\\times'..j..'='..i*j..'$';
my_file = open("py_latex.tex", 'w')
num = 6
for i in range(1,num+1):
for j in range(1,num+1):
x=x+'$'+str(i)+' \\times '+str(j)+' = '+str(i*j)+'$'
if j<num :
The Latex file generated by the Python code above is the following, which is then compiled using pdflatex
It is clear than both using Lua or Python to generate the table is much easier than using direct Tex coding (programming directly in Tex is very hard for most of us and can only be done by the real Latex programmers with many long years of Latex programming).
Using a higher level language such as Lua or Python is much simpler as the languages are easier to program in.
Currently I use Python to generate Latex files. For example, the following page was generated from one Python script.
There are advantages to both methods. And it is left to the reader to decide which method might work for them. This note is meant to only illustrate the methods and document them.