\newpage
\section{LuaLaTeX for Beginners: An Introduction to Lua Scripting}

\subsection{Introduction to Lua with LaTeX}

\tkzEngine{\LUALATEX} is a variant of LaTeX that integrates Lua as a scripting language. This enables :

\begin{itemize}
  \item Perform advanced calculations.
  \item Manipulate text and data.
  \item Generate dynamic content in a document.
\end{itemize}

\subsection{Using Lua in a LaTeX document}

In \tkzNamePack{tkz-elements}, I only use two ways of integrating code into \tkzname{Lua}, which are as follows:

\begin{itemize}
  \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.}

  Lua code can be executed directly in a document using \tkzMacro{lualatex}{directlua} :

  |\directlua{tex.print(math.exp(1))}| -->  \directlua{tex.print(math.exp(1))}

  \item  Loading an external Lua file:

  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.

 \emph{dofile:}   Immediately executes a Lua file. Equivalent to loadfile(filename)()

\emph{loadfile:}    Loads a Lua file into memory (without executing it immediately); returns a function to execute.

\emph{require:} Loads a Lua module once (via package.loaded) and executes it; uses package.path to search for the file.


Examples are provided in this documentation, which you can see :

 [\ref{sec:work_organization}] |\directlua{dofile("lua/sangaku.lua")}|

  or [\ref{sub:six_circles_in_a_triangle}] |\directlua{loadfile ("lua/search\_circle.lua")(1.4)|

\end{itemize}

\tkzRBomb 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).

With \tkzEnv{luacode}{luacode} environment, you need to use two hyphens.

The next subsection describes some of the differences between \TeX{} and LuaTeX{} for special characters and catcodes.

\subsection{Interaction between Lua and LaTeX}

\tkzEngine{\LUALATEX} allows you to interact with LaTeX, in particular via :

\begin{itemize}
\item \code{|tex.print()|}: displays text in LaTeX.
\item \code{|tex.sprint()|}: inserts content without extra space.\\
\end{itemize}

\begin{mybox}
\begin{verbatim}
|\directlua{tex.sprint("\\textbf{Bold text generated by Lua}")}|
\end{verbatim}
\directlua{tex.sprint("\\textbf{Bold text generated by Lua}")}
\end{mybox}


\subsection{The variables}

\begin{mybox}
  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.
\end{mybox}

Let's analyze what we've just written. Four points are important: "named label", "type of value", "dynamically" and "scope".


\subsubsection{Named label}

The name you assign to a variable must follow certain rules:

\begin{itemize}
  \item They can contain letters (a-z, A-Z), digit (0-9) and the underscore symbol (\_).
  \item They cannot start with a digit.
  \item They are case-sensitive.
  \item Some Lua keywords (such as if, then, function, local, etc.) are reserved and cannot be used as variable names.
\end{itemize}

\subsubsection{Data types}
\label{ssub:types}
 What types of values can be assigned to a variable? Here's a list of the simplest:

\begin{itemize}
    \item \textbf{nil} : undefined value.
    \item \textbf{boolean} : \texttt{true} or \texttt{false}.
    \item \textbf{number} : double-precision floating-point numbers (reals).
    \item \textbf{string} : strings.
    \item \textbf{table} : associative data structures(key-value) and arrays.
    \item \textbf{function} : anonymous or named functions.
\end{itemize}

\subsubsection{Dynamically}

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}.

\tkzRBomb 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}.

\subsubsection{Scope and block}

\begin{enumerate}

  \item  \code{\textbf{Block}}\\
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.

Here are the primary ways blocks are defined in Lua:

\begin{itemize}
  \item \code{|do ... end|}. This explicitly creates a block. Any local variables declared within a do...end block are only accessible within that block.

  \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.

\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.

\item \code{|function...end|}. The body of a function, between function and end, is a block that contains the function's code.
\end{itemize}


\item \code{\textbf{Scope}}\\
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.

A variable declared as \code{local} in a block is not accessible outside it.

Example:

\begin{mybox}
\begin{verbatim}
\directlua{
 do
  local x = 10
  tex.print(x) % Accessible here
end
 tex.print(x) % Error! x is out of scope here}
\end{verbatim}
\end{mybox}
\end{enumerate}

\subsection{The values}

Let's see what you need to know about the main values.

%   \begin{enumerate}[label=(\greek*)]

\subsubsection{\code{nil}}


  \begin{itemize}

    \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.

\begin{mybox}
  \begin{verbatim}
    \directlua{
    tex.print(tostring(no_assigned))}
    and
    tex.print(type(no_assigned)) gives
  \end{verbatim}
\directlua{tex.print(tostring(no_assigned))}
\directlua{tex.print(type(no_assigned))}
\end{mybox}

\item Table and \code{nil}.\\

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.

  \end{itemize}

\subsubsection{Booleans}

\begin{itemize}
  \item In Lua, there are only two boolean values: \code{true} and \code{false}.
  \item Booleans belong to the boolean data type.
  \item They are manipulated using logical operators (\code{and}, \code{or}, \code{not}) to form more complex boolean expressions.
  \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).
  If you want to distinguish between nil and false you need to be more explicit
\begin{mybox}
\begin{verbatim}
  if v == false then
   ...
  elseif v == nil then
   ...
  else
   ...
  end
\end{verbatim}
\end{mybox}
\end{itemize}

\subsubsection{Number}


\begin{itemize}
  \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.

\item Lua uses a standard 64-bit floating-point representation.
\item Even though there's only one numeric type, Lua handles integer values efficiently.

\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.
You can use functions defined in the math library.

\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$.\\
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.

\end{itemize}

\subsubsection{Strings}

\begin{enumerate}[label=(\alph*)]
  \item Construction

 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.


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.

\begin{tkzexample}[latex=.4\textwidth]
\directlua{tex.print('a string with " ')}
\end{tkzexample}

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.

\begin{tkzexample}[latex=.4\textwidth]
\directlua{tex.print("a string with \string\" ")}
\end{tkzexample}



\item Concatenation: \code{|..|}. An interesting example is the ability to create multiple variables:
\begin{mybox}
  \begin{verbatim}
    local t= {}
    local i = 5
    t["x_" .. tostring(i)] = 11
    tex.print(t.x_5)
  \end{verbatim}

\end{mybox}


\item Lua provides a powerful string library (string) with many useful functions for manipulating strings. Here are some common ones:

\begin{itemize}

\item \code{string.char(n)},
\item \code{string.len(s)},

\item \code{string.sub(s, i [, j])},

\item \code{string.find(s, pattern [, init [, plain]])},

\item \code{string.gsub(s, pattern, repl [, n])},

\item \code{string.format(formatstring, ...)}, etc.
\end{itemize}

\item Special or magic characters in the library \code{String}\\

\begin{center}
  \begin{tabular}{@{}ll@{}}
  \toprule
  \textbf{Character} & \textbf{Meaning} \\
  \midrule
  \texttt{.} & Matches any character \\
  \texttt{\%} & Escape character (for magic characters) \\
  \texttt{+} & One or more repetitions \\
  \texttt{-} & Zero or more repetitions (minimal) \\
  \texttt{*} & Zero or more repetitions (greedy) \\
  \texttt{?} & Zero or one occurrence \\
  \texttt{[ ]} & Character class \\
  \texttt{\^{}} & Beginning of string \\
  \texttt{\$} & End of string \\
  \bottomrule
  \end{tabular}
\end{center}

\item Character Classes (after \texttt{\%})

\begin{center}
  \begin{tabular}{@{}ll@{}}
  \toprule
  \textbf{Code} & \textbf{Meaning} \\
  \midrule
  \texttt{a} & Letters (A-Z, a-z) \\
  \texttt{c} & Control characters \\
  \texttt{d} & Digits (0-9) \\
  \texttt{g} & Printable characters (except space) \\
  \texttt{l} & Lowercase letters \\
  \texttt{p} & Punctuation characters \\
  \texttt{s} & Space characters \\
  \texttt{u} & Uppercase letters \\
  \texttt{w} & Alphanumeric characters \\
  \texttt{x} & Hexadecimal digits (0-9, A-F, a-f) \\
  \texttt{z} & Null character (ASCII 0) \\
  \bottomrule
  \end{tabular}
\end{center}

\item Notes
\begin{itemize}
    \item To match a literal magic character (like \texttt{.} or \texttt{*}), prefix it with \texttt{\%}.
    \item Uppercase codes (\texttt{\%A}, \texttt{\%D}, etc.) match anything \emph{except} the corresponding class.
\end{itemize}

\item String.format in LuaLaTeX - Memo Sheet
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.

\begin{center}
  \begin{tabular}{@{}ll@{}}
  \toprule
  \textbf{Lua format}   & \textbf{Description} \\ \midrule
  \texttt{\%d}      & Decimal integer   (7 or 7.0)                           \\
  \texttt{\%i}      & Placeholder for an integer or hexadecimal)         \\
  \texttt{\%f}      & Floating-point number (fixed precision)      \\
  \texttt{\%g}      & Floating-point number (automatic precision)  \\
  \texttt{\%s}      & Placeholder for a string                            \\
  \texttt{\%e}      & Scientific notation (exponent)               \\
  \texttt{\%\%}     & Percent sign (escaping)                      \\
  \texttt{\%-5d}    & Left-align the integer with a field width of 5  \\
  \texttt{\%10.2f}  & Right-align a floating-point number with width 10 and 2 decimal places \\
  \texttt{\%.2f}    & Floating-point number with 2 decimal places  \\
  \texttt{\%g}      & Floating-point number with general format    \\ \bottomrule
  \end{tabular}
\end{center}


* Basic Formatting
\begin{itemize}
  \item \texttt{string.format(\%d, 5)} outputs: \texttt{5}
  \item \texttt{string.format(\%f, 2.5)} outputs: \texttt{2.500000}
  \item \texttt{string.format(\%g, 1234567.89)} outputs: \texttt{1.23457e+06}
  \item \texttt{string.format(\%s, "z.A")} outputs: \texttt{z.A}
\end{itemize}

* Mathematical Expressions in LaTeX
You can easily format mathematical expressions like powers and equations:
\begin{itemize}
  \item \texttt{string.format(\$ \%d \textasciicircum 3 = \%d \$, x, x\textasciicircum3)} will output something like \texttt{\$8\textasciicircum 3 = 512\$}
\end{itemize}

* Special Characters
\begin{itemize}
  \item \texttt{string.format(\%\%)} outputs: \texttt{\%}
\end{itemize}


\item If s = "example" then |tex.print(s:len())| gives $7$.
\end{enumerate}

\subsubsection{The Tables}

\begin{itemize}

\item Definition\\
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.

  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.


  \item Table creation.\\
  The simplest way to create a table is with the constructor expression \{\}, but the following example uses sugar syntax

  \begin{mybox}
    \code{t = \{one = 1, two = 4, three = 9, four = 16, five = 25\}} \\
    Pairs (key,value) are separated by commas or semicolons. The key is to the left of the = sign and the value to the right.
   | t.one = 1; t.two = 4; etc.|
  \end{mybox}

  In fact, this corresponds to

  \begin{mybox}
    \code{t = \{["one"] = 1, ["two"] = 4, ["three"] = 9, ["four"] = 16, ["five"] = 25\}} \\
  \end{mybox}

  which is the most general definition of a table.

   | t.["one"] = 1; t.["two"] = 4; etc.|

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

  \item Table Manipulation.\\
There are in built functions for table manipulation and they are listed in the following table.

\begin{table}[htbp]
\centering
\caption{Built-in Table Manipulation Functions in Lua}
\begin{tabular}{@{}ll@{}}
\toprule
\textbf{Function} & \textbf{Description} \\
\midrule
\texttt{table.insert(t, [pos,] value)} & Inserts a value into table \texttt{t} at position \texttt{pos} (default: end). \\
\texttt{table.remove(t, [pos])}        & Removes the element at position \texttt{pos} from table \texttt{t}. \\
\texttt{table.sort(t [, comp])}        & Sorts the elements of table \texttt{t} in-place. Optional comparator. \\
\texttt{table.concat(t [, sep [, i [, j]]])} & Concatenates elements of \texttt{t} from \texttt{i} to \texttt{j} using separator \texttt{sep}. \\
\texttt{table.unpack(t [, i [, j]])}   & Returns the elements of \texttt{t} from index \texttt{i} to \texttt{j}. \\
\texttt{table.pack(...)}          & Returns a new table with all arguments stored as elements. \\

\bottomrule
\end{tabular}
\end{table}






\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 (.).
\item Deleting elements: To remove an element from a table, simply assign the value nil to its key.
\end{itemize}

\subsubsection{Functions}

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.

 \begin{enumerate}[label=(\alph*)]
  \item Basic Syntax

\begin{tkzexample}[latex=.4\textwidth]
  \directlua{
    function cubic(x)
       return x^3
    end
    tex.print(cubic(5))}
\end{tkzexample}

\item Parameters and Return Values\\

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.

This involves dividing with whole numbers. The simplest solution
is to create this function in an external file: “lua/divide.lua”.

\begin{mybox}
\begin{verbatim}
 function divide_and_remainder(dividend, divisor)
   if divisor == 0 then
     tex.error("Error: Cannot divide by zero")
     return nil
   else
     local quotient = math.floor(dividend / divisor)
     local remainder = dividend % divisor
     return quotient, remainder
   end
 end
\end{verbatim}
\end{mybox}

\begin{verbatim}
\directlua{
 dofile("lua/divide.lua")
local pc = string.char(37)
local num1 = 17
local num2 = 5
local q, r = divide_and_remainder(num1, num2)
tex.sprint(string.format("The quotient of ".. pc.. "d divided by"
.. pc.." d is:".. pc.." d\\par", num1, num2, q))
tex.sprint(string.format("The remainder is: "..pc.."d\\par", r))
}
\end{verbatim}

\directlua{
 dofile("lua/divide.lua")
local pc = string.char(37)
local num1 = 17
local num2 = 5
local q, r = divide_and_remainder(num1, num2)
tex.sprint(string.format("The quotient of ".. pc.. "d divided by".. pc.."
 d is:".. pc.." d\\par", num1, num2, q))
tex.sprint(string.format("The remainder is: "..pc.."d\\par", r))
}

Let's examine the version of the function if it is defined in the macro \tkzMacro{lualatex}{directlua}.

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.

One solution for these two cases is to define a macro \tkzname{pc} which replaces the \%.

\begin{verbatim}
 \makeatletter
 \let\pc\@percentchar
 \makeatother
\end{verbatim}

The code becomes :


\begin{verbatim}
\directlua{
 function divide_and_remainder(dividend, divisor)
   if divisor == 0 then
     tex.error("Error: Cannot divide by zero")
     return nil
   else
     local quotient = math.floor(dividend / divisor)
     local remainder = dividend \pc divisor
     return quotient, remainder
   end
 end

local num1 = 17
local num2 = 5
local q, r = divide_and_remainder(num1, num2)

tex.sprint(string.format([[The quotient of \pc i divided by
 \pc i is: \pc i\\]], num1, num2, q))
tex.sprint(string.format([[The remainder is: \pc i]], r))}
\end{verbatim}

\item Variadic Functions\\

Use ... to handle a variable number of arguments:

First example:

It's the easiest way to avoid problems linked to the \#.

\begin{itemize}


  \item   \begin{tkzexample}[latex=.2\textwidth]
    \directlua{
    local function sum_all(...)
      local total = 0
      for _, value in ipairs{...} do
        total = total + value
      end
      return total
    end

    tex.print(sum_all(1, 2, 3, 4))
    }
  \end{tkzexample}


\item   Second example:

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.

  \begin{tkzexample}[latex=.2\textwidth]
    \directlua{
    local function sum_all(...)
      local arg = {...}
      local total = 0
      for i = 1, utils.table_getn(arg) do
        total = total + arg[i]
      end
      return total
    end
    local result = sum_all(10, 20, 30, 40)
    tex.print(result)}
  \end{tkzexample}


\item   Third example:

It's always possible to use \#, with a little effort (texhnic).

\begin{tkzexample}[latex=.2\textwidth]
 \bgroup
 \catcode`\#=12
 \directlua{
 local function sum_all(...)
   local arg = {...}
   local total = 0
   for i = 1, #arg do
     total = total + arg[i]
   end
   return total
 end
 local result = sum_all(10, 20, 30, 40)
 tex.print(result)}
 \egroup
\end{tkzexample}
\end{itemize}


\item  Recursion\\

Lua supports recursive functions:

\begin{tkzexample}[latex=.4\textwidth]
  \directlua{dofile("lua/fact.lua")}
  \newcommand*{\luafact}[1]{\directlua{
    tex.write(fact(\the\numexpr(#1)\relax))}%
  }
  $8! = \luafact{8}$
\end{tkzexample}



\item Methods (Object-like Syntax)\\

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.

Here's an example:


\begin{tkzexample}[latex = .2\textwidth]
  \directlua{
   z.A = point(0, 0)
   z.B = point(5, 0)
   L.AB = line(z.A, z.B)
   T.ABC = L.AB:half()
   _,_,z.C = T.ABC:get()
   tex.print(tostring(z.C))}
\end{tkzexample}

Without the colon syntax, you would need to pass the object explicitly as the first argument:

\begin{verbatim}
  T.ABC = L.AB.half(L.AB)
  _,_,z.C = T.ABC.get(T.ABC)
\end{verbatim}

\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.
\end{enumerate}

\subsection{Control structures}


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.

\textbf{1. Conditional statements}

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.

\textbf{2. Loops}

Loops are used to repeat actions:

while repeats as long as a condition is true.
repeat ... until repeats until a condition becomes true (it always runs at least once).
for is used to count or go through elements in a table.

\textbf{3. Local variables and blocks}

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.

\textbf{4. Breaking and returning}

\emph{break} lets you stop a loop early.
return sends a value back from a function or stops it completely.
Lua keeps things simple, so once you learn these basic structures, you can write all kinds of logic in your programs!

   \begin{enumerate}
  \item \code{if then else}
  \begin{tkzexample}[latex = .35\textwidth]
    \directlua{
    x = math.sin(math.pi)
     tex.print("x = ",x)
       tex.print([[\\]])
    if math.abs(x) < 1e-12 then
    tex.print("$x = 0$")
    elseif x >0 then
     tex.print("$x > 0$")
     else
      tex.print("$x < 0$")
    end
    }
  \end{tkzexample}


\item \code{while}
\begin{tkzexample}[latex = .35\textwidth]
\directlua{
 i = 1
 while i <= 5 do
   tex.print(i)
   i = i + 1
 end}
\end{tkzexample}

\item \code{repeat}
\begin{tkzexample}[latex = .35\textwidth]
\directlua{
 x = 0
 repeat
   x = x + 2
   tex.print(x)
 until x == 6}
\end{tkzexample}

  \item Numeric \code{for}: \\
 | for init,max/min value, increment do statement(s)  end|



\begin{tkzexample}[latex = .35\textwidth]
\directlua{
  numbers = {10, 20, 30, 40, 50}
  local nb = utils.table_getn(numbers)
  for i = 1, nb do
    local sep = (i < nb) and ", " or "."
    tex.sprint(numbers[i] .. sep)
  end}
\end{tkzexample}


  \item Generic \code{for}:\\
   |for i,v in ipairs(t) do tex.print(v) end|

  \begin{tkzexample}[latex = .35\textwidth]
 \directlua{
    t = {a = 1, b = 2}
    for k, v in pairs(t) do
      tex.print(k, v)
    end}
  \end{tkzexample}

  an example for the package:\\

\begin{tkzexample}[latex = .35\textwidth]
  \directlua{
  init_elements()
  z.A = point(0, 1)
  z.B = point(2, -1)
  z.C = point(1, 1)
  for k, v in pairs(z) do
    tex.sprint(k,": ","(".. tostring(v)..")")
    tex.print('\\\\')
  end}
\end{tkzexample}

  \item Summary about \code{for}
  \begin{center}
    \bgroup
    \small
  \captionof{table}{Comparison of \texttt{ipairs} and \texttt{pairs} in Lua}\label{for:summary}

  \begin{tabular}{@{} lcc @{}}
  \toprule
   \textbf{Feature} & \texttt{ipairs(t)} & \texttt{pairs(t)} \\
   \midrule
   Iterates over      & Numeric keys \texttt{1..n}      & All keys (strings, numbers, etc.) \\
   Order              & Guaranteed (1, 2, 3, \ldots)     & Not guaranteed \\
   Stops at           & First \texttt{nil} in sequence  & After all keys \\
   Use case           & Arrays / Lists                  & Tables / Dictionaries \\
   Skips non-numeric  & \cmark                          & \xmark \\
   Includes holes     & \xmark                          & \cmark \\
   \bottomrule
   \end{tabular}
  \egroup
  \end{center}



\item \code{break} and \code{return}
  \begin{itemize}
  \item     break: exits a loop.

\begin{tkzexample}[latex = .35\textwidth]
\directlua{  for i = 1, 10 do
    if i == 5 then break end
    tex.print(i)
  end}
\end{tkzexample}

\item    return: exits a function (or a chunk) with or without values.

Here's an example with the following constraints:

\begin{enumerate}[label=(\roman*)]

\item   The function loops over a list of numbers.

\item   If it finds an even number (value \% 2 == 0), it returns it immediately.

\item   If it sees $-1$, it uses break to stop the loop without returning a value right away.

\item   If no even number is found before a $-1$, the function returns nil at the end.
\end{enumerate}


\begin{tkzexample}[latex=.25\textwidth]

   \makeatletter
   \let\pc\@percentchar
   \makeatother

\directlua{%
  function find_first_even(t)
    for i = 1, utils.table_getn(t) do
      local value = t[i]
      if value \pc 2 == 0 then
        return value
      elseif value == -1 then
        break
      end
    end
    return nil
  end

  local numbers = {1, 3, 5, -1, 4, 6}
  tex.print(tostring(find_first_even(numbers))) }
\end{tkzexample}

\end{itemize}

\end{enumerate}

\subsection{Lua Sugar Syntax}
\label{sub:lua_sugar_syntax}
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:

   \begin{enumerate}
  \item  Method calls with ":"\\
 \code{ obj:method(arg)} Is sugar for: \code{ obj.method(obj, arg)}

 The : implicitly passes obj as the first argument (self), which is very helpful in object-oriented programming.


  \item   Table field access with "."\\
  \code{t.key}  Is sugar for: \code{  t["key"]}

  This is more readable when the key is a valid identifier (no spaces, punctuation, etc.).

  \item Shorthand table constructors\\
  \code{local t = \{1, 2, 3\}}  Is equivalent to: \code{ local t = \{[1]=1, [2]=2, [3]=3\}}

  And:

  \code{local t = \{a = 1, b = 2\}} Is sugar for:  \code{local t = \{["a"] = 1, ["b"] = 2\}}

  \item Loop sugar (e.g., for k, v in pairs(t) do)\\
  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.

\begin{mybox}
\begin{verbatim}
  for k, v in pairs(t) do
     ...
  end
\end{verbatim}
\end{mybox}


 \item  Logical expressions as default value tricks\\
 x = a or b
 Is often used to mean: “if a is truthy, use it, otherwise use b”. Great for setting default values.

 \item  do ... end blocks\\
 This is a way to create a local scope block — useful for limiting variable visibility.
\end{enumerate}

\subsection{Example: Calculating the sum of 1 to 10}
\label{sub:calculating_the_sum}

Lua is useful for advanced calculations that LaTeX alone cannot handle efficiently.

\vspace{1em}
\begin{tkzexample}[latex=.5\textwidth]
\directlua{
  local somme = 0
  for i = 1, 10 do
    somme = somme + i
  end
  tex.print("Somme de 1 à 10 : " .. somme)}
\end{tkzexample}
%

\subsubsection{Example: Fibonacci}

 \vspace{1em}
  Calcul du terme de rang $10$

\vspace{1em}
\begin{tkzexample}[latex = .4\textwidth]
\directlua{
 function fibonacci(n)
   if n == 0 then
     return 0
   elseif n == 1 then
     return 1
   else
     return fibonacci(n - 1) + fibonacci(n - 2)
   end
 end}
    Le terme de rang $10$ de la suite de
    Fibonacci est
    \(u_{10}=\directlua{tex.print(
    fibonacci(10))}\)
\end{tkzexample}
\endinput
