Debian Codegraph @

texmf-dist/doc/latex/tkz-elements/TKZdoc-elements-lua.tex

raw
1 \newpage
2 \section{LuaLaTeX for Beginners: An Introduction to Lua Scripting}
3
4 \subsection{Introduction to Lua with LaTeX}
5
6 \tkzEngine{\LUALATEX} is a variant of LaTeX that integrates Lua as a scripting language. This enables:
7
8 \begin{itemize}
9 \item Perform advanced calculations.
10 \item Manipulate text and data.
11 \item Generate dynamic content in a document.
12 \end{itemize}
13
14 \subsection{Using Lua in a LaTeX document}
15
16 In \tkzNamePack{tkz-elements}, I only use two ways of integrating code into \tkzname{Lua}, which are as follows:
17
18 \begin{itemize}
19 \item Lua code block with \tkzMacro{lualatex}{directlua}. Note\footnote{You can use the \tkzEnv{luacode}{luacode} environment, after loading the package of the same name. The \tkzEnv{tkz-elements}{tkzelements} environment can also be used.}
20
21 Lua code can be executed directly in a document using \tkzMacro{lualatex}{directlua}:
22
23 |\directlua{tex.print(math.exp(1))}| --> \directlua{tex.print(math.exp(1))}
24
25 \item Loading an external Lua file:
26
27 You can write a separate Lua script and load it with: \tkzFct{lua}{dofile}, \tkzFct{lua}{loadfile} or \tkzFct{lua}{require}. Each of these functions has its own advantages, depending on the circumstances; initially, we'll be focusing on the first two.
28
29 \emph{dofile:} Immediately executes a Lua file. Equivalent to loadfile(filename)()
30
31 \emph{loadfile:} Loads a Lua file into memory (without executing it immediately); returns a function to execute.
32
33 \emph{require:} Loads a Lua module once (via package.loaded) and executes it; uses package.path to search for the file.
34
35
36 Examples are provided in this documentation, which you can see:
37
38 [\ref{sec:work_organization}] |\directlua{dofile("lua/sangaku.lua")}|
39
40
41 \end{itemize}
42
43 \tkzRHand How to comment in a file under \tkzEngine{\LUALATEX}. There are several cases to consider: in the \LATEX{} part outside a |directlua| directive, the \% symbol is always used. Within a |\directlua| directive, \% is still used. In an external file |fic.lua|, the symbol for a single-line comment in Lua is |--| (two hyphens).
44
45 With \tkzEnv{luacode}{luacode} environment, you need to use two hyphens.
46
47 The next subsection describes some of the differences between \TeX{} and LuaTeX{} for special characters and catcodes.
48
49 \subsection{Special Characters and Catcodes in \tkzNamePack{Lua\TeX}} % (fold)
50 \label{sub:special_characters_and_catcodes}
51
52 \tkzHand{\textcolor{red}{Warning}}:
53 Working with \tkzNamePack{Lua\TeX} exposes deep differences between how Lua and \TeX{} handle characters—especially special characters—and how category codes (catcodes) are assigned and interpreted.
54
55 \subsubsection{What Are Catcodes in \LaTeX?} % (fold)
56 \label{ssub:what_are_catcodes}
57
58 In \LaTeX{}, every character is associated with a \emph{category code}, or \emph{catcode}, which determines how \TeX{} interprets it during input processing.
59
60
61 \begin{tabular}{lll}
62 \toprule
63 \textbf{Character} & \textbf{Catcode} & \textbf{Meaning} \\
64 \midrule
65 \verb|\| & 0 & Escape character (starts a control sequence) \\
66 \verb|{| & 1 & Begin group \\
67 \verb|}| & 2 & End group \\
68 \verb|#| & 6 & Macro parameter \\
69 \verb|^| & 7 & Superscript (in math mode) \\
70 \verb|%| & 14 & Comment character \\
71 \bottomrule
72 \end{tabular}
73
74
75 These catcodes can change dynamically within a macro or document. This flexibility is powerful, but also risky when interfacing with Lua.
76
77 % subsubsection what_are_catcodes (end)
78
79 \subsubsection{Lua Does Not Understand Catcodes} % (fold)
80 \label{sub:lua_does_not_understand_catcodes}
81
82 Lua interprets strings as sequences of bytes or UTF-8 code points. It has \emph{no concept of catcodes}. When Lua sends content to \TeX{} using \tkzMacro{lualatex}{directlua}, the interpretation is performed by \TeX{} according to the current catcode settings.
83
84 This discrepancy leads to common issues:
85
86 \begin{itemize}
87 \item Special characters such as \verb|#|, \verb|%|, or \verb|^| are not escaped, which can break the \LaTeX{} parser.
88 \item Control sequences may be misinterpreted if \verb|\| is improperly used or redefined.
89 \item Group delimiters (\verb|{| and \verb|}|) inserted from Lua may be incorrectly parsed, especially when injected into macros using \tkzFct{lualatex}{tex.sprint}.
90 \end{itemize}
91
92 % subsubsection lua_does_not_understand_catcodes (end)
93
94 \subsubsection{Typical Problem Examples} % (fold)
95 \label{ssub:typical_problems}
96
97 \begin{itemize}
98 \item \textbf{Hash (\#)}: Printing \verb|\mycmd{#1}| from Lua may raise an error if \verb|#| does not have catcode 6 or is not escaped correctly.
99 \item \textbf{Newlines (\texttt{\textbackslash n})}: Lua uses \verb|\n| for line breaks, which are not valid in TeX input unless passed through \tkzMacro{latex}{scantokens}.
100 \item \textbf{Percent (\%)}: The \% (percent) symbol is special to both (La)TeX and Lua, but in very different ways. In (La)TeX, it's the default comment character. In Lua, it's one of the "magic" characters in pattern matching operations. (Lua's other "magic" characters are |^$()[]*+-?]|.)
101
102 \end{itemize}
103
104
105 \subsection{Interaction between Lua and LaTeX}
106
107 \tkzEngine{\LUALATEX} allows you to interact with LaTeX, in particular via:
108
109 \begin{itemize}
110 \item \code{|tex.print()|}: displays text in LaTeX.
111 \item \code{|tex.sprint()|}: inserts content without extra space.\\
112 \end{itemize}
113
114 \begin{mybox}
115 \begin{verbatim}
116 |\directlua{tex.sprint("\\textbf{Bold text generated by Lua}")}|
117 \end{verbatim}
118 \directlua{tex.sprint("\\textbf{Bold text generated by Lua}")}
119 \end{mybox}
120
121
122 \subsection{The variables}
123
124 \begin{mybox}
125 In Lua, a variable is a named label that stores a value. Its type is determined dynamically by the value assigned to it, and its scope (global or local) influences where it can be used in your program.
126 \end{mybox}
127
128 Let's analyze what we've just written. Four points are important: "named label", "type of value", "dynamically" and "scope".
129
130
131 \subsubsection{Named label}
132
133 The name you assign to a variable must follow certain rules:
134
135 \begin{itemize}
136 \item They can contain letters (a-z, A-Z), digit (0-9) and the underscore symbol (\_).
137 \item They cannot start with a digit.
138 \item They are case-sensitive.
139 \item Some Lua keywords (such as if, then, function, local, etc.) are reserved and cannot be used as variable names.
140 \end{itemize}
141
142 \subsubsection{Data types}
143 \label{ssub:types}
144 What types of values can be assigned to a variable? Here's a list of the simplest:
145
146 \begin{itemize}
147 \item \textbf{nil}: undefined value.
148 \item \textbf{boolean}: \texttt{true} or \texttt{false}.
149 \item \textbf{number}: double-precision floating-point numbers (reals).
150 \item \textbf{string}: strings.
151 \item \textbf{table}: associative data structures(key-value) and arrays.
152 \item \textbf{function}: anonymous or named functions.
153 \end{itemize}
154
155 \subsubsection{Dynamically}
156
157 The type is defined by the assigned value. So when \code{|x = 5|} then the type of \code{x} is \code{number}, but if \code{|x = true|} then its type changes to \code{boolean}.
158
159 \tkzRHand This warning was issued earlier concerning classes and variables reserved by the \tkzNamePack{tkz-elements}. For example, you cannot use: \code{circle} with $circle = ...$ which would result in losing the use of the class \tkzClass{circle}. Similarly, $C= 1$ would result in the loss of the contents of the table \tkzVar{circle}{C}.
160
161 \subsubsection{Scope and block}
162
163 \begin{enumerate}
164
165 \item \code{\textbf{Block}}\\
166 In Lua, a block is a sequence of statements that are treated as a single unit. Blocks in Lua are delimited by specific keywords. They are crucial for structuring code, defining the scope of local variables, and controlling the flow of execution.
167
168 Here are the primary ways blocks are defined in Lua:
169
170 \begin{itemize}
171 \item \code{|do ... end|}. This explicitly creates a block. Any local variables declared within a do...end block are only accessible within that block.
172
173 \item \code{|if ... then ... else ... end|} or \code{|if...then...elseif...then...end|}. The statements between then and end (or else and end, or the then following elseif) form a block that is executed conditionally.
174
175 \item \code{|for...do...end|} or \code{|while...do...end|} The body of the loop, between do and end, is a block that is executed repeatedly.
176
177 \item \code{|function...end|}. The body of a function, between function and end, is a block that contains the function's code.
178 \end{itemize}
179
180
181 \item \code{\textbf{Scope}}\\
182 Lua has two main types of scope: global or local. The scope of a variable determines where in your code that variable is accessible. By default, a variable that is assigned a value without being explicitly declared (with local) is global. It is recommended and preferable to declare only local variables in a function or block. This is done by adding \code{local} in front of the variable name.
183
184 A variable declared as \code{local} in a block is not accessible outside it.
185
186 Example:
187
188 \begin{mybox}
189 \begin{verbatim}
190 \directlua{
191 do
192 local x = 10
193 tex.print(x) % Accessible here
194 end
195 tex.print(x) % Error! x is out of scope here}
196 \end{verbatim}
197 \end{mybox}
198 \end{enumerate}
199
200 \subsection{The values}
201
202 Let's see what you need to know about the main values.
203
204 % \begin{enumerate}[label=(\greek*)]
205
206 \subsubsection{\code{nil}}
207
208
209 \begin{itemize}
210
211 \item \code{nil} is the most basic and its own data type. \code{nil} is used to indicate that a variable has not yet been assigned a value, or that a value has been explicitly suppressed.
212
213 \begin{mybox}
214 \begin{verbatim}
215 \directlua{
216 tex.print(tostring(no_assigned))}
217 and
218 tex.print(type(no_assigned)) gives
219 \end{verbatim}
220 \directlua{tex.print(tostring(no_assigned))}
221 \directlua{tex.print(type(no_assigned))}
222 \end{mybox}
223
224 \item Table and \code{nil}.\\
225
226 Assigning \code{nil} to a key removes that entry from the table. It's possible to delete a table using \code{nil}. This can free up memory if there are no other references to this table.
227
228 \end{itemize}
229
230 \subsubsection{Booleans}
231
232 \begin{itemize}
233 \item In Lua, there are only two boolean values: \code{true} and \code{false}.
234 \item Booleans belong to the boolean data type.
235 \item They are manipulated using logical operators (\code{and}, \code{or}, \code{not}) to form more complex boolean expressions.
236 \item Unlike many other languages, in Lua, only the values false and nil are considered false in a boolean context (e.g., in an if condition).
237 If you want to distinguish between nil and false you need to be more explicit
238 \begin{mybox}
239 \begin{verbatim}
240 if v == false then
241 ...
242 elseif v == nil then
243 ...
244 else
245 ...
246 end
247 \end{verbatim}
248 \end{mybox}
249 \end{itemize}
250
251 \subsubsection{Number}
252
253
254 \begin{itemize}
255 \item Single Numeric Type. Lua has only one numeric type for representing real (double-precision floating-point) numbers. This means that all numbers, whether they look like integers or have decimal points, are treated the same.
256
257 \item Lua uses a standard 64-bit floating-point representation.
258 \item Even though there's only one numeric type, Lua handles integer values efficiently.
259
260 \item Arithmetic Operators.Lua supports the standard arithmetic operators. It is worth noting|%| (modulo) The remainder of the division and |//| (floor division) - Divides and rounds the result down to the nearest integer.
261 You can use functions defined in the math library.
262
263 \item A number can be transformed into a string with the \code{tostring} function. Example: a = 10 b = "1" c = tostring(a) .. b. Finaly, |tex.print(c)| gives $101$.\\
264 Remark: in some cases, operations like \code{addition} or \code{concatenation} transform the type of one of the operands to obtain a result, but there are many special cases.
265
266 \end{itemize}
267
268 \subsubsection{Strings}
269
270 \begin{enumerate}[label=(\alph*)]
271 \item Construction
272
273 You can define string literals in Lua using single quotes ('...'), double quotes ("..."), or double square brackets ([[...]]), but there are differences between these methods. There are no major problems if the strings don't contain any special characters.
274
275
276 A first small problem arises if we want to include a single quote or a double quote into the string. The simplest method is to define the string with the double square brackets. You can include a single quote inside a string defined with double quote or vice versa.
277
278 \begin{tkzexample}[latex=.4\textwidth]
279 \directlua{tex.print('a string with " ')}
280 \end{tkzexample}
281
282 And if you like a bit of a challenge, it's still possible to include a double quote inside a string defined with double quotes. This time, to use a common method with \TeX{}, we try to write \", but this leads to an error. Simply inactivate \" with \string\" to obtain the correct result.
283
284 \begin{tkzexample}[latex=.4\textwidth]
285 \directlua{tex.print("a string with \string\" ")}
286 \end{tkzexample}
287
288
289
290 \item Concatenation: \code{|..|}. An interesting example is the ability to create multiple variables:
291 \begin{mybox}
292 \begin{verbatim}
293 local t= {}
294 local i = 5
295 t["x_" .. tostring(i)] = 11
296 tex.print(t.x_5)
297 \end{verbatim}
298
299 \end{mybox}
300
301
302 \item Lua provides a powerful string library (string) with many useful functions for manipulating strings. Here are some common ones:
303
304 \begin{itemize}
305
306 \item \code{string.char(n)},
307 \item \code{string.len(s)},
308
309 \item \code{string.sub(s, i [, j])},
310
311 \item \code{string.find(s, pattern [, init [, plain]])},
312
313 \item \code{string.gsub(s, pattern, repl [, n])},
314
315 \item \code{string.format(formatstring, ...)}, etc.
316 \end{itemize}
317
318 \item Special or magic characters in the library \code{String}\\
319
320 \begin{center}
321 \begin{tabular}{@{}ll@{}}
322 \toprule
323 \textbf{Character} & \textbf{Meaning} \\
324 \midrule
325 \texttt{.} & Matches any character \\
326 \texttt{\%} & Escape character (for magic characters) \\
327 \texttt{+} & One or more repetitions \\
328 \texttt{-} & Zero or more repetitions (minimal) \\
329 \texttt{*} & Zero or more repetitions (greedy) \\
330 \texttt{?} & Zero or one occurrence \\
331 \texttt{[ ]} & Character class \\
332 \texttt{\^{}} & Beginning of string \\
333 \texttt{\$} & End of string \\
334 \bottomrule
335 \end{tabular}
336 \end{center}
337
338 \item Character Classes (after \texttt{\%})
339
340 \begin{center}
341 \begin{tabular}{@{}ll@{}}
342 \toprule
343 \textbf{Code} & \textbf{Meaning} \\
344 \midrule
345 \texttt{a} & Letters (A-Z, a-z) \\
346 \texttt{c} & Control characters \\
347 \texttt{d} & Digits (0-9) \\
348 \texttt{g} & Printable characters (except space) \\
349 \texttt{l} & Lowercase letters \\
350 \texttt{p} & Punctuation characters \\
351 \texttt{s} & Space characters \\
352 \texttt{u} & Uppercase letters \\
353 \texttt{w} & Alphanumeric characters \\
354 \texttt{x} & Hexadecimal digits (0-9, A-F, a-f) \\
355 \texttt{z} & Null character (ASCII 0) \\
356 \bottomrule
357 \end{tabular}
358 \end{center}
359
360 \item Notes
361 \begin{itemize}
362 \item To match a literal magic character (like \texttt{.} or \texttt{*}), prefix it with \texttt{\%}.
363 \item Uppercase codes (\texttt{\%A}, \texttt{\%D}, etc.) match anything \emph{except} the corresponding class.
364 \end{itemize}
365
366 \item String.format in LuaLaTeX - Memo Sheet
367 I've chosen to place the code \tkzname{Lua} as an argument to the |directlua| directive, which means you'll have to keep an eye out for any special symbols (\#, \%, \_ etc.) you may be tempted to use.
368
369 \begin{center}
370 \begin{tabular}{@{}ll@{}}
371 \toprule
372 \textbf{Lua format} & \textbf{Description} \\ \midrule
373 \texttt{\%d} & Decimal integer (7 or 7.0) \\
374 \texttt{\%i} & Placeholder for an integer or hexadecimal) \\
375 \texttt{\%f} & Floating-point number (fixed precision) \\
376 \texttt{\%g} & Floating-point number (automatic precision) \\
377 \texttt{\%s} & Placeholder for a string \\
378 \texttt{\%e} & Scientific notation (exponent) \\
379 \texttt{\%\%} & Percent sign (escaping) \\
380 \texttt{\%-5d} & Left-align the integer with a field width of 5 \\
381 \texttt{\%10.2f} & Right-align a floating-point number with width 10 and 2 decimal places \\
382 \texttt{\%.2f} & Floating-point number with 2 decimal places \\
383 \texttt{\%g} & Floating-point number with general format \\ \bottomrule
384 \end{tabular}
385 \end{center}
386
387
388 * Basic Formatting
389 \begin{itemize}
390 \item \texttt{string.format(\%d, 5)} outputs: \texttt{5}
391 \item \texttt{string.format(\%f, 2.5)} outputs: \texttt{2.500000}
392 \item \texttt{string.format(\%g, 1234567.89)} outputs: \texttt{1.23457e+06}
393 \item \texttt{string.format(\%s, "z.A")} outputs: \texttt{z.A}
394 \end{itemize}
395
396 * Mathematical Expressions in LaTeX
397 You can easily format mathematical expressions like powers and equations:
398 \begin{itemize}
399 \item \texttt{string.format(\$ \%d \textasciicircum 3 = \%d \$, x, x\textasciicircum3)} will output something like \texttt{\$8\textasciicircum 3 = 512\$}
400 \end{itemize}
401
402 * Special Characters
403 \begin{itemize}
404 \item \texttt{string.format(\%\%)} outputs: \texttt{\%}
405 \end{itemize}
406
407
408 \item If s = "example" then |tex.print(s:len())| gives $7$.
409 \end{enumerate}
410
411 \subsubsection{The Tables}
412
413 \begin{itemize}
414
415 \item Definition\\
416 In Lua, the table type implements associative arrays and are the only data structure available. This means that an association is created between two entities. The first is named key and the second value. A key is associated with a unique value. A key can be an integer, a real (rare but possible), a string, a boolean, a table, a function, but not nil.
417
418 A very frequent special case concerns tables whose keys are consecutive integers from 1. These are simply referred to as arrays, in which case the keys are indices.
419
420
421 \item Table creation.\\
422 The simplest way to create a table is with the constructor expression \{\}, but the following example uses sugar syntax
423
424 \begin{mybox}
425 \code{t = \{one = 1, two = 4, three = 9, four = 16, five = 25\}} \\
426 Pairs (key,value) are separated by commas or semicolons. The key is to the left of the = sign and the value to the right.
427 | t.one = 1; t.two = 4; etc.|
428 \end{mybox}
429
430 In fact, this corresponds to
431
432 \begin{mybox}
433 \code{t = \{["one"] = 1, ["two"] = 4, ["three"] = 9, ["four"] = 16, ["five"] = 25\}} \\
434 \end{mybox}
435
436 which is the most general definition of a table.
437
438 | t.["one"] = 1; t.["two"] = 4; etc.|
439
440 The use of sugar syntax is pleasant for the user, but it hides important points. First, the \code{dot notation} for string keys is valid only if the string keys follow the rules for Lua identifiers (alphanumeric and underscore, not starting with a digit).
441
442 \item Table Manipulation.\\
443 There are in built functions for table manipulation and they are listed in the following table.
444
445 \begin{table}[htbp]
446 \centering
447 \caption{Built-in Table Manipulation Functions in Lua}
448 \begin{tabular}{@{}ll@{}}
449 \toprule
450 \textbf{Function} & \textbf{Description} \\
451 \midrule
452 \texttt{table.insert(t, [pos,] value)} & Inserts a value into table \texttt{t} at position \texttt{pos} (default: end). \\
453 \texttt{table.remove(t, [pos])} & Removes the element at position \texttt{pos} from table \texttt{t}. \\
454 \texttt{table.sort(t [, comp])} & Sorts the elements of table \texttt{t} in-place. Optional comparator. \\
455 \texttt{table.concat(t [, sep [, i [, j]]])} & Concatenates elements of \texttt{t} from \texttt{i} to \texttt{j} using separator \texttt{sep}. \\
456 \texttt{table.unpack(t [, i [, j]])} & Returns the elements of \texttt{t} from index \texttt{i} to \texttt{j}. \\
457 \texttt{table.pack(...)} & Returns a new table with all arguments stored as elements. \\
458
459 \bottomrule
460 \end{tabular}
461 \end{table}
462
463
464
465
466
467
468 \item Accessing elements: You can access table elements using square brackets [] with the corresponding key. If the key is a valid string identifier, you can also use dot notation (.).
469 \item Deleting elements: To remove an element from a table, simply assign the value nil to its key.
470 \end{itemize}
471
472 \subsubsection{Functions}
473
474 In Lua, functions possess first-class status, which means they can be assigned to variables, provided as arguments to other functions, and used as return values from functions.
475
476 \begin{enumerate}[label=(\alph*)]
477 \item Basic Syntax
478
479 \begin{tkzexample}[latex=.4\textwidth]
480 \directlua{
481 function cubic(x)
482 return x^3
483 end
484 tex.print(cubic(5))}
485 \end{tkzexample}
486
487 \item Parameters and Return Values\\
488
489 Functions can take any number of parameters and return multiple values. Let's look at an example that illustrates this case and shows some of the difficulties associated with Lua's special characters.
490
491 This involves dividing with whole numbers. The simplest solution
492 is to create this function in an external file: “lua/divide.lua”.
493
494 \begin{mybox}
495 \begin{verbatim}
496 function divide_and_remainder(dividend, divisor)
497 if divisor == 0 then
498 tex.error("Error: Cannot divide by zero")
499 return nil
500 else
501 local quotient = math.floor(dividend / divisor)
502 local remainder = dividend % divisor
503 return quotient, remainder
504 end
505 end
506 \end{verbatim}
507 \end{mybox}
508
509 \begin{verbatim}
510 \directlua{
511 dofile("lua/divide.lua")
512 local pc = string.char(37)
513 local num1 = 17
514 local num2 = 5
515 local q, r = divide_and_remainder(num1, num2)
516 tex.sprint(string.format("The quotient of ".. pc.. "d divided by"
517 .. pc.." d is:".. pc.." d\\par", num1, num2, q))
518 tex.sprint(string.format("The remainder is: "..pc.."d\\par", r))
519 }
520 \end{verbatim}
521
522 \directlua{
523 dofile("lua/divide.lua")
524 local pc = string.char(37)
525 local num1 = 17
526 local num2 = 5
527 local q, r = divide_and_remainder(num1, num2)
528 tex.sprint(string.format("The quotient of ".. pc.. "d divided by".. pc.."
529 d is:".. pc.." d\\par", num1, num2, q))
530 tex.sprint(string.format("The remainder is: "..pc.."d\\par", r))
531 }
532
533 Another solution is to use a local variable, for example:
534
535 \verb|local format = string.char(37) .. ".2f"|
536
537 and then \verb| tex.print(string.format(format , ...))|
538
539 Let's examine the version of the function if it is defined in the macro \tkzMacro{lualatex}{directlua}.
540
541 The problem is the use of l'operator \% (Modulus Operator and remainder of after an integer division). The same problem occurs when using the string.format function and the \%d or \%i: placeholder for an integer.
542
543 One solution for these two cases is to define a macro \tkzname{pc} which replaces the \%.
544
545 \begin{verbatim}
546 \makeatletter
547 \let\pc\@percentchar
548 \makeatother
549 \end{verbatim}
550
551 The code becomes:
552
553
554 \begin{verbatim}
555 \directlua{
556 function divide_and_remainder(dividend, divisor)
557 if divisor == 0 then
558 tex.error("Error: Cannot divide by zero")
559 return nil
560 else
561 local quotient = math.floor(dividend / divisor)
562 local remainder = dividend \pc divisor
563 return quotient, remainder
564 end
565 end
566
567 local num1 = 17
568 local num2 = 5
569 local q, r = divide_and_remainder(num1, num2)
570
571 tex.sprint(string.format([[The quotient of \pc i divided by
572 \pc i is: \pc i\\]], num1, num2, q))
573 tex.sprint(string.format([[The remainder is: \pc i]], r))}
574 \end{verbatim}
575
576 \item Variadic Functions\\
577
578 Use ... to handle a variable number of arguments:
579
580 First example:
581
582 It's the easiest way to avoid problems linked to the \#.
583
584 \begin{itemize}
585
586
587 \item \begin{tkzexample}[latex=.2\textwidth]
588 \directlua{
589 local function sum_all(...)
590 local total = 0
591 for _, value in ipairs{...} do
592 total = total + value
593 end
594 return total
595 end
596
597 tex.print(sum_all(1, 2, 3, 4))
598 }
599 \end{tkzexample}
600
601
602 \item Second example:
603
604 Here, I'm using a new function from the \tkzFct{utils}{table\_getn} package, which replaces an old Lua function \tkzFct{lua}{table.getn}, which was used to obtain the size of the table.
605
606 \begin{tkzexample}[latex=.2\textwidth]
607 \directlua{
608 local function sum_all(...)
609 local arg = {...}
610 local total = 0
611 for i = 1, utils.table_getn(arg) do
612 total = total + arg[i]
613 end
614 return total
615 end
616 local result = sum_all(10, 20, 30, 40)
617 tex.print(result)}
618 \end{tkzexample}
619
620
621 \item Third example:
622
623 It's always possible to use \#, with a little effort (texhnic).
624
625 \begin{tkzexample}[latex=.2\textwidth]
626 \bgroup
627 \catcode`\#=12
628 \directlua{
629 local function sum_all(...)
630 local arg = {...}
631 local total = 0
632 for i = 1, #arg do
633 total = total + arg[i]
634 end
635 return total
636 end
637 local result = sum_all(10, 20, 30, 40)
638 tex.print(result)}
639 \egroup
640 \end{tkzexample}
641 \end{itemize}
642
643
644 \item Recursion\\
645
646 Lua supports recursive functions:
647
648 \begin{tkzexample}[latex=.4\textwidth]
649 \directlua{dofile("lua/fact.lua")}
650 \newcommand*{\luafact}[1]{\directlua{
651 tex.write(fact(\the\numexpr(#1)\relax))}%
652 }
653 $8! = \luafact{8}$
654 \end{tkzexample}
655
656
657
658 \item Methods (Object-like Syntax)\\
659
660 When defining functions for tables (objects), you can use the colon syntax (:) to automatically pass the object itself as the first argument, usually called self.
661
662 Here's an example:
663
664
665 \begin{tkzexample}[latex = .2\textwidth]
666 \directlua{
667 z.A = point(0, 0)
668 z.B = point(5, 0)
669 L.AB = line(z.A, z.B)
670 T.ABC = L.AB:half()
671 _,_,z.C = T.ABC:get()
672 tex.print(tostring(z.C))}
673 \end{tkzexample}
674
675 Without the colon syntax, you would need to pass the object explicitly as the first argument:
676
677 \begin{verbatim}
678 T.ABC = L.AB.half(L.AB)
679 _,_,z.C = T.ABC.get(T.ABC)
680 \end{verbatim}
681
682 \code{half} and \code{get} are methods defined for object tables. When called with the colon syntax, they automatically receive the instance (self) they operate on.
683 \end{enumerate}
684
685 \subsection{Control structures}
686
687
688 Control structures let your program make decisions and repeat actions. Lua has a small set of easy-to-use control structures to help you write flexible and powerful code.
689
690 \textbf{1. Conditional statements}
691
692 Use if, elseif, and else when you want your code to do different things depending on conditions. This is how your program can "choose" between different options.
693
694 \textbf{2. Loops}
695
696 Loops are used to repeat actions:
697
698 while repeats as long as a condition is true.
699 repeat ... until repeats until a condition becomes true (it always runs at least once).
700 for is used to count or go through elements in a table.
701
702 \textbf{3. Local variables and blocks}
703
704 When you create a variable using local, it only exists inside the block where you wrote it. A block can be a function, a loop, or an if statement.
705
706 \textbf{4. Breaking and returning}
707
708 \emph{break} lets you stop a loop early.
709 return sends a value back from a function or stops it completely.
710 Lua keeps things simple, so once you learn these basic structures, you can write all kinds of logic in your programs!
711
712 \begin{enumerate}
713 \item \code{if then else}
714 \begin{tkzexample}[latex = .35\textwidth]
715 \directlua{
716 x = math.sin(math.pi)
717 tex.print("x = ",x)
718 tex.print([[\\]])
719 if math.abs(x) < 1e-12 then
720 tex.print("$x = 0$")
721 elseif x >0 then
722 tex.print("$x > 0$")
723 else
724 tex.print("$x < 0$")
725 end
726 }
727 \end{tkzexample}
728
729
730 \item \code{while}
731 \begin{tkzexample}[latex = .35\textwidth]
732 \directlua{
733 i = 1
734 while i <= 5 do
735 tex.print(i)
736 i = i + 1
737 end}
738 \end{tkzexample}
739
740 \item \code{repeat}
741 \begin{tkzexample}[latex = .35\textwidth]
742 \directlua{
743 x = 0
744 repeat
745 x = x + 2
746 tex.print(x)
747 until x == 6}
748 \end{tkzexample}
749
750 \item Numeric \code{for}: \\
751 | for init,max/min value, increment do statement(s) end|
752
753
754
755 \begin{tkzexample}[latex = .35\textwidth]
756 \directlua{
757 numbers = {10, 20, 30, 40, 50}
758 local nb = utils.table_getn(numbers)
759 for i = 1, nb do
760 local sep = (i < nb) and ", " or "."
761 tex.sprint(numbers[i] .. sep)
762 end}
763 \end{tkzexample}
764
765
766 \item Generic \code{for}:\\
767 |for i,v in ipairs(t) do tex.print(v) end|
768
769 \begin{tkzexample}[latex = .35\textwidth]
770 \directlua{
771 t = {a = 1, b = 2}
772 for k, v in pairs(t) do
773 tex.print(k, v)
774 end}
775 \end{tkzexample}
776
777 an example for the package:\\
778
779 \begin{tkzexample}[latex = .35\textwidth]
780 \directlua{
781 init_elements()
782 z.A = point(0, 1)
783 z.B = point(2, -1)
784 z.C = point(1, 1)
785 for k, v in pairs(z) do
786 tex.sprint(k,": ","(".. tostring(v)..")")
787 tex.print('\\\\')
788 end}
789 \end{tkzexample}
790
791 \item Summary about \code{for}
792 \begin{center}
793 \bgroup
794 \small
795 \captionof{table}{Comparison of \texttt{ipairs} and \texttt{pairs} in Lua}\label{for:summary}
796
797 \begin{tabular}{@{} lcc @{}}
798 \toprule
799 \textbf{Feature} & \texttt{ipairs(t)} & \texttt{pairs(t)} \\
800 \midrule
801 Iterates over & Numeric keys \texttt{1..n} & All keys (strings, numbers, etc.) \\
802 Order & Guaranteed (1, 2, 3, \ldots) & Not guaranteed \\
803 Stops at & First \texttt{nil} in sequence & After all keys \\
804 Use case & Arrays / Lists & Tables / Dictionaries \\
805 Skips non-numeric & \cmark & \xmark \\
806 Includes holes & \xmark & \cmark \\
807 \bottomrule
808 \end{tabular}
809 \egroup
810 \end{center}
811
812
813
814 \item \code{break} and \code{return}
815 \begin{itemize}
816 \item break: exits a loop.
817
818 \begin{tkzexample}[latex = .35\textwidth]
819 \directlua{ for i = 1, 10 do
820 if i == 5 then break end
821 tex.print(i)
822 end}
823 \end{tkzexample}
824
825 \item return: exits a function (or a chunk) with or without values.
826
827 Here's an example with the following constraints:
828
829 \begin{enumerate}[label=(\roman*)]
830
831 \item The function loops over a list of numbers.
832
833 \item If it finds an even number (value \% 2 == 0), it returns it immediately.
834
835 \item If it sees $-1$, it uses break to stop the loop without returning a value right away.
836
837 \item If no even number is found before a $-1$, the function returns nil at the end.
838 \end{enumerate}
839
840
841 \begin{tkzexample}[latex=.25\textwidth]
842
843 \makeatletter
844 \let\pc\@percentchar
845 \makeatother
846
847 \directlua{%
848 function find_first_even(t)
849 for i = 1, utils.table_getn(t) do
850 local value = t[i]
851 if value \pc 2 == 0 then
852 return value
853 elseif value == -1 then
854 break
855 end
856 end
857 return nil
858 end
859
860 local numbers = {1, 3, 5, -1, 4, 6}
861 tex.print(tostring(find_first_even(numbers))) }
862 \end{tkzexample}
863
864 \end{itemize}
865
866 \end{enumerate}
867
868 \subsection{Lua Sugar Syntax}
869 \label{sub:lua_sugar_syntax}
870 The "sugar syntax" in Lua refers to syntactic elements that make the language more concise and readable changing its fundamental meaning. Here are the main forms of sugar syntax in Lua:
871
872 \begin{enumerate}
873 \item Method calls with ":"\\
874 \code{ obj:method(arg)} Is sugar for: \code{ obj.method(obj, arg)}
875
876 The ":" implicitly passes obj as the first argument (self), which is very helpful in object-oriented programming.
877
878
879 \item Table field access with "."\\
880 \code{t.key} Is sugar for: \code{ t["key"]}
881
882 This is more readable when the key is a valid identifier (no spaces, punctuation, etc.).
883
884 \item Shorthand table constructors\\
885 \code{local t = \{1, 2, 3\}} Is equivalent to: \code{ local t = \{[1]=1, [2]=2, [3]=3\}}
886
887 And:
888
889 \code{local t = \{a = 1, b = 2\}} Is sugar for: \code{local t = \{["a"] = 1, ["b"] = 2\}}
890
891 \item Loop sugar (e.g., for k, v in pairs(t) do)\\
892 Even though pairs() is just a function, the way Lua loops over tables using for is very clean and readable. k for keys , v for value.
893
894 \begin{mybox}
895 \begin{verbatim}
896 for k, v in pairs(t) do
897 ...
898 end
899 \end{verbatim}
900 \end{mybox}
901
902
903 \item Logical expressions as default value tricks\\
904 x = a or b
905 Is often used to mean: “if a is truthy, use it, otherwise use b”. Great for setting default values.
906
907 \item do ... end blocks\\
908 This is a way to create a local scope block — useful for limiting variable visibility.
909 \end{enumerate}
910
911 \subsection{Example: Calculating the sum of 1 to 10}
912 \label{sub:calculating_the_sum}
913
914 Lua is useful for advanced calculations that LaTeX alone cannot handle efficiently.
915
916 \vspace{1em}
917 \begin{tkzexample}[latex=.5\textwidth]
918 \directlua{
919 local somme = 0
920 for i = 1, 10 do
921 somme = somme + i
922 end
923 tex.print("Sum of 1 to 10: " .. somme)}
924 \end{tkzexample}
925 %
926
927 \subsubsection{Example: Fibonacci}
928
929 \vspace{1em}
930 Calculation of the rank term $10$
931
932 \vspace{1em}
933 \begin{tkzexample}[latex = .4\textwidth]
934 \directlua{
935 function fibonacci(n)
936 if n == 0 then
937 return 0
938 elseif n == 1 then
939 return 1
940 else
941 return fibonacci(n - 1) + fibonacci(n - 2)
942 end
943 end}
944 The term of rank $10$ in the Fibonacci sequence
945 is
946 \(u_{10}=\directlua{tex.print(
947 fibonacci(10))}\)
948 \end{tkzexample}
949 \endinput