aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>1995-11-16 18:46:02 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>1995-11-16 18:46:02 -0200
commit07d64e78b69422ed165e2af796daae2b06cc8b83 (patch)
tree51a7a5ea3f06e5d8de8e7f26edf645108c2819a4
parentfa649fbc26494bf829406a8d94c974a873ab0451 (diff)
downloadlua-07d64e78b69422ed165e2af796daae2b06cc8b83.tar.gz
lua-07d64e78b69422ed165e2af796daae2b06cc8b83.tar.bz2
lua-07d64e78b69422ed165e2af796daae2b06cc8b83.zip
reference manual
-rw-r--r--manual.tex1741
1 files changed, 1741 insertions, 0 deletions
diff --git a/manual.tex b/manual.tex
new file mode 100644
index 00000000..584808e6
--- /dev/null
+++ b/manual.tex
@@ -0,0 +1,1741 @@
1\documentstyle[A4,11pt,bnf]{article}
2
3\newcommand{\rw}[1]{{\bf #1}}
4\newcommand{\see}[1]{see Section~\ref{#1}}
5\newcommand{\nil}{{\bf nil}}
6\newcommand{\Line}{\rule{\linewidth}{.5mm}}
7\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
8
9\newcommand{\Index}[1]{#1\index{#1}}
10\newcommand{\IndexVerb}[1]{{\tt #1}\index{#1}}
11\newcommand{\Def}[1]{{\em #1}\index{#1}}
12\newcommand{\Deffunc}[1]{\index{{\tt #1}}}
13
14
15
16\begin{document}
17
18\title{Reference Manual of the Programming Language Lua 2.2}
19
20\author{%
21Roberto Ierusalimschy\quad
22Luiz Henrique de Figueiredo\quad
23Waldemar Celes Filho
24\vspace{1.0ex}\\
25%\small \tecgraf \ --- PUC-Rio\\
26\smallskip
27\small\tt roberto,lhf,celes@icad.puc-rio.br
28\vspace{2.0ex}\\
29%MCC 08/95 ---
30Departamento de Inform\'atica --- PUC-Rio
31}
32
33\date{November, 1995}
34
35\maketitle
36
37
38\begin{abstract}
39\noindent
40Lua is an extension programming language designed to be used
41as a configuration language for any program that needs one.
42This document describes version 2.2 of the Lua programming language and the
43API that allows interaction between Lua programs and its host C program.
44It also presents some examples of using the main features of the system.
45\end{abstract}
46
47\vspace{4ex}
48\begin{quotation}
49\small
50\begin{center}{\bf Sum\'ario}\end{center}
51\vspace{1ex}
52\noindent
53Lua \'e uma linguagem de extens\~ao projetada para ser usada como
54linguagem de configura\c{c}\~ao em qualquer programa que precise de
55uma.
56Este documento descreve a vers\~ao 2.2 da linguagem de programa\c{c}\~ao Lua e a
57Interface de Programa\c{c}\~ao que permite a intera\c{c}\~ao entre programas Lua
58e o programa C hospedeiro.
59O documento tamb\'em apresenta alguns exemplos de uso das principais
60ca\-racte\-r\'{\i}sticas do sistema.
61\end{quotation}
62
63
64\section{Introduction}
65
66Lua is an extension programming language designed to support
67general procedural programming features with data description
68facilities.
69It is supposed to be used as a configuration language for any
70program that needs one.
71Its main extensions are related to object-oriented facilities,
72and fallbacks,
73but it has some other minor contributions.
74Lua has been designed and implemented by
75W.~Celes~F., L.~H.~de Figueiredo and R.~Ierusalimschy.
76
77Lua is implemented as a library, written in C.
78Being an extension language, Lua has no notion of a ``main'' program:
79it only works {\em embedded} in a host client,
80called the {\em embedding} program.
81This host program can invoke functions to execute a piece of
82code in Lua, can write and read Lua variables,
83and can register C functions to be called by Lua code.
84Through the use of C functions, Lua can be augmented to cope with
85rather different domains,
86thus creating customized programming languages sharing a syntactical framework.
87
88Lua is free distribution software,
89and provided as usual with no guarantees.
90The implementation described in this manual is available
91by anonymous ftp from
92\begin{verbatim}
93 ftp.icad.puc-rio.br:/pub/lua/lua-2.2.tar.gz
94\end{verbatim}
95or by WWW (World Wide Web) from
96\begin{verbatim}
97 http://www.inf.puc-rio.br/~roberto/lua.html
98\end{verbatim}
99
100
101\section{Environment and Modules}
102
103All statements in Lua are executed in a \Def{global environment}.
104This environment, which keeps all global variables and functions,
105is initialized at the beginning of the embedding program and
106persists until its end.
107
108The global environment can be manipulated by Lua code or
109by the embedding program,
110which can read and write global variables
111using functions in the library that implements Lua.
112
113\Index{Global variables} do not need declaration.
114Any variable is assumed to be global unless explicitly declared local
115(see local declarations, Section~\ref{localvar}).
116Before the first assignment, the value of a global variable is \nil.
117
118The unit of execution of Lua is called a \Def{chunk}.
119The syntax for chunks is:%
120\footnote{As usual, \rep{{\em a}} means 0 or more {\em a\/}'s,
121\opt{{\em a}} means an optional {\em a} and \oneormore{{\em a}} means
122one or more {\em a\/}'s.}
123\begin{Produc}
124\produc{chunk}{\rep{statement \Or function}}
125\end{Produc}%
126A chunk may contain statements and function definitions,
127and may be in a file or in a string inside the host program.
128When a chunk is executed, first all its functions and statements are compiled,
129then the statements are executed in sequential order.
130All modifications a chunk effects on the global environment persist
131after its end.
132Those include modifications to global variables and definitions
133of new functions%
134\footnote{Actually, a function definition is an
135assignment to a global variable; \see{TypesSec}.}.
136
137
138
139\section{\Index{Types}} \label{TypesSec}
140
141Lua is a dynamically typed language.
142Variables do not have types; only values do.
143All values carry their own type.
144Therefore, there are no type definitions in the language.
145
146There are seven \Index{basic types} in Lua: \Def{nil}, \Def{number},
147\Def{string}, \Def{function}, \Def{CFunction}, \Def{userdata},
148and \Def{table}.
149{\em Nil} is the type of the value \nil,
150whose main property is to be different from any other value.
151{\em Number} represents real (floating point) numbers,
152while {\em string} has the usual meaning.
153
154Functions are considered first-class values in Lua.
155This means that functions can be stored in variables,
156passed as arguments to other functions and returned as results.
157When a function is defined in Lua, its body is compiled and stored
158in a given variable.
159Lua can call (and manipulate) functions written in Lua and
160functions written in C; the latter have type {\em CFunction\/}.
161
162The type {\em userdata} is provided to allow
163arbitrary \Index{C pointers} to be stored in Lua variables.
164It corresponds to \verb'void*' and has no pre-defined operations in Lua,
165besides assignment and equality test.
166However, by using fallbacks, the programmer may define operations
167for {\em userdata} values; \see{fallback}.
168
169The type {\em table} implements \Index{associative arrays},
170that is, \Index{arrays} which can be indexed not only with numbers,
171but with any value (except \nil).
172Therefore, this type may be used not only to represent ordinary arrays,
173but also symbol tables, sets, records, etc.
174To represent \Index{records}, Lua uses the field name as an index.
175The language supports this representation by
176providing \verb'a.name' as syntactic sugar for \verb'a["name"]'.
177Tables may also carry methods.
178Because functions are first class values,
179table fields may contain functions.
180The form \verb't:f(x)' is syntactic sugar for \verb't.f(t,x)',
181which calls the method \verb'f' from the table \verb't' passing
182itself as the first parameter.
183
184It is important to notice that tables are objects, and not values.
185Variables cannot contain tables, only references to them.
186Assignment, parameter passing and returns always manipulate references
187to tables, and do not imply any kind of copy.
188Moreover, tables must be explicitly created before used;
189\see{tableconstructor}.
190
191
192
193\section{The Language}
194
195This section describes the lexis, syntax and semantics of Lua.
196
197
198\subsection{Lexical Conventions} \label{lexical}
199
200Lua is a case sensitive language.
201\Index{Identifiers} can be any string of letters, digits, and underscores,
202not beginning with a digit.
203The following words are reserved, and cannot be used as identifiers:
204\index{reserved words}
205\begin{verbatim}
206 and do else elseif end
207 function if local nil not
208 or repeat return until then while
209\end{verbatim}
210
211The following strings denote other \Index{tokens}:
212\begin{verbatim}
213 ~= <= >= < > == = .. + - * /
214 % ( ) { } [ ] ; , .
215\end{verbatim}
216
217\Index{Literal strings} can be delimited by matching single or double quotes,
218and can contain the C-like escape sequences
219\verb-'\n'-, \verb-'\t'- and \verb-'\r'-.
220Literal strings can also be delimited by matching \verb'[[ ... ]]'.
221Literals in this last form may run for several lines,
222may contain nested \verb'[[ ... ]]',
223and do not interpret escape sequences.
224
225\Index{Comments} start anywhere outside a string with a
226double hyphen (\verb'--') and run until the end of the line.
227
228\Index{Numerical constants} may be written with an optional decimal part,
229and an optional decimal exponent.
230Examples of valid numerical constants are:
231\begin{verbatim}
232 4 4. .4 4.57e-3 .3e12
233\end{verbatim}
234
235
236\subsection{\Index{Coercion}} \label{coercion}
237
238Lua provides some automatic conversions.
239Any arithmetic operation applied to a string tries to convert
240that string to a number, following the usual rules.
241Conversely, whenever a number is used when a string is expected,
242that number is converted to a string, according to the following rule:
243if the number is an integer, it is written without exponent or decimal point;
244otherwise, it is formatted following the ``\verb'%g'''
245conversion specification of the standard \verb'printf' C function.
246
247
248
249\subsection{\Index{Adjustment}} \label{adjust}
250
251Functions in Lua can return many values.
252Because there are no type declarations,
253the system does not know how many values a function will return,
254or how many parameters it needs.
255Therefore, sometimes, a list of values must be {\em adjusted\/}, at run time,
256to a given length.
257If there are more values than are needed, the last values are thrown away.
258If there are more needs than values, the list is extended with as
259many \nil's as needed.
260Adjustment occurs in multiple assignment and function calls.
261
262
263\subsection{Statements}
264
265Lua supports an almost conventional set of \Index{statements}.
266The conventional commands include
267assignment, control structures and procedure calls.
268Non-conventional commands include table constructors,
269explained in Section \ref{tableconstructor},
270and local variable declarations.
271
272\subsubsection{Blocks}
273A \Index{block} is a list of statements, executed sequentially.
274Any statement can be optionally followed by a semicolon.
275\begin{Produc}
276\produc{block}{\rep{stat sc} \opt{ret sc}}
277\produc{sc}{\opt{\ter{;}}}
278\end{Produc}%
279For syntactic reasons, a \Index{return statement} can only be written
280as the last statement of a block.
281This restriction also avoids some ``statement not reached'' errors.
282
283\subsubsection{\Index{Assignment}} \label{assignment}
284The language allows \Index{multiple assignment}.
285Therefore, the syntax defines a list of variables on the left side,
286and a list of expressions on the right side.
287Both lists have their elements separated by commas.
288\begin{Produc}
289\produc{stat}{varlist1 \ter{=} explist1}
290\produc{varlist1}{var \rep{\ter{,} var}}
291\end{Produc}%
292This statement first evaluates all values on the right side
293and eventual indices on the left side,
294and then makes the assignments.
295Therefore, it can be used to exchange two values, as in
296\begin{verbatim}
297 x, y = y, x
298\end{verbatim}
299Before the assignment, the list of values is {\em adjusted} to
300the length of the list of variables; \see{adjust}.
301
302\begin{Produc}
303\produc{var}{name}
304\end{Produc}%
305A single name can denote a global or a local variable,
306or a formal parameter.
307\begin{Produc}
308\produc{var}{var \ter{[} exp1 \ter{]}}
309\end{Produc}%
310Square brackets are used to index a table.
311If \verb'var' results in a table value,
312the field indexed by the expression value gets the assigned value.
313Otherwise, the fallback {\em settable} is called,
314with three parameters: the value of \verb'var',
315the value of expression, and the value being assigned to it;
316\see{fallback}.
317\begin{Produc}
318\produc{var}{var \ter{.} name}
319\end{Produc}%
320The syntax \verb'var.NAME' is just syntactic sugar for
321\verb'var["NAME"]'.
322
323\subsubsection{Control Structures}
324The \Index{condition expression} of a control structure can return any value.
325All values different from \nil\ are considered true,
326while \nil\ is considered false.
327{\tt if}'s, {\tt while}'s and {\tt repeat}'s have the usual meaning.
328
329\index{while-do}\index{repeat-until}\index{if-then-else}
330\begin{Produc}
331\produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end} \OrNL
332\rwd{repeat} block \rwd{until} exp1 \OrNL
333\rwd{if} exp1 \rwd{then} block \rep{elseif}
334 \opt{\rwd{else} block} \rwd{end}}
335\produc{elseif}{\rwd{elseif} exp1 \rwd{then} block}
336\end{Produc}
337
338A {\tt return} is used to return values from a function. \label{return}
339Because a function may return more than one value,
340the syntax for a \Index{return statement} is:
341\begin{Produc}
342\produc{ret}{\rwd{return} explist}
343\end{Produc}
344
345\subsubsection{Expressions as Statements} \label{statexp}
346All expressions with possible side-effects can be
347executed as statements.
348These include function calls and table constructors:
349\begin{Produc}
350\produc{stat}{functioncall}
351\produc{stat}{tableconstructor}
352\end{Produc}%
353Eventual returned values are thrown away.
354Function calls are explained in Section \ref{functioncall};
355constructors are the subject of Section \ref{tableconstructor}.
356
357\subsubsection{Local Declarations} \label{localvar}
358\Index{Local variables} can be declared anywhere inside a block.
359Their scope begins after the declaration and lasts until the
360end of the block.
361The declaration may include an initial assignment:
362\begin{Produc}
363\produc{stat}{\rwd{local} declist \opt{init}}
364\produc{declist}{name \rep{\ter{,} name}}
365\produc{init}{\ter{=} explist1}
366\end{Produc}%
367If there is an initial assignment, it has the same semantics
368of a multiple assignment.
369Otherwise, all variables are initialized with \nil.
370
371
372\subsection{\Index{Expressions}}
373
374\subsubsection{\Index{Simple Expressions}}
375Simple expressions are:
376\begin{Produc}
377\produc{exp}{\ter{(} exp \ter{)}}
378\produc{exp}{\rwd{nil}}
379\produc{exp}{\ter{number}}
380\produc{exp}{\ter{literal}}
381\produc{exp}{var}
382\end{Produc}%
383Numbers (numerical constants) and
384string literals are explained in Section~\ref{lexical}.
385Variables are explained in Section~\ref{assignment}.
386
387\subsubsection{Arithmetic Operators}
388Lua supports the usual \Index{arithmetic operators}.
389These operators are the binary
390\verb'+', \verb'-', \verb'*', \verb'/' and \verb'^' (exponentiation),
391and the unary \verb'-'.
392If the operands are numbers, or strings that can be converted to
393numbers, according to the rules given in Section \ref{coercion},
394all operations but exponentiation have the usual meaning.
395Otherwise, the fallback ``arith'' is called; \see{fallback}.
396An exponentiation always calls this fallback.
397The standard mathematical library redefines this fallback,
398giving the expected meaning to \Index{exponentiation};
399\see{mathlib}.
400
401\subsubsection{Relational Operators}
402Lua offers the following \Index{relational operators}:
403\begin{verbatim}
404 < > <= >= ~= ==
405\end{verbatim}
406All return \nil\ as false and 1 as true.
407
408Equality first compares the types of its operands.
409If they are different, the result is \nil.
410Otherwise, their values are compared.
411Numbers and strings are compared in the usual way.
412Tables, CFunctions, and functions are compared by reference,
413that is, two tables are considered equal only if they are the same table.
414The operator \verb'~=' is exactly the negation of equality (\verb'=').
415
416The other operators work as follows.
417If both arguments are numbers, they are compared as such.
418Otherwise, if both arguments can be converted to strings,
419their values are compared using lexicographical order.
420Otherwise, the fallback ``order'' is called; \see{fallback}.
421
422\subsubsection{Logical Operators}
423All logical operators, like control structures,
424consider \nil\ as false and anything else as true.
425The \Index{logical operators} are:
426\index{and}\index{or}\index{not}
427\begin{verbatim}
428 and or not
429\end{verbatim}
430The operators \verb'and' and \verb'or' use \Index{short-cut evaluation},
431that is,
432the second operand is evaluated only if necessary.
433
434\subsubsection{Concatenation}
435Lua offers a string \Index{concatenation} operator,
436denoted by ``\IndexVerb{..}''.
437If operands are strings or numbers, they are converted to
438strings according to the rules in Section \ref{coercion}.
439Otherwise, the fallback ``concat'' is called; \see{fallback}.
440
441\subsubsection{Precedence}
442\Index{Operator precedence} follows the table below,
443from the lower to the higher priority:
444\begin{verbatim}
445 and or
446 < > <= >= ~= =
447 ..
448 + -
449 * /
450 not - (unary)
451 ^
452\end{verbatim}
453All binary operators are left associative, except for \verb'^',
454which is right associative.
455
456\subsubsection{Table Constructors} \label{tableconstructor}
457Table \Index{constructors} are expressions that create tables;
458every time a constructor is evaluated, a new table is created.
459Constructors can be used to create empty tables,
460or to create a table and initialize some fields.
461
462The general syntax for constructors is:
463\begin{Produc}
464\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
465\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist}
466\produc{lfieldlist}{\opt{lfieldlist1}}
467\produc{ffieldlist}{\opt{ffieldlist1}}
468\end{Produc}
469
470The form {\em lfieldlist1} is used to initialize lists.
471\begin{Produc}
472\produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
473\end{Produc}%
474The expressions in the list are assigned to consecutive numerical indexes,
475starting with 1.
476As an example:
477\begin{verbatim}
478 a = {"v1", "v2", 34}
479\end{verbatim}
480is equivalent to:
481\begin{verbatim}
482 temp = {}
483 temp[1] = "v1"
484 temp[2] = "v2"
485 temp[3] = 34
486 a = temp
487\end{verbatim}
488
489The next form initializes named fields in a table.
490\begin{Produc}
491\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
492\produc{ffield}{name \ter{=} exp}
493\end{Produc}%
494As an example:
495\begin{verbatim}
496 a = {x = 1, y = 3}
497\end{verbatim}
498is equivalent to:
499\begin{verbatim}
500 temp = {}
501 temp.x = 1
502 temp.y = 3
503 a = temp
504\end{verbatim}
505
506
507\subsubsection{Function Calls} \label{functioncall}
508A \Index{function call} has the following syntax:
509\begin{Produc}
510\produc{functioncall}{var realParams}
511\end{Produc}%
512Here, \verb'var' can be any variable (global, local, indexed, etc).
513If its type is {\em function\/} or {\em CFunction\/},
514this function is called.
515Otherwise, the fallback ``function'' is called,
516having as first parameter the value of \verb'var',
517and then the original call parameters.
518
519The form:
520\begin{Produc}
521\produc{functioncall}{var \ter{:} name realParams}
522\end{Produc}%
523can be used to call ``methods''.
524A call \verb'var:name(...)'
525is syntactic sugar for
526\begin{verbatim}
527 var.name(var, ...)
528\end{verbatim}
529except that \verb'var' is evaluated only once.
530
531\begin{Produc}
532\produc{realParams}{\ter{(} \opt{explist1} \ter{)}}
533\produc{realParams}{tableconstructor}
534\produc{explist1}{exp1 \rep{\ter{,} exp1}}
535\end{Produc}%
536All argument expressions are evaluated before the call;
537then the list of \Index{arguments} is adjusted to
538the length of the list of parameters (\see{adjust});
539finally, this list is assigned to the formal parameters.
540A call of the form \verb'f{...}' is syntactic sugar for
541\verb'f({...})', that is,
542the parameter list is a single new table.
543
544Because a function can return any number of results
545(\see{return}),
546the number of results must be adjusted before used.
547If the function is called as an statement (\see{statexp}),
548its return list is adjusted to 0.
549If the function is called in a place that needs a single value
550(syntactically denoted by the non-terminal \verb'exp1'),
551its return list is adjusted to 1.
552If the function is called in a place that can hold many values
553(syntactically denoted by the non-terminal \verb'exp'),
554no adjustment is done.
555
556
557\subsection{\Index{Function Definitions}}
558
559Functions in Lua can be defined anywhere in the global level of a module.
560The syntax for function definition is:
561\begin{Produc}
562\produc{function}{\rwd{function} var \ter{(} \opt{parlist1} \ter{)}
563 block \rwd{end}}
564\end{Produc}
565
566When Lua pre-compiles a chunk,
567all its function bodies are pre-compiled, too.
568Then, when Lua ``executes'' the function definition,
569its body is stored, with type {\em function},
570into the variable \verb'var'.
571
572Parameters act as local variables,
573initialized with the argument values.
574\begin{Produc}
575\produc{parlist1}{'name' \rep{\ter{,} name}}
576\end{Produc}
577
578Results are returned using the \verb'return' statement (\see{return}).
579If control reaches the end of a function without a return instruction,
580the function returns with no results.
581
582There is a special syntax for definition of \Index{methods},
583that is, functions which have an extra parameter \Def{self}.
584\begin{Produc}
585\produc{function}{\rwd{function} var \ter{:} name \ter{(} \opt{parlist1}
586 \ter{)} block \rwd{end}}
587\end{Produc}%
588A declaration like
589\begin{verbatim}
590function v:f (...)
591 ...
592end
593\end{verbatim}
594is equivalent to
595\begin{verbatim}
596function v.f (self, ...)
597 ...
598end
599\end{verbatim}
600that is, the function gets an extra formal parameter called \verb'self'.
601Notice that
602the variable \verb'v' must be previously initialized with a table value.
603
604
605\subsection{Fallbacks} \label{fallback}
606
607Lua provides a powerful mechanism to extend its semantics,
608called \Def{fallbacks}.
609Basically, a fallback is a programmer defined function
610which is called whenever Lua does not know how to proceed.
611
612Lua supports the following fallbacks,
613identified by the given strings:
614\begin{description}
615\item[``arith'']\index{arithmetic fallback}
616called when an arithmetic operation is applied to non numerical operands,
617or when the binary \verb'^' operation is called.
618It receives three arguments:
619the two operands (the second one is nil when the operation is unary minus)
620and one of the following strings describing the offended operator:
621\begin{verbatim}
622 add sub mul div pow unm
623\end{verbatim}
624Its return value is the final result of the arithmetic operation.
625The default function issues an error.
626\item[``order'']\index{order fallback}
627called when an order comparison is applied to non numerical or
628non string operands.
629It receives three arguments:
630the two operands and
631one of the following strings describing the offended operator:
632\begin{verbatim}
633 lt gt le ge
634\end{verbatim}
635Its return value is the final result of the comparison operation.
636The default function issues an error.
637\item[``concat'']\index{concatenation fallback}
638called when a concatenation is applied to non string operands.
639It receives the two operands as arguments.
640Its return value is the final result of the concatenation operation.
641The default function issues an error.
642\item[``index'']\index{index fallback}
643called when Lua tries to retrieve the value of an index
644not present in a table.
645It receives as arguments the table and the index.
646Its return value is the final result of the indexing operation.
647The default function returns nil.
648\item[``gettable'']\index{gettable fallback}
649called when Lua tries to index a non table value.
650It receives as arguments the non table value and the index.
651Its return value is the final result of the indexing operation.
652The default function issues an error.
653\item[``settable'']\index{settable fallback}
654called when Lua tries to assign indexed a non table value.
655It receives as arguments the non table value,
656the index, and the assigned value.
657The default function issues an error.
658\item[``function'']\index{function falback}
659called when Lua tries to call a non function value.
660It receives as arguments the non function value and the
661arguments given in the original call.
662Its return values are the final results of the call operation.
663The default function issues an error.
664\item[``gc'']
665called during garbage collection.
666It receives as argument the table being collected.
667After each run of the collector this function is called with argument nil.
668Because this function operates during garbage collection,
669it must be used with great care,
670and programmers should avoid the creation of new objects
671(tables or strings) in this function.
672The default function does nothing.
673\item[``error'']\index{error fallback}
674called when an error occurs.
675It receives as argument a string describing the error.
676The default function prints the message on the standard error output.
677\end{description}
678
679The function \IndexVerb{setfallback} is used to change a fallback action.
680Its first argument is a string describing the fallback,
681and the second the new function to be called.
682It returns the old function for the given fallback.
683
684Section \ref{exfallback} shows an example of the use of fallbacks.
685
686
687\subsection{Error Handling} \label{error}
688
689Because Lua is an extension language,
690all Lua actions start from C code calling a function from the Lua library.
691Whenever an error occurs during Lua compilation or execution,
692an error fallback function is called,
693and then the corresponding function from the library
694(\verb'lua_dofile', \verb'lua_dostring',
695\verb'lua_call', and \verb'lua_callfunction')
696is terminated returning an error condition.
697
698The only argument to the error fallback function is a string describing
699the error and some extra informations,
700like current line (when the error is at compilation)
701or current function (when the error is at execution).
702For more information about an error,
703the Lua program can include the compilation pragma \verb'$debug'.
704\index{debug pragma}
705This pragma must be written in a line by itself.
706When an error occurs in a program compiled with this option,
707the error message includes extra information showing the stack of calls.
708
709The standard error routine only prints the error message
710to \verb'stderr'.
711If needed, it is possible to change the error fallback routine;
712\see{fallback}.
713
714Lua code can generate an error by calling the function \verb'error'.
715Its optional parameter is a string,
716which is used as the error message.
717
718
719\section{The Application Program Interface}
720
721This section describes the API for Lua, that is,
722the set of C functions available to the host program to communicate
723with the library.
724The API functions can be classified in the following categories:
725\begin{enumerate}
726\item executing Lua code;
727\item converting values between C and Lua;
728\item manipulating (reading and writing) Lua objects;
729\item calling Lua functions;
730\item C functions to be called by Lua;
731\item locking Lua Objects.
732\end{enumerate}
733All API functions are declared in the file \verb'lua.h'.
734
735\subsection{Executing Lua Code}
736A host program can execute Lua programs written in a file or in a string,
737using the following functions:
738\Deffunc{lua_dofile}\Deffunc{lua_dostring}
739\begin{verbatim}
740int lua_dofile (char *filename);
741int lua_dostring (char *string);
742\end{verbatim}
743Both functions return an error code:
7440, in case of success; non zero, in case of errors.
745The function \verb'lua_dofile', if called with argument NULL (0),
746executes the ``file'' {\tt stdin}.
747
748\subsection{Converting Values between C and Lua} \label{valuesCLua}
749Because Lua has no static type system,
750all values passed between Lua and C have type \IndexVerb{lua\_Object},
751which works like an abstract type in C that can hold any Lua value.
752
753Lua has automatic memory management, and garbage collection.
754Because of that, a \verb'lua_Object' has a limited scope,
755and is only valid inside the {\em block\/} where it was created.
756A C function called from Lua is a block,
757and its parameters are valid only until its end.
758A good programming practice is to convert Lua objects to C values
759as soon as they are available,
760and never to store \verb'lua_Object's in C global variables.
761
762When C code calls Lua repeatedly, as in a loop,
763objects returned by these calls accumulate,
764and may create a memory problem.
765To avoid this,
766nested blocks can be defined with the functions:
767\begin{verbatim}
768void lua_beginblock (void);
769void lua_endblock (void);
770\end{verbatim}
771After the end of the block,
772all \verb'lua_Object''s created inside it are released.
773
774To check the type of a \verb'lua_Object',
775the following function is available:
776\Deffunc{lua_type}
777\begin{verbatim}
778int lua_type (lua_Object object);
779\end{verbatim}
780plus the following macros:
781\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring}
782\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata}
783\begin{verbatim}
784int lua_isnil (lua_Object object);
785int lua_isnumber (lua_Object object);
786int lua_isstring (lua_Object object);
787int lua_istable (lua_Object object);
788int lua_iscfunction (lua_Object object);
789int lua_isuserdata (lua_Object object);
790\end{verbatim}
791All macros return 1 if the object has the given type,
792and 0 otherwise.
793
794The function \verb'lua_type' can be used to distinguish between
795different kinds of user data; see below.
796
797To translate a value from type \verb'lua_Object' to a specific C type,
798the programmer can use:
799\Deffunc{lua_getnumber}\Deffunc{lua_getstring}
800\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
801\begin{verbatim}
802double lua_getnumber (lua_Object object);
803char *lua_getstring (lua_Object object);
804lua_CFunction lua_getcfunction (lua_Object object);
805void *lua_getuserdata (lua_Object object);
806\end{verbatim}
807\verb'lua_getnumber' converts a \verb'lua_Object' to a float.
808This \verb'lua_Object' must be a number or a string convertible to number
809(\see{coercion}); otherwise, the function returns 0.
810
811\verb'lua_getstring' converts a \verb'lua_Object' to a string (\verb'char *').
812This \verb'lua_Object' must be a string or a number;
813otherwise, the function returns 0 (the null pointer).
814This function does not create a new string, but returns a pointer to
815a string inside the Lua environment.
816Because Lua has garbage collection, there is no guarantee that such
817pointer will be valid after the block ends.
818
819\verb'lua_getcfunction' converts a \verb'lua_Object' to a C function.
820This \verb'lua_Object' must have type {\em CFunction\/};
821otherwise, the function returns 0 (the null pointer).
822The type \verb'lua_CFunction' is explained in Section~\ref{LuacallC}.
823
824\verb'lua_getuserdata' converts a \verb'lua_Object' to \verb'void*'.
825This \verb'lua_Object' must have type {\em userdata\/};
826otherwise, the function returns 0 (the null pointer).
827
828The reverse process, that is, passing a specific C value to Lua,
829is done by using the following functions:
830\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring}\Deffunc{lua_pushliteral}
831\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}\Deffunc{lua_pushuserdata}
832\begin{verbatim}
833void lua_pushnumber (double n);
834void lua_pushstring (char *s);
835void lua_pushliteral (char *s);
836void lua_pushcfunction (lua_CFunction f);
837void lua_pushusertag (void *u, int tag);
838\end{verbatim}
839plus the macro:
840\begin{verbatim}
841void lua_pushuserdata (void *u);
842\end{verbatim}
843All of them receive a C value,
844convert it to a correspondent \verb'lua_Object',
845and leave the result on the top of the Lua stack,
846where it can be assigned to a Lua variable,
847passed as paramenter to a Lua function, etc (see below). \label{pushing}
848\verb'lua_pushliteral' is like \verb'lua_pushstring',
849but also puts the string in the Lua literal table.
850This avoids the string to be garbage collected,
851and therefore has a better overall performance.
852As a rule, when the string to be pushed is a literal,
853\verb'lua_pushliteral' should be used.
854
855User data can have different tags,
856whose semantics are defined by the host program.
857Any positive integer can be used to tag a user data.
858When a user data is retrieved,
859the function \verb'lua_type' can be used to get its tag.
860
861To complete the set,
862the value \nil\ or a \verb'lua_Object' can also be pushed onto the stack,
863with:
864\Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
865\begin{verbatim}
866void lua_pushnil (void);
867void lua_pushobject (lua_Object object);
868\end{verbatim}
869
870
871\subsection{Manipulating Lua Objects}
872To read the value of any global Lua variable,
873one can use the function:
874\Deffunc{lua_getglobal}
875\begin{verbatim}
876lua_Object lua_getglobal (char *varname);
877\end{verbatim}
878To store a value previously pushed onto the stack in a global variable,
879there is the function:
880\Deffunc{lua_storeglobal}
881\begin{verbatim}
882void lua_storeglobal (char *varname);
883\end{verbatim}
884
885Tables can also be manipulated via the API.
886The function
887\Deffunc{lua_getsubscript}
888\begin{verbatim}
889lua_Object lua_getsubscript (void);
890\end{verbatim}
891expects on the stack a table and an index,
892and returns the contents of the table at that index.
893As in Lua, if the first object is not a table,
894or the index is not present in the table,
895the correspondent fallback is called.
896
897For compatibility with previous versions of the API,
898the following macros are supported:
899\Deffunc{lua_getindexed}\Deffunc{lua_getfield}
900\begin{verbatim}
901lua_Object lua_getindexed (lua_Object table, float index);
902lua_Object lua_getfield (lua_Object table, char *field);
903\end{verbatim}
904The first one is used for numeric indices,
905while the second can be used for any string index.
906
907To store a value in an index,
908the program must push onto the stack the table, the index,
909and the value,
910and then call the function:
911\Deffunc{lua_storesubscript}
912\begin{verbatim}
913void lua_storesubscript (void);
914\end{verbatim}
915Again, the correspondent fallback is called if needed.
916
917Finally, the function
918\Deffunc{lua_createtable}
919\begin{verbatim}
920lua_Object lua_createtable (void);
921\end{verbatim}
922creates a new table.
923
924{\em Please Notice:\/}
925Most functions from the Lua library receive parameters through the stack.
926Because other functions also use the stack,
927it is important that these
928parameters be pushed just before the correspondent call,
929without intermediate calls to the Lua library.
930For instance, suppose the user wants the value of \verb'a[i]'.
931A simplistic solution would be:
932\begin{verbatim}
933 /* Warning: WRONG CODE */
934 lua_Object result;
935 lua_pushobject(lua_getglobal("a")); /* push table */
936 lua_pushobject(lua_getglobal("i")); /* push index */
937 result = lua_getsubscript();
938\end{verbatim}
939However, the call \verb'lua_getglobal("i")' modifies the stack,
940and invalidates the previous pushed value.
941A correct solution could be:
942\begin{verbatim}
943 lua_Object result;
944 lua_Object index = lua_getglobal("i");
945 lua_pushobject(lua_getglobal("a")); /* push table */
946 lua_pushobject(index); /* push index */
947 result = lua_getsubscript();
948\end{verbatim}
949
950\subsection{Calling Lua Functions}
951Functions defined in Lua by a chunk executed with
952\verb'dofile' or \verb'dostring' can be called from the host program.
953This is done using the following protocol:
954first, the arguments to the function are pushed onto the Lua stack
955(\see{pushing}), in direct order, i.e., the first argument is pushed first.
956Again, it is important to emphasize that, during this phase,
957no other Lua function can be called.
958
959Then, the function is called using
960\Deffunc{lua_call}\Deffunc{lua_callfunction}
961\begin{verbatim}
962int lua_call (char *functionname);
963\end{verbatim}
964or
965\begin{verbatim}
966int lua_callfunction (lua_Object function);
967\end{verbatim}
968Both functions return an error code:
9690, in case of success; non zero, in case of errors.
970Finally, the returned values (a Lua function may return many values)
971can be retrieved with the macro
972\Deffunc{lua_getresult}
973\begin{verbatim}
974lua_Object lua_getresult (int number);
975\end{verbatim}
976where \verb'number' is the order of the result, starting with 1.
977When called with a number larger than the actual number of results,
978this function returns \verb'LUA_NOOBJECT'.
979
980Two special Lua functions have exclusive interfaces:
981\verb'error' and \verb'setfallback'.
982A C function can generate a Lua error calling the function
983\Deffunc{lua_error}
984\begin{verbatim}
985void lua_error (char *message);
986\end{verbatim}
987This function never returns.
988If the C function has been called from Lua,
989the corresponding Lua execution terminates,
990as if an error had occurred inside Lua code.
991Otherwise, the whole program terminates.
992
993Fallbacks can be changed with:
994\Deffunc{lua_setfallback}
995\begin{verbatim}
996lua_Object lua_setfallback (char *name, lua_CFunction fallback);
997\end{verbatim}
998The first parameter is the fallback name,
999and the second a CFunction to be used as the new fallback.
1000This function returns a \verb'lua_Object',
1001which is the old fallback value,
1002or nil on fail (invalid fallback name).
1003This old value can be used for chaining fallbacks.
1004
1005An example of C code calling a Lua function is shown in
1006Section~\ref{exLuacall}.
1007
1008
1009\subsection{C Functions} \label{LuacallC}
1010To register a C function to Lua,
1011there is the following macro:
1012\Deffunc{lua_register}
1013\begin{verbatim}
1014#define lua_register(n,f) (lua_pushcfunction(f), lua_storeglobal(n))
1015/* char *n; */
1016/* lua_CFunction f; */
1017\end{verbatim}
1018which receives the name the function will have in Lua,
1019and a pointer to the function.
1020This pointer must have type \verb'lua_CFunction',
1021which is defined as
1022\Deffunc{lua_CFunction}
1023\begin{verbatim}
1024typedef void (*lua_CFunction) (void);
1025\end{verbatim}
1026that is, a pointer to a function with no parameters and no results.
1027
1028In order to communicate properly with Lua,
1029a C function must follow a protocol,
1030which defines the way parameters and results are passed.
1031
1032To access its arguments, a C function calls:
1033\Deffunc{lua_getparam}
1034\begin{verbatim}
1035lua_Object lua_getparam (int number);
1036\end{verbatim}
1037where \verb'number' starts with 1 to get the first argument.
1038When called with a number larger than the actual number of arguments,
1039this function returns \IndexVerb{LUA\_NOOBJECT}.
1040In this way, it is possible to write functions that work with
1041a variable number of parameters.
1042
1043To return values, a C function just pushes them onto the stack,
1044in direct order; \see{valuesCLua}.
1045Like a Lua function, a C function called by Lua can also return
1046many results.
1047
1048Section~\ref{exCFunction} presents an example of a CFunction.
1049
1050
1051\subsection{Locking Lua Objects}
1052
1053As already noted, \verb'lua_Object's are volatile.
1054If the C code needs to keep a \verb'lua_Object'
1055outside block boundaries,
1056it has to {\em lock} the object.
1057The routines to manipulate locking are the following:
1058\Deffunc{lua_lock}\Deffunc{lua_getlocked}
1059\Deffunc{lua_pushlocked}\Deffunc{lua_unlock}
1060\begin{verbatim}
1061int lua_lock (void);
1062lua_Object lua_getlocked (int ref);
1063void lua_pushlocked (int ref);
1064void lua_unlock (int ref);
1065\end{verbatim}
1066The function \verb'lua_lock' locks the object
1067which is on the top of the stack,
1068and returns a reference to it.
1069Whenever the locked object is needed,
1070a call to \verb'lua_getlocked'
1071returns a handle to it,
1072while \verb'lua_pushlocked' pushes the handle on the stack.
1073When a locked object is no longer needed,
1074it can be unlocked with a call to \verb'lua_unlock'.
1075
1076
1077
1078\section{Predefined Functions and Libraries}
1079
1080The set of \Index{predefined functions} in Lua is small but powerful.
1081Most of them provide features that allows some degree of
1082\Index{reflexivity} in the language.
1083Many of these features cannot be simulated with the rest of the
1084Language nor with the standard API.
1085
1086The libraries, on the other hand, provide useful routines
1087that are implemented directly through the standard API.
1088Therefore, they are not necessary to the language,
1089and are provided as separated C modules.
1090Currently there are three standard libraries:
1091\begin{itemize}
1092\item string manipulation;
1093\item mathematical functions (sin, cos, etc);
1094\item input and output.
1095\end{itemize}
1096In order to have access to these libraries,
1097the host program must call the functions
1098\verb-strlib_open-, \verb-mathlib_open-, and \verb-iolib_open-,
1099declared in \verb-lualib.h-.
1100
1101
1102\subsection{Predefined Functions}
1103
1104\subsubsection*{{\tt dofile (filename)}}\Deffunc{dofile}
1105This function receives a file name,
1106opens it and executes its contents as a Lua chunk.
1107It returns 1 if there are no errors, \nil\ otherwise.
1108
1109\subsubsection*{{\tt dostring (string)}}\Deffunc{dostring}
1110This function executes a given string as a Lua chunk.
1111It returns 1 if there are no errors, \nil\ otherwise.
1112
1113\subsubsection*{{\tt next (table, index)}}\Deffunc{next}
1114This function allows a program to traverse all fields of a table.
1115Its first argument is a table and its second argument
1116is an index in this table.
1117It returns the next index of the table and the
1118value associated with the index.
1119When called with \nil\ as its second argument,
1120the function returns the first index
1121of the table (and its associated value).
1122When called with the last index, or with \nil\ in an empty table,
1123it returns \nil.
1124
1125In Lua there is no declaration of fields;
1126semantically, there is no difference between a
1127field not present in a table or a field with value \nil.
1128Therefore, the function only considers fields with non nil values.
1129The order the indices are enumerated is not specified,
1130{\em even for numeric indices}.
1131
1132See Section \ref{exnext} for an example of the use of this function.
1133
1134\subsubsection*{{\tt nextvar (name)}}\Deffunc{nextvar}
1135This function is similar to the function \verb'next',
1136but it iterates over the global variables.
1137Its single argument is the name of a global variable,
1138or \nil\ to get a first name.
1139Similarly to \verb'next', it returns the name of another variable
1140and its value,
1141or \nil\ if there are no more variables.
1142See Section \ref{exnext} for an example of the use of this function.
1143
1144\subsubsection*{{\tt print (e1, e2, ...)}}\Deffunc{print}
1145This function receives any number of arguments,
1146and prints their values in a reasonable format.
1147Each value is printed in a new line.
1148This function is not intended for formatted output,
1149but as a quick way to show a value,
1150for instance for error messages or debugging.
1151See Section~\ref{libio} for functions for formatted output.
1152
1153\subsubsection*{{\tt tonumber (e)}}\Deffunc{tonumber}
1154This function receives one argument,
1155and tries to convert it to a number.
1156If the argument is already a number or a string convertible
1157to a number (\see{coercion}), it returns that number;
1158otherwise, it returns \nil.
1159
1160\subsubsection*{{\tt type (v)}}\Deffunc{type}
1161This function allows Lua to test the type of a value.
1162It receives one argument, and returns its type, coded as a string.
1163The possible results of this function are
1164\verb'"nil"' (a string, not the value \nil),
1165\verb'"number"',
1166\verb'"string"',
1167\verb'"table"',
1168\verb'"function"' (returned both for C functions and Lua functions),
1169and \verb'"userdata"'.
1170
1171Besides this string, the function returns a second result,
1172which is the \Def{tag} of the value.
1173This tag can be used to distinguish between user
1174data with different tags,
1175and between C functions and Lua functions.
1176
1177\subsubsection*{{\tt error (message)}}\Deffunc{error}
1178This function issues an error message and terminates
1179the last called function from the library
1180(\verb'lua_dofile', \verb'lua_dostring', \ldots).
1181It never returns.
1182
1183\subsubsection*{{\tt setglobal (name, value)}}\Deffunc{setglobal}
1184This function assigns the given value to a global variable.
1185The string \verb'name' does not need to be a syntactically valid variable name.
1186Therefore, this function can set global variables with strange names like
1187\verb'm v 1' or \verb'34'.
1188
1189\subsubsection*{{\tt getglobal (name)}}\Deffunc{getglobal}
1190This function retrieves the value of a global variable.
1191The string \verb'name' does not need to be a syntactically valid variable name.
1192
1193\subsubsection*{{\tt setfallback (fallbackname, newfallback)}}
1194\Deffunc{setfallback}
1195This function sets a new fallback function to the given fallback.
1196It returns the old fallback function.
1197
1198\subsection{String Manipulation}
1199This library provides generic functions for string manipulation,
1200such as finding and extracting substrings.
1201When indexing a string, the first character has position 1.
1202See Section \ref{exstring} for some examples on string manipulation
1203in Lua.
1204
1205\subsubsection*{{\tt strfind (str, substr, [init, [end]])}}
1206\Deffunc{strfind}
1207Receives two string arguments,
1208and returns a number.
1209This number indicates the first position where the second argument appears
1210in the first argument.
1211If the second argument is not a substring of the first one,
1212then \verb'strfind' returns \nil.
1213A third optional numerical argument specifies where to start the search.
1214Another optional numerical argument specifies where to stop it.
1215
1216\subsubsection*{{\tt strlen (s)}}\Deffunc{strlen}
1217Receives a string and returns its length.
1218
1219\subsubsection*{{\tt strsub (s, i, [j])}}\Deffunc{strsub}
1220Returns another string, which is a substring of \verb's',
1221starting at \verb'i' and runing until \verb'j'.
1222If \verb'j' is absent,
1223it is assumed to be equal to the length of \verb's'.
1224Particularly, the call \verb'strsub(s,1,j)' returns a prefix of \verb's'
1225with length \verb'j',
1226while the call \verb'strsub(s,i)' returns a suffix of \verb's',
1227starting at \verb'i'.
1228
1229\subsubsection*{{\tt strlower (s)}}\Deffunc{strlower}
1230Receives a string and returns a copy of that string with all
1231upper case letters changed to lower case.
1232All other characters are left unchanged.
1233
1234\subsubsection*{{\tt strupper (s)}}\Deffunc{strupper}
1235Receives a string and returns a copy of that string with all
1236lower case letters changed to upper case.
1237All other characters are left unchanged.
1238
1239\subsubsection*{{\tt ascii (s, [i])}}\Deffunc{ascii}
1240Returns the ascii code of the character \verb's[i]'.
1241If \verb'i' is absent, it is assumed to be 1.
1242
1243\subsubsection*{{\tt int2str (\{i\})}}\Deffunc{int2str}
1244Receives 0 or more numbers.
1245Returns a string with length equal to the number of arguments,
1246wherein each character has ascii value equal
1247to its correspondent argument.
1248
1249\subsection{Mathematical Functions} \label{mathlib}
1250
1251This library is an interface to some functions of the standard C math library.
1252Moreover, it registers a fallback for the binary operator \verb'^' which,
1253when applied to numbers \verb'x^y', returns $x^y$.
1254
1255The library provides the following functions:
1256\Deffunc{abs}\Deffunc{acos}\Deffunc{asin}\Deffunc{atan}
1257\Deffunc{atan2}\Deffunc{ceil}\Deffunc{cos}\Deffunc{floor}
1258\Deffunc{log}\Deffunc{log10}\Deffunc{max}\Deffunc{min}
1259\Deffunc{mod}\Deffunc{sin}\Deffunc{sqrt}\Deffunc{tan}
1260\begin{verbatim}
1261abs acos asin atan atan2 ceil cos floor
1262log log10 max min mod sin sqrt tan
1263\end{verbatim}
1264Most of them
1265are only interfaces to the homonymous functions in the C library,
1266except that, for the trigonometric functions,
1267all angles are expressed in degrees.
1268
1269The function \verb'max' returns the maximum
1270value of its numeric arguments.
1271Similarly, \verb'min' computes the minimum.
1272Both can be used with an unlimited number of arguments.
1273
1274The function \verb'mod' is equivalent to the \verb'%' operator in C.
1275
1276
1277\subsection{I/O Facilities} \label{libio}
1278
1279All I/O operations in Lua are done over two {\em current} files,
1280one for reading and one for writing.
1281Initially, the current input file is \verb'stdin',
1282and the current output file is \verb'stdout'.
1283
1284Unless otherwise stated,
1285all I/O functions return 1 on success and \nil\ on failure.
1286
1287\subsubsection*{{\tt readfrom (filename)}}\Deffunc{readfrom}
1288
1289This function opens a file named \verb'filename' and sets it as the
1290{\em current} input file.
1291When called without parameters,
1292this function closes the current input file,
1293and restores \verb'stdin' as the current input file.
1294
1295{\em System dependent:} if \verb'filename' starts with a \verb'|',
1296then a \Index{piped input} is open, via function \IndexVerb{popen}.
1297
1298\subsubsection*{{\tt writeto (filename)}}\Deffunc{writeto}
1299
1300This function opens a file named \verb'filename' and sets it as the
1301{\em current} output file.
1302Notice that, if the file already exists, it is completely erased with this
1303operation.
1304When called without parameters,
1305this function closes the current output file,
1306and restores \verb'stdout' as the current output file.
1307\index{closing a file}
1308
1309{\em System dependent:} if \verb'filename' starts with a \verb'|',
1310then a \Index{piped output} is open, via function \IndexVerb{popen}.
1311
1312\subsubsection*{{\tt appendto (filename)}}\Deffunc{appendto}
1313
1314This function opens a file named \verb'filename' and sets it as the
1315{\em current} output file.
1316Unlike the \verb'writeto' operation,
1317this function does not erase any previous content of the file.
1318This function returns 2 if the file already exists,
13191 if it creates a new file, and \nil\ on failure.
1320
1321\subsubsection*{{\tt remove (filename)}}\Deffunc{remove}
1322
1323This function deletes the file with the given name.
1324
1325\subsubsection*{{\tt read ([format])}}\Deffunc{read}
1326
1327This function returns a value read from the current input.
1328An optional string argument specifies the way the input is interpreted.
1329
1330Without a format argument, {\tt read} first skips blanks, tabs and newlines.
1331Then it checks whether the current character is \verb'"' or \verb-'-.
1332If so, it reads a string up to the ending quotation mark,
1333and returns this string, without the quotation marks.
1334Otherwise it reads up to a blank, tab or newline.
1335
1336The format string can have the following format:
1337\begin{verbatim}
1338 ?[n]
1339\end{verbatim}
1340where \verb'?' can be:
1341\begin{description}
1342\item['s' or 'S'] to read a string;
1343\item['f' or 'F'] to read a real number;
1344\item['i' or 'I'] to read an integer.
1345\end{description}
1346The optional \verb'n' is a number which specifies how many characters
1347must be read to compose the input value.
1348Particularly, the format \verb'"s1"' reads a single character.
1349
1350\subsubsection*{{\tt readuntil (char)}}\Deffunc{readuntil}
1351
1352Reads the current input until the first ocurrence of the given character.
1353Returns the string read.
1354The character itself is not read.
1355
1356\subsubsection*{{\tt write (value, [format])}}\Deffunc{write}
1357
1358This function writes the value of its first argument to the current output.
1359An optional second argument specifies the format to be used.
1360This format is given as a string, composed of four parts.
1361The first part is the only one not optional, and must be one of the
1362following characters:
1363\begin{description}
1364\item['s' or 'S'] to write strings;
1365\item['f' or 'F'] to write floats;
1366\item['i' or 'I'] to write integers.
1367\end{description}
1368These characters can be followed by
1369\begin{verbatim}
1370 [?][m][.n]
1371\end{verbatim}
1372where:
1373\begin{description}
1374\item[\verb'?'] indicates justification inside the field.
1375\begin{itemize}
1376\item['\verb'<''] right justification (default);
1377\item['\verb'>''] left justification;
1378\item['\verb'|''] center justification.
1379\end{itemize}
1380\item[\verb'm'] Indicates the field size in characters.
1381\item[\verb'.n'] For reals, indicates the number of digital places.
1382For integers, it is the minimum number of digits.
1383This option has no meaning for strings.
1384\end{description}
1385
1386When called without a format string,
1387this function writes numbers using the \verb'%g' format
1388and strings with \verb'%s'.
1389
1390% \subsubsection*{{\tt debug ()}}
1391% This function, when called, repeatedly presents a prompt \verb'lua_debug> '
1392% in the error output stream (\verb'stderr'),
1393% reads a line from the standard input,
1394% and executes (``dostring'') the line.
1395% The loop ends when the user types \verb'cont' to the prompt.
1396% This function then returns and the execution of the program continues.
1397
1398
1399\section{Some Examples}
1400
1401This section gives examples showing some features of Lua.
1402It does not intend to cover the whole language,
1403but only to illustrate some interesting uses of the system.
1404
1405
1406\subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext}
1407\Deffunc{next}\Deffunc{nextvar}
1408This example shows how to use the function \verb'next' to iterate
1409over the fields of a table.
1410Function \Def{clone} receives any table and returns a clone of it.
1411\begin{verbatim}
1412function clone (t) -- t is a table
1413 local new_t = {} -- creates a new table
1414 local i, v = next(t, nil) -- i is an index of t, v = t[i]
1415 while i do
1416 new_t[i] = v
1417 i, v = next(t, i) -- get next index
1418 end
1419 return new_t
1420end
1421\end{verbatim}
1422
1423The next example prints the names of all global variables
1424in the system with non nil values:
1425\begin{verbatim}
1426function printGlobalVariables ()
1427 local i, v = nextvar(nil)
1428 while i do
1429 print(i)
1430 i, v = nextvar(i)
1431 end
1432end
1433\end{verbatim}
1434
1435
1436\subsection{String Manipulation} \label{exstring}
1437
1438The first example is a function to trim extra blanks at the beginning
1439and end of a string.
1440\begin{verbatim}
1441function trim(s)
1442 local l = 1
1443 while strsub(s,l,l) == ' ' do
1444 l = l+1
1445 end
1446 local r = strlen(s)
1447 while strsub(s,r,r) == ' ' do
1448 r = r-1
1449 end
1450 return strsub(s,l,r)
1451end
1452\end{verbatim}
1453
1454The second example shows a function that eliminates all blanks
1455of a string.
1456\begin{verbatim}
1457function remove_blanks (s)
1458 local b = strfind(s, ' ')
1459 while b do
1460 s = strsub(s, 1, b-1) .. strsub(s, b+1)
1461 b = strfind(s, ' ')
1462 end
1463 return s
1464end
1465\end{verbatim}
1466
1467
1468\subsection{\Index{Persistence}}
1469Because of its reflexive facilities,
1470persistence in Lua can be achieved within the language.
1471This section shows some ways to store and retrieve values in Lua,
1472using a text file written in the language itself as the storage media.
1473
1474To store a single value with a name,
1475the following code is enough:
1476\begin{verbatim}
1477function store (name, value)
1478 write('\n' .. name .. '=')
1479 write_value(value)
1480end
1481\end{verbatim}
1482\begin{verbatim}
1483function write_value (value)
1484 local t = type(value)
1485 if t == 'nil' then write('nil')
1486 elseif t == 'number' then write(value)
1487 elseif t == 'string' then write('[[' .. value .. ']]')
1488 end
1489end
1490\end{verbatim}
1491In order to restore this value, a \verb'lua_dofile' suffices.
1492
1493Storing tables is a little more complex.
1494Assuming that the table is a tree,
1495and all indices are identifiers
1496(that is, the tables are being used as records),
1497its value can be written directly with table constructors.
1498First, the function \verb'write_value' is changed to
1499\begin{verbatim}
1500function write_value (value)
1501 local t = type(value)
1502 if t == 'nil' then write('nil')
1503 elseif t == 'number' then write(value)
1504 elseif t == 'string' then write('"' .. value .. '"')
1505 elseif t == 'table' then write_record(value)
1506 end
1507end
1508\end{verbatim}
1509The function \verb'write_record' is:
1510\begin{verbatim}
1511function write_record(t)
1512 local i, v = next(t, nil)
1513 write('{') -- starts constructor
1514 while i do
1515 store(i, v)
1516 write(', ')
1517 i, v = next(t, i)
1518 end
1519 write('}') -- closes constructor
1520end
1521\end{verbatim}
1522
1523
1524\subsection{Inheritance} \label{exfallback}
1525The fallback for absent indices can be used to implement many
1526kinds of \Index{inheritance} in Lua.
1527As an example,
1528the following code implements single inheritance:
1529\begin{verbatim}
1530function Index (t,f)
1531 if f == 'parent' then -- to avoid loop
1532 return OldIndex(t,f)
1533 end
1534 local p = t.parent
1535 if type(p) == 'table' then
1536 return p[f]
1537 else
1538 return OldIndex(t,f)
1539 end
1540end
1541
1542OldIndex = setfallback("index", Index)
1543\end{verbatim}
1544Whenever Lua attempts to access an absent field in a table,
1545it calls the fallback function \verb'Index'.
1546If the table has a field \verb'parent' with a table value,
1547then Lua attempts to access the desired field in this parent object.
1548This process is repeated ``upwards'' until a value
1549for the field is found or the object has no parent.
1550In the latter case, the previous fallback is called to supply a value
1551for the field.
1552
1553When better performance is needed,
1554the same fallback may be implemented in C,
1555as illustrated in Figure~\ref{Cinher}.
1556\begin{figure}
1557\Line
1558\begin{verbatim}
1559int lockedParentName; /* stores the lock index for the string "parent" */
1560int lockedOldIndex; /* previous fallback function */
1561
1562void callOldFallback (lua_Object table, lua_Object index)
1563{
1564 lua_Object oldIndex = lua_getlocked(lockedOldIndex);
1565 lua_pushobject(table);
1566 lua_pushobject(index);
1567 lua_callfunction(oldIndex);
1568}
1569
1570void Index (void)
1571{
1572 lua_Object table = lua_getparam(1);
1573 lua_Object index = lua_getparam(2);
1574 lua_Object parent;
1575 if (lua_isstring(index) && strcmp(lua_getstring(index), "parent") == 0)
1576 {
1577 callOldFallback(table, index);
1578 return;
1579 }
1580 lua_pushobject(table);
1581 lua_pushlocked(lockedParentName);
1582 parent = lua_getsubscript();
1583 if (lua_istable(parent))
1584 {
1585 lua_pushobject(parent);
1586 lua_pushobject(index);
1587 /* return result from getsubscript */
1588 lua_pushobject(lua_getsubscript());
1589 }
1590 else
1591 callOldFallback(table, index);
1592}
1593\end{verbatim}
1594\caption{Inheritance in C.\label{Cinher}}
1595\Line
1596\end{figure}
1597This code must be registered with:
1598\begin{verbatim}
1599 lua_pushliteral("parent");
1600 lockedParentName = lua_lock();
1601 lua_pushobject(lua_setfallback("index", Index));
1602 lockedOldIndex = lua_lock();
1603\end{verbatim}
1604Notice how the string \verb'"parent"' is kept
1605locked in Lua for optimal performance.
1606
1607\subsection{A CFunction} \label{exCFunction}\index{functions in C}
1608A CFunction to compute the maximum of a variable number of arguments
1609is shown in Figure~\ref{Cmax}.
1610\begin{figure}
1611\Line
1612\begin{verbatim}
1613void math_max (void)
1614{
1615 int i=1; /* number of arguments */
1616 double d, dmax;
1617 lua_Object o;
1618 /* the function must get at least one argument */
1619 if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
1620 lua_error ("too few arguments to function `max'");
1621 /* and this argument must be a number */
1622 if (!lua_isnumber(o))
1623 lua_error ("incorrect argument to function `max'");
1624 dmax = lua_getnumber (o);
1625 /* loops until there is no more arguments */
1626 while ((o = lua_getparam(i++)) != LUA_NOOBJECT)
1627 {
1628 if (!lua_isnumber(o))
1629 lua_error ("incorrect argument to function `max'");
1630 d = lua_getnumber (o);
1631 if (d > dmax) dmax = d;
1632 }
1633 /* push the result to be returned */
1634 lua_pushnumber (dmax);
1635}
1636\end{verbatim}
1637\caption{C function {\tt math\_max}.\label{Cmax}}
1638\Line
1639\end{figure}
1640After registered with
1641\begin{verbatim}
1642lua_register ("max", math_max);
1643\end{verbatim}
1644this function is available in Lua, as follows:
1645\begin{verbatim}
1646i = max(4, 5, 10, -34) -- i receives 10
1647\end{verbatim}
1648
1649
1650\subsection{Calling Lua Functions} \label{exLuacall}
1651
1652This example illustrates how a C function can call the Lua function
1653\verb'remove_blanks' presented in Section~\ref{exstring}.
1654\begin{verbatim}
1655void remove_blanks (char *s)
1656{
1657 lua_pushstring(s); /* prepare parameter */
1658 lua_call("remove_blanks"); /* call Lua function */
1659 strcpy(s, lua_getstring(lua_getresult(1))); /* copy result back to 's' */
1660}
1661\end{verbatim}
1662
1663
1664\section*{Acknowledgments}
1665
1666The authors would like to thank CENPES/PETROBR\'AS which,
1667jointly with TeCGraf, used extensively early versions of
1668this system and gave valuable comments.
1669The authors would also like to thank Carlos Henrique Levy,
1670who found the name of the game%
1671\footnote{BTW, Lua means {\em moon} in Portuguese.}.
1672
1673
1674
1675\appendix
1676
1677\section{Incompatibilities with Previous Versions}
1678
1679Although great care has been taken to avoid incompatibilities with
1680the previous public versions of Lua,
1681some differences had to be introduced.
1682Here is a list of all these differences.
1683
1684\subsection*{Incompatibilities with \Index{version 2.1}}
1685\begin{itemize}
1686\item
1687The function {\tt type} now returns the string {\tt function}
1688both for C and Lua functions.
1689Because Lua functions and C functions are compatible,
1690this behavior is usually more useful.
1691When needed, the second result of function {\tt type} may be used
1692to distinguish between Lua and C functions.
1693\item
1694A function definition only assigns the function value to the
1695given variable at execution time.
1696\end{itemize}
1697
1698\subsection*{Incompatibilities with \Index{version 1.1}}
1699\begin{itemize}
1700\item
1701The equality test operator now is denoted by \verb'==',
1702instead of \verb'='.
1703\item
1704The syntax for table construction has been greatly simplified.
1705The old \verb'@(size)' has been substituted by \verb'{}'.
1706The list constructor (formerly \verb'@[...]') and the record
1707constructor (formerly \verb'@{...}') now are both coded like
1708\verb'{...}'.
1709When the construction involves a function call,
1710like in \verb'@func{...}',
1711the new syntax does not use the \verb'@'.
1712More important, {\em a construction function must now
1713explicitly return the constructed table}.
1714\item
1715The function \verb'lua_call' no longer has the parameter \verb'nparam'.
1716\item
1717The function \verb'lua_pop' is no longer available,
1718since it could lead to strange behavior.
1719In particular,
1720to access results returned from a Lua function,
1721the new macro \verb'lua_getresult' should be used.
1722\item
1723The old functions \verb'lua_storefield' and \verb'lua_storeindexed'
1724have been replaced by
1725\begin{verbatim}
1726int lua_storesubscript (void);
1727\end{verbatim}
1728with the parameters explicitly pushed on the stack.
1729\item
1730The functionality of the function \verb'lua_errorfunction' has been
1731replaced by the {\em fallback} mechanism; \see{error}.
1732\item
1733When calling a function from the Lua library,
1734parameters passed through the stack
1735must be pushed just before the correspondent call,
1736with no intermediate calls to Lua.
1737Special care should be taken with macros like
1738\verb'lua_getindexed' and \verb'lua_getfield'.
1739\end{itemize}
1740
1741\end{document}