From 0a0c9593b846c33781f3adea84a8e9125a747131 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Mon, 30 Mar 1998 15:17:55 -0300 Subject: [PATCH] many small corrections; strings with '\0' --- manual.tex | 413 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 265 insertions(+), 148 deletions(-) diff --git a/manual.tex b/manual.tex index 0084f04d..dde7d737 100644 --- a/manual.tex +++ b/manual.tex @@ -1,4 +1,4 @@ -% $Id: manual.tex,v 1.5 1998/01/13 15:42:43 roberto Exp roberto $ +% $Id: manual.tex,v 1.6 1998/01/14 13:49:44 roberto Exp roberto $ \documentstyle[fullpage,11pt,bnf]{article} @@ -38,7 +38,7 @@ Waldemar Celes \tecgraf\ --- Computer Science Department --- PUC-Rio } -\date{\small \verb$Date: 1998/01/13 15:42:43 $} +\date{\small \verb$Date: 1998/01/14 13:49:44 $} \maketitle @@ -47,21 +47,54 @@ Waldemar Celes \begin{abstract} \noindent -Lua is an extension programming language designed to be used -as a configuration language for any program that needs one. -This document describes version \Version\ of the Lua programming language and -the API that allows interaction between Lua programs and their host C programs. -\end{abstract} +Lua is a programming language originally designed for extending applications, +but also frequently used as a general-purpose, stand-alone language. +Lua combines simple procedural syntax (similar to Pascal) +with powerful data description constructs based on associative +arrays and extensible semantics. +Lua is dynamically typed, interpreted from bytecodes, +and has automatic memory management with garbage collection, +making it ideal for configuration, scripting, and rapid prototyping. +Lua is implemented as a small library of C functions, +written in ANSI C, and compiles unmodified in all known platforms. +The implementation goals are simplicity, efficiency, portability, +and low embedding cost. + +Lua has been developed at TeCGraf, +the Computer Graphics Technology Group of PUC-Rio +(the Pontifical Catholic University of Rio de Janeiro in Brazil). +TeCGraf is a laboratory of the Department of Computer Science. +Dozens of industrial products developed by TeCGraf use Lua. + +This document describes version \Version\ of the Lua programming language +and the API that allows interaction between Lua programs and their +host C programs. +\end{abstract} \vspace{4ex} \begin{quotation} \small \begin{center}{\bf Sum\'ario}\end{center} \vspace{1ex} \noindent -Lua \'e uma linguagem de extens\~ao projetada para ser usada como -linguagem de configura\c{c}\~ao em qualquer programa que precise de -uma. +Lua \'e uma linguagem de programa\c{c}\~ao originalmente projetada para +extens\~ao de aplica\c{c}\~oes, +e que \'e tamb\'em frequentemente usada como uma linguagem de +prop\'osito geral. +Lua combina uma sintaxe procedural simples (similar a Pascal) +com poderosas facilidades para descri\c{c}\~ao de dados baseadas +em tabelas associativas e uma sem\^antica estens\'{\i}vel. +Lua tem tipagem din\^amica, \'e interpretada via bytecodes, +e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo, +tornando-se ideal para configura\c{c}\~ao, scripting, +e prototipagem r\'apida. + +Lua \'e implementada como uma pequena biblioteca de fun\c{c}\~oes C, +escrita em ANSI C, e compila sem modifica\c{c}\~oes em todas as +plataformas conhecidas. +Os objetivos da implementa\c{c}\~ao s\~ao simplicidade, efici\^encia, +portabilidade, e baixo custo. + Este documento descreve a vers\~ao \Version\ da linguagem de programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. @@ -74,7 +107,8 @@ a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. \footnotesize Copyright \copyright\ 1994--1998 TeCGraf, PUC-Rio. Written by Waldemar Celes Filho, -Roberto Ierusalimschy, Luiz Henrique de Figueiredo. +Roberto Ierusalimschy, +and Luiz Henrique de Figueiredo. All rights reserved. % Permission is hereby granted, without written agreement and without license or @@ -170,6 +204,7 @@ A chunk is simply a sequence of statements: \begin{Produc} \produc{chunk}{\rep{stat} \opt{ret}} \end{Produc}% +Statements are described in \See{stats}. (As usual, \rep{\emph{a}} means 0 or more \emph{a}'s, \opt{\emph{a}} means an optional \emph{a} and \oneormore{\emph{a}} means one or more \emph{a}'s.) @@ -203,7 +238,8 @@ whose main property is to be different from any other value. \emph{Number} represents real (floating-point) numbers, while \emph{string} has the usual meaning; notice that Lua is \Index{eight-bit clean}, -so strings can have ISO characters. +and so strings can contain any ISO character, +\emph{including} \verb|'\0'|. The function \verb|type| returns a string describing the type of a given value \see{pdf-type}. @@ -222,7 +258,7 @@ arbitrary \Index{C pointers} to be stored in Lua variables. It corresponds to a \verb|void*| and has no pre-defined operations in Lua, besides assignment and equality test. However, by using \emph{tag methods}, -the programmer may define operations for \emph{userdata} values +the programmer can define operations for \emph{userdata} values \see{tag-method}. The type \emph{table} implements \Index{associative arrays}, @@ -230,6 +266,7 @@ that is, \Index{arrays} that can be indexed not only with numbers, but with any value (except \nil). Therefore, this type may be used not only to represent ordinary arrays, but also symbol tables, sets, records, etc. +Tables are the main data structuring mechanism in Lua. To represent \Index{records}, Lua uses the field name as an index. The language supports this representation by providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. @@ -248,13 +285,15 @@ Moreover, tables must be explicitly created before used \see{tableconstructor}. Tags are mainly used to select tag methods when -some events occur \see{tag-method}. -Each of the types nil, number and string has a different tag. +some events occur. +Tag methods are the main mechanism for extending the +semantics of Lua \see{tag-method}. +Each of the types \M{nil}, \M{number} and \M{string} has a different tag. All values of each of these types have this same pre-defined tag. -Values of type function can have two different tags, +Values of type \M{function} can have two different tags, depending on whether they are Lua or C functions. Finally, -values of type userdata and table can have +values of type \M{userdata} and \M{table} can have as many different tags as needed \see{tag-method}. Tags are created with the function \verb|newtag|, and the function \verb|tag| returns the tag of a given value. @@ -296,7 +335,20 @@ The following strings denote other \Index{tokens}: \Index{Literal strings} can be delimited by matching single or double quotes, and can contain the C-like escape sequences -\verb|'\n'|, \verb|'\t'| and \verb|'\r'|. +\verb|'\a'| (bell), +\verb|'\b'| (back space), +\verb|'\f'| (form feed), +\verb|'\n'| (new line), +\verb|'\r'| (carriage return), +\verb|'\t'| (horizontal tab), +\verb|'\v'| (vertical tab), +\verb|'\\'|, +\verb|'\"'|, +and \verb|'\''|. +A character in a string may also be specified by its numerical value, +through the escape sequence \verb|'\ddd'|, +where \verb|ddd| is a sequence of up to three \emph{decimal} digits. +Strings in Lua may contain any 8-bit value, including 0. Literal strings can also be delimited by matching \verb|[[ ... ]]|. Literals in this bracketed form may run for several lines, may contain nested \verb|[[ ... ]]| pairs, @@ -304,6 +356,15 @@ and do not interpret escape sequences. This form is specially convenient for writing strings that contain program pieces or other quoted strings. +As an example, in a system using ASCII, +the following three literals are equivalent: +\begin{verbatim} +1) "alo\n123\"" +2) '\97lo\10\04923"' +3) [[alo + 123"]] +\end{verbatim} + \Index{Comments} start anywhere outside a string with a double hyphen (\verb|--|) and run until the end of the line. @@ -322,7 +383,7 @@ Examples of valid numerical constants are: \subsection{The \Index{Pre-processor}} \label{pre-processor} All lines that start with a \verb|$| are handled by a pre-processor. -The \verb|$| can be followed by any of the following directives: +The \verb|$| must be immediately followed by one of the following directives: \begin{description} \item[\T{debug}] --- turn on some debugging facilities \see{pragma}. \item[\T{nodebug}] --- turn off some debugging facilities \see{pragma}. @@ -332,11 +393,11 @@ If \M{cond} is false, then this part is skipped by the lexical analyzer. If \M{cond} is true, then this part is skipped by the lexical analyzer. \item[\T{end}] --- ends a conditional part. \item[\T{else}] --- starts an ``else'' conditional part, -switching the ``skip'' status. +flopping the ``skip'' status. \item[\T{endinput}] --- ends the lexical parse of the file. \end{description} -Directives can be freely nested. +Directives may be freely nested. Particularly, a \verb|$endinput| may occur inside a \verb|$if|; in that case, even the matching \verb|$end| is not parsed. @@ -352,7 +413,7 @@ Therefore, actions in a chunk do not affect its own conditional directives. \subsection{\Index{Coercion}} \label{coercion} -Lua provides some automatic conversions between values. +Lua provides some automatic conversions between values at run time. Any arithmetic operation applied to a string tries to convert that string to a number, following the usual rules. Conversely, whenever a number is used when a string is expected, @@ -373,13 +434,15 @@ the system does not know how many values a function will return, or how many parameters it needs. Therefore, sometimes, a list of values must be \emph{adjusted}, at run time, to a given length. -If there are more values than are needed, then the last values are thrown away. -If there are more needs than values, then the list is extended with as -many \nil's as needed. -Adjustment occurs in multiple assignment and function calls. +If there are more values than are needed, +then the last values are thrown away. +If there are more needs than values, +then the list is extended with as many \nil's as needed. +Adjustment occurs in multiple assignment \see{assignment} +and function calls \see{functioncall}. -\subsection{Statements} +\subsection{Statements}\label{stats} Lua supports an almost conventional set of \Index{statements}, similar to those in Pascal or C. @@ -391,7 +454,7 @@ and local variable declarations \see{localvar}. \subsubsection{Blocks} A \Index{block} is a list of statements, which are executed sequentially. -Any statement can be optionally followed by a semicolon: +A statement may be optionally followed by a semicolon: \begin{Produc} \produc{block}{\rep{stat sc} \opt{ret}} \produc{sc}{\opt{\ter{;}}} @@ -404,7 +467,7 @@ A block may be explicitly delimited: \begin{Produc} \produc{stat}{\rwd{do} block \rwd{end}} \end{Produc}% -This is useful to control the scope of local variables. +This is useful to control the scope of local variables \see{localvar}. \subsubsection{\Index{Assignment}} \label{assignment} The language allows \Index{multiple assignment}. @@ -436,8 +499,15 @@ Square brackets are used to index a table: \begin{Produc} \produc{var}{simpleexp \ter{[} exp1 \ter{]}} \end{Produc}% -The \verb|var| should result in a table value, -where the field indexed by the expression value gets the assigned value. +The \M{simpleexp} should result in a table value, +from where the field indexed by the expression +value gets the assigned value. + +The syntax \verb|var.NAME| is just syntactic sugar for +\verb|var["NAME"]|: +\begin{Produc} +\produc{var}{simpleexp \ter{.} name} +\end{Produc}% The meaning of assignments and evaluations of global variables and indexed variables can be changed by tag methods \see{tag-method}. @@ -446,16 +516,10 @@ an assignment \verb|x = val|, where \verb|x| is a global variable, is equivalent to a call \verb|setglobal('x', val)|; an assignment \verb|t[i] = val| is equivalent to \verb|settable_event(t, i, val)|. -See \See{tag-method} for a description of these functions. +See \See{tag-method} for a complete description of these functions. (Function \verb|setglobal| is pre-defined in Lua. Function \T{settable\_event} is used only for explanatory purposes.) -The syntax \verb|var.NAME| is just syntactic sugar for -\verb|var["NAME"]|: -\begin{Produc} -\produc{var}{simpleexp \ter{.} name} -\end{Produc}% - \subsubsection{Control Structures} The \Index{condition expression} of a control structure may return any value. All values different from \nil\ are considered true; @@ -471,7 +535,7 @@ only \nil\ is considered false. \produc{elseif}{\rwd{elseif} exp1 \rwd{then} block} \end{Produc} -A \T{return} is used to return values from a function or a chunk. +A \T{return} is used to return values from a function or from a chunk. \label{return} Because they may return more than one value, the syntax for a \Index{return statement} is: @@ -485,7 +549,7 @@ function calls can be executed as statements: \begin{Produc} \produc{stat}{functioncall} \end{Produc}% -In this case, returned values are thrown away. +In this case, all returned values are thrown away. Function calls are explained in \See{functioncall}. \subsubsection{Local Declarations} \label{localvar} @@ -549,7 +613,7 @@ the binary \verb|+| (addition), \verb|/| (division) and \verb|^| (exponentiation), and unary \verb|-| (negation). If the operands are numbers, or strings that can be converted to -numbers, according to the rules given in \See{coercion}, +numbers (according to the rules given in \See{coercion}), then all operations except exponentiation have the usual meaning. Otherwise, an appropriate tag method is called \see{tag-method}. An exponentiation always calls a tag method. @@ -564,7 +628,7 @@ Lua provides the following \Index{relational operators}: \end{verbatim} All these return \nil\ as false and a value different from \nil\ as true. -Equality first compares the types of its operands. +Equality first compares the tags of its operands. If they are different, then the result is \nil. Otherwise, their values are compared. Numbers and strings are compared in the usual way. @@ -573,22 +637,24 @@ that is, two tables are considered equal only if they are the same table. The operator \verb|~=| is exactly the negation of equality (\verb|==|). Note that the conversion rules of \See{coercion} \emph{do not} apply to equality comparisons. -Thus, \verb|"0"==0| evaluates to false. +Thus, \verb|"0"==0| evaluates to false, +and \verb|t[0]| and \verb|t["0"]| denote different +entries in a table. The other operators work as follows. If both arguments are numbers, then they are compared as such. Otherwise, if both arguments are strings, -their values are compared using lexicographical order. +then their values are compared using lexicographical order. Otherwise, the ``order'' tag method is called \see{tag-method}. \subsubsection{Logical Operators} -Like control structures, all logical operators -consider \nil\ as false and anything else as true. The \Index{logical operators} are: \index{and}\index{or}\index{not} \begin{verbatim} and or not \end{verbatim} +Like control structures, all logical operators +consider \nil\ as false and anything else as true. The operator \verb|and| returns \nil\ if its first argument is \nil; otherwise, it returns its second argument. The operator \verb|or| returns its first argument @@ -646,13 +712,15 @@ For example: \begin{verbatim} a = {"v1", "v2", 34} \end{verbatim} -is essentially equivalent to: +is equivalent to: \begin{verbatim} - temp = {} - temp[1] = "v1" - temp[2] = "v2" - temp[3] = 34 - a = temp + do + local temp = {} + temp[1] = "v1" + temp[2] = "v2" + temp[3] = 34 + a = temp + end \end{verbatim} The form \emph{ffieldlist1} initializes other fields in a table: @@ -664,14 +732,16 @@ For example: \begin{verbatim} a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c} \end{verbatim} -is essentially equivalent to: +is equivalent to: \begin{verbatim} - temp = {} - temp[f(k)] = g(y) - temp.x = 1 -- or temp["x"] = 1 - temp.y = 3 -- or temp["y"] = 3 - temp[0] = b+c - a = temp + do + local temp = {} + temp[f(k)] = g(y) + temp.x = 1 -- or temp["x"] = 1 + temp.y = 3 -- or temp["y"] = 3 + temp[0] = b+c + a = temp + end \end{verbatim} An expression like \verb|{x = 1, y = 4}| is in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. @@ -681,25 +751,28 @@ and can be used in the same constructor separated by a semi-collon. For example, all forms below are correct: \begin{verbatim} - x = {;}; x = {'a', 'b',}; x = {type='list'; 'a', 'b'} + x = {;} + x = {'a', 'b',} + x = {type='list'; 'a', 'b'} x = {f(0), f(1), f(2),; n=3} \end{verbatim} \subsubsection{Function Calls} \label{functioncall} A \Index{function call} has the following syntax: \begin{Produc} -\produc{functioncall}{simpleexp realParams} +\produc{functioncall}{simpleexp args} \end{Produc}% First, \M{simpleexp} is evaluated. If its value has type \emph{function}, -then this function is called. +then this function is called, +with the given arguments. Otherwise, the ``function'' tag method is called, having as first parameter the value of \M{simpleexp}, and then the original call parameters. The form: \begin{Produc} -\produc{functioncall}{simpleexp \ter{:} name realParams} +\produc{functioncall}{simpleexp \ter{:} name args} \end{Produc}% can be used to call ``methods''. A call \verb|simpleexp:name(...)| @@ -710,9 +783,9 @@ is syntactic sugar for except that \verb|simpleexp| is evaluated only once. \begin{Produc} -\produc{realParams}{\ter{(} \opt{explist1} \ter{)}} -\produc{realParams}{tableconstructor} -\produc{realParams}{\ter{literal}} +\produc{args}{\ter{(} \opt{explist1} \ter{)}} +\produc{args}{tableconstructor} +\produc{args}{\ter{literal}} \produc{explist1}{exp1 \rep{\ter{,} exp1}} \end{Produc}% All argument expressions are evaluated before the call. @@ -761,7 +834,7 @@ is just syntactic sugar for: end \end{verbatim} -A function definition is an executable expresion, +A function definition is an executable expression, whose value has type \emph{function}. When Lua pre-compiles a chunk, all its function bodies are pre-compiled, too. @@ -774,7 +847,7 @@ Different instances of a same function may have different upvalues. Parameters act as local variables, -initialized with the argument values. +initialized with the argument values: \begin{Produc} \produc{parlist1}{\ter{\ldots}} \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} @@ -786,8 +859,8 @@ the length of the list of parameters \see{adjust}, unless the function is a \Def{vararg} function, indicated by the dots (\ldots) at the end of its parameter list. A vararg function does not adjust its argument list; -instead, it collects any extra arguments in an implicit parameter, -called \Def{arg}. +instead, it collects any extra arguments into an implicit parameter, +called \IndexVerb{arg}. This parameter is always initialized as a table, with a field \verb|n| with the number of extra arguments, and the extra arguments at positions 1, 2, \ldots @@ -815,7 +888,7 @@ If control reaches the end of a function without a return instruction, then the function returns with no results. There is a special syntax for defining \Index{methods}, -that is, functions that have an extra parameter \Def{self}. +that is, functions that have an extra parameter \IndexVerb{self}. \begin{Produc} \produc{function}{\rwd{function} name \ter{:} name \ter{(} \opt{parlist1} \ter{)} block \rwd{end}} @@ -858,17 +931,17 @@ appears is instantiated. The name used in an upvalue may be the name of any variable visible at the point where the function is defined. -See some examples below: +Here are some examples: \begin{verbatim} a,b,c = 1 -- global variables function f () - local x,b; -- x and b are locals to f + local x,b -- x and b are local to f function g () - local a,y -- a and y are locals go g + local a,y -- a and y are local to g p = a -- OK, access local 'a' p = c -- OK, access global 'c' p = b -- ERROR: cannot access a variable in outer scope - p = %b -- OK, access frozen value of 'b' + p = %b -- OK, access frozen value of 'b' (local to 'f') p = %c -- OK, access frozen value of global 'c' p = %y -- ERROR: 'y' is not visible where 'g' is defined end @@ -881,7 +954,7 @@ end Lua provides a powerful mechanism to extend its semantics, called \Def{Tag Methods}. A tag method (TM) is a programmer-defined function -that can be called at many key points of the evaluation of a program, +that is called at specific key points during the evaluation of a program, allowing a programmer to change the standard Lua behavior at these points. Each of these points is called an \Def{event}. @@ -889,7 +962,7 @@ The tag method called for any specific event is selected according to the tag of the values involved in the event \see{TypesSec}. The function \IndexVerb{settagmethod} changes the tag method -associated with a given pair \M{}. +associated with a given pair \M{(tag, event)}. Its first parameter is the tag, the second the event name (a string, see below), and the third parameter is the new method (a function), @@ -941,7 +1014,7 @@ If it also fails, then it gets a tag method from tag~0: -- call the method with both operands and an extra -- argument with the event name return tm(op1, op2, "add") - else -- no tag method available: Default behavior + else -- no tag method available: default behavior error("unexpected type at arithmetic operation") end end @@ -950,15 +1023,15 @@ If it also fails, then it gets a tag method from tag~0: \item[``sub'':]\index{sub event} called when a \verb|-| operation is applied to non numerical operands. -Behavior similar to \verb|"add"| event. +Behavior similar to the \verb|"add"| event. \item[``mul'':]\index{mul event} called when a \verb|*| operation is applied to non numerical operands. -Behavior similar to \verb|"add"| event. +Behavior similar to the \verb|"add"| event. \item[``div'':]\index{div event} called when a \verb|/| operation is applied to non numerical operands. -Behavior similar to \verb|"add"| event. +Behavior similar to the \verb|"add"| event. \item[``pow'':]\index{pow event} called when a \verb|^| operation is applied. @@ -969,7 +1042,7 @@ called when a \verb|^| operation is applied. -- call the method with both operands and an extra -- argument with the event name return tm(op1, op2, "pow") - else -- no tag method available: Default behavior + else -- no tag method available: default behavior error("unexpected type at arithmetic operation") end end @@ -991,7 +1064,7 @@ called when an unary \verb|-| operation is applied to a non numerical operand. -- call the method with the operand, nil, and an extra -- argument with the event name return tm(op, nil, "unm") - else -- no tag method available: Default behavior + else -- no tag method available: default behavior error("unexpected type at arithmetic operation") end end @@ -1021,17 +1094,17 @@ or non string operands. \item[``gt'':]\index{gt event} called when a \verb|>| operation is applied to non numerical or non string operands. -Behavior similar to \verb|"lt"| event. +Behavior similar to the \verb|"lt"| event. \item[``le'':]\index{le event} called when a \verb|<=| operation is applied to non numerical or non string operands. -Behavior similar to \verb|"lt"| event. +Behavior similar to the \verb|"lt"| event. \item[``ge'':]\index{ge event} called when a \verb|>=| operation is applied to non numerical or non string operands. -Behavior similar to \verb|"lt"| event. +Behavior similar to the \verb|"lt"| event. \item[``concat'':]\index{concatenation event} called when a concatenation is applied to non string operands. @@ -1057,7 +1130,7 @@ not present in a table. See event \verb|"gettable"| for its semantics. \item[``getglobal'':]\index{getglobal event} -called whenever Lua accesses a global variable. +called whenever Lua needs the value of a global variable. This method can only be set for \nil\ and for tags created by \verb|newtag|. \begin{verbatim} @@ -1176,7 +1249,8 @@ Lua does the equivalent of the call \verb|gc_event(nil)|. \subsection{Error Handling} \label{error} Because Lua is an extension language, -all Lua actions start from C code calling a function from the Lua library. +all Lua actions start from C code in the host program +calling a function from the Lua library. Whenever an error occurs during Lua compilation or execution, the \Def{error method} is called, and then the corresponding function from the library @@ -1193,7 +1267,7 @@ which gets the new error handler as its only parameter The standard I/O library uses this facility to redefine the error method, using the debug facilities \see{debugI}, in order to print some extra information, -like the call stack. +such as the call stack. To provide more information about errors, Lua programs should include the compilation pragma \verb|$debug|. @@ -1236,6 +1310,7 @@ This function allocates and initializes some internal structures, and defines all pre-defined functions of Lua. If the library is already opened, this function has no effect. +All standard libraries call \verb|lua_open| when they are opened. If necessary, the library may be closed:\Deffunc{lua_close} \begin{verbatim} @@ -1277,9 +1352,9 @@ and 0 otherwise. The function \verb|lua_isnumber| accepts numbers and numerical strings, whereas \verb|lua_isstring| accepts strings and numbers \see{coercion}, -and \verb|lua_isfunction| accepts Lua and C functions. +and \verb|lua_isfunction| accepts Lua functions and C functions. -To check the tag of a \verb|lua_Object|, +To get the tag of a \verb|lua_Object|, the following function is available: \Deffunc{lua_tag} \begin{verbatim} @@ -1288,11 +1363,12 @@ int lua_tag (lua_Object object); To translate a value from type \verb|lua_Object| to a specific C type, the programmer can use: -\Deffunc{lua_getnumber}\Deffunc{lua_getstring} +\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} \begin{verbatim} -float lua_getnumber (lua_Object object); +double lua_getnumber (lua_Object object); char *lua_getstring (lua_Object object); +long lua_strlen (lua_Object object); lua_CFunction lua_getcfunction (lua_Object object); void *lua_getuserdata (lua_Object object); \end{verbatim} @@ -1306,9 +1382,13 @@ This \verb|lua_Object| must be a string or a number; otherwise, the function returns~0 (the \verb|NULL| pointer). This function does not create a new string, but returns a pointer to a string inside the Lua environment. +Those strings always have a 0 after their last character (like in C), +but may contain other zeros in their body. +If you do not know whether a string may contain zeros, +you can use \verb|lua_strlen| to check the actual length. Because Lua has garbage collection, there is no guarantee that such pointer will be valid after the block ends -(see below). +\see{GC}. \verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. This \verb|lua_Object| must have type \emph{CFunction}; @@ -1319,6 +1399,7 @@ The type \verb|lua_CFunction| is explained in \See{LuacallC}. This \verb|lua_Object| must have type \emph{userdata}; otherwise, the function returns 0 (the \verb|NULL| pointer). +\subsection{Garbage Collection}\label{GC} Because Lua has automatic memory management and garbage collection, a \verb|lua_Object| has a limited scope, and is only valid inside the \emph{block} where it has been created. @@ -1335,7 +1416,7 @@ long lua_collectgarbage (long limit); \end{verbatim} This function returns the number of objects collected. The argument \verb|limit| makes the next cycle occur only -when that number of new objects have been created. +after that number of new objects have been created. If \verb|limit|=0, then Lua uses an adaptable heuristics to set this limit. @@ -1343,15 +1424,15 @@ All communication between Lua and C is done through two abstract data types, called \Def{lua2C} and \Def{C2lua}. The first one, as the name implies, is used to pass values from Lua to C: -Parameters when Lua calls C and results when C calls Lua. +parameters when Lua calls C and results when C calls Lua. The structure C2lua is used in the reverse direction: -Parameters when C calls Lua and results when Lua calls C. +parameters when C calls Lua and results when Lua calls C. The structure lua2C is an abstract array, which can be indexed with the function: \Deffunc{lua_lua2C} \begin{verbatim} -lua_Object lua_lua2C (int number); +lua_Object lua_lua2C (int number); \end{verbatim} where \verb|number| starts with 1. When called with a number larger than the array size, @@ -1361,15 +1442,16 @@ a variable number of parameters, and to call Lua functions that return a variable number of results. Notice that the structure lua2C cannot be directly modified by C code. -The second structure, C2lua, is a stack. +The second structure, C2lua, is an abstract stack. Pushing elements into this stack is done with the following functions and macros: -\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring} +\Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} \Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} \Deffunc{lua_pushnil}\Deffunc{lua_pushobject} \Deffunc{lua_pushuserdata}\label{pushing} \begin{verbatim} void lua_pushnumber (double n); +void lua_pushlstring (char *s, long len); void lua_pushstring (char *s); void lua_pushusertag (void *u, int tag); void lua_pushnil (void); @@ -1379,6 +1461,11 @@ void lua_pushcfunction (lua_CFunction f); /* macro */ All of them receive a C value, convert it to a corresponding \verb|lua_Object|, and leave the result on the top of C2lua. +Particularly, functions \verb|lua_pushlstring| and \verb|lua_pushstring| +make an internal copy of the given string. +Function \verb|lua_pushstring| can only be used to push proper C strings +(that is, strings which do not contain zeros and end with a zero); +otherwise you can use the more generic \verb|lua_pushlstring|. The function \Deffunc{lua_pop} \begin{verbatim} @@ -1398,9 +1485,9 @@ Otherwise, a new userdata is created, with the given value and tag. If this function is called with \verb|tag|=\verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG}, then Lua will try to find any userdata with the given value, -no matter its tag. +regardless of its tag. If there is no userdata with that value, then a new one is created, -with tag=0. +with tag equals to 0. Userdata can have different tags, whose semantics are only known to the host program. @@ -1533,7 +1620,6 @@ Functions defined in Lua by a chunk executed with This is done using the following protocol: first, the arguments to the function are pushed onto C2lua \see{pushing}, in direct order, i.e., the first argument is pushed first. - Then, the function is called using \Deffunc{lua_callfunction} \begin{verbatim} @@ -1558,7 +1644,7 @@ equivalent to the Lua code: lua_pushstring("how"); /* 1st argument */ lua_pushobject(lua_getglobal("t")); /* push value of global 't' */ lua_pushstring("x"); /* push the string 'x' */ - lua_pushobject(lua_gettable()); /* push result of t.x (= t['x']) */ + lua_pushobject(lua_gettable()); /* push result of t.x (2nd arg) */ lua_pushnumber(4); /* 3th argument */ lua_callfunction(lua_getglobal("f")); /* call Lua function */ lua_pushobject(lua_getresult(1)); /* push first result of the call */ @@ -1639,7 +1725,7 @@ which defines the way parameters and results are passed. A C function receives its arguments in structure lua2C; to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} -again just another name to \verb|lua_lua2C|. +again just another name for \verb|lua_lua2C|. To return values, a C function just pushes them onto the stack C2lua, in direct order \see{valuesCLua}. Like a Lua function, a C function called by Lua can also return @@ -1666,11 +1752,11 @@ these upvalues are inserted as the first arguments to the function, before the actual arguments provided in the call. For some examples of C functions, see files \verb|lstrlib.c|, -\verb|liolib.c| and \verb|lmathlib.c| in Lua distribution. +\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. \subsection{References to Lua Objects} -As noted in \See{LuacallC}, \verb|lua_Object|s are volatile. +As noted in \See{GC}, \verb|lua_Object|s are volatile. If the C code needs to keep a \verb|lua_Object| outside block boundaries, then it must create a \Def{reference} to the object. @@ -1695,7 +1781,7 @@ if the object has been collected, \verb|lua_getref| returns \verb|LUA_NOOBJECT|. When a reference is no longer needed, -it can be freed with a call to \verb|lua_unref|. +it can be released with a call to \verb|lua_unref|. @@ -1740,7 +1826,7 @@ then Lua stops getting arguments at the first nil value. By default, all results from \verb|func| are just returned by the call. -If the string \verb|mode| contains \verb|p|, +If the string \verb|mode| contains \verb|"p"|, the results are \emph{packed} in a single table.\index{packed results} That is, \verb|call| returns just one table; at index \verb|n|, the table has the total number of results @@ -1748,8 +1834,8 @@ from the call; the first result is at index 1, etc. For instance, the following calls produce the following results: \begin{verbatim} -a = call(sin, {5}) --> a = 0.0871557 = sin(5) -a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) +a = call(sin, {5}) --> a = 0.0871557 = sin(5) +a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) t = {x=1} a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} \end{verbatim} @@ -1757,7 +1843,7 @@ a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} By default, if an error occurs during the function call, the error is propagated. -If the string \verb|mode| contains \verb|x|, +If the string \verb|mode| contains \verb|"x"|, then the call is \emph{protected}.\index{protected calls} In this mode, function \verb|call| does not generate an error, whatever happens during the call. @@ -1773,7 +1859,7 @@ no error messages will be issued during the execution of the called function. Forces a garbage collection cycle. Returns the number of objects collected. An optional argument, \verb|limit|, is a number that -makes the next cycle occur when that number of new +makes the next cycle occur only after that number of new objects have been created. If absent, Lua uses an adaptable algorithm to set this limit. @@ -1782,10 +1868,10 @@ the API function \verb|lua_collectgarbage|. \subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile} This function receives a file name, -opens it, and executes its contents as a Lua chunk, +opens the file, and executes the file contents as a Lua chunk, or as pre-compiled chunks. When called without arguments, -it executes the contents of the standard input (\verb|stdin|). +\verb|dofile| executes the contents of the standard input (\verb|stdin|). If there is any error executing the file, then \verb|dofile| returns \nil. Otherwise, it returns the values returned by the chunk, @@ -1843,12 +1929,12 @@ otherwise the semantics of \verb|nextvar| is undefined. This function cannot be written with the standard API. \subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} -Executes \verb|function| over all elements of \verb|table|. +Executes the given \verb|function| over all elements of \verb|table|. For each element, the function is called with the index and respective value as arguments. If the function returns any non-nil value, the loop is broken, and the value is returned -as the final value of |verb|foreach|. +as the final value of \verb|foreach|. This function could be defined in Lua: \begin{verbatim} @@ -1868,7 +1954,7 @@ For each variable, the function is called with its name and its value as arguments. If the function returns any non-nil value, the loop is broken, and the value is returned -as the final value of |verb|foreachvar|. +as the final value of \verb|foreachvar|. This function could be defined in Lua: \begin{verbatim} @@ -1908,7 +1994,7 @@ represents 10, `B' represents 11, and so forth, with `Z' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part \see{coercion}. -In other bases only integer numbers are accepted. +In other bases only integers are accepted. \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} This function allows Lua to test the type of a value. @@ -1930,14 +2016,15 @@ It receives one argument, and returns its tag (a number). This function sets the tag of a given table \see{TypesSec}. \verb|tag| must be a value created with \verb|newtag| \see{pdf-newtag}. +It returns the value of its first argument (the table). For security reasons, it is impossible to change the tag of a userdata from Lua. + \subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert} This function issues an \emph{``assertion failed!''} error when its argument is \nil. - -This function could be defined in Lua: +This function is equivalent to the following Lua function: \begin{verbatim} function assert (v, m) if not v then @@ -1978,10 +2065,15 @@ this function can set global variables with strange names like \verb|"m v 1"| or \verb|34|. It returns the value of its second argument. +The string \verb|name| does not need to be a +syntactically valid variable name. + \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} This function assigns the given value to a global variable, or calls a tag method. Its full semantics is explained in \See{tag-method}. +The string \verb|name| does not need to be a +syntactically valid variable name. \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} This function retrieves the value of a global variable. @@ -1993,6 +2085,9 @@ This function retrieves the value of a global variable, or calls a tag method. Its full semantics is explained in \See{tag-method}. +The string \verb|name| does not need to be a +syntactically valid variable name. + \subsubsection*{\ff \T{seterrormethod (newmethod)}} \label{pdf-seterrormethod} Sets the error handler \see{error}. @@ -2002,7 +2097,7 @@ Returns the old error handler. \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} \Deffunc{settagmethod} -This function sets a new tag method to the given pair \M{}. +This function sets a new tag method to the given pair \M{(tag, event)}. It returns the old method. If \verb|newmethod| is \nil, it restores the default behavior for the given event. @@ -2010,7 +2105,7 @@ it restores the default behavior for the given event. \subsubsection*{\ff \T{gettagmethod (tag, event)}} \Deffunc{gettagmethod} This function returns the current tag method -for a given pair \M{}. +for a given pair \M{(tag, event)}. \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} \Deffunc{copytagmethods} @@ -2022,7 +2117,7 @@ it returns \verb|tagto|. This library provides generic functions for string manipulation, such as finding and extracting substrings and pattern matching. When indexing a string, the first character is at position~1 -(not~0, as in C). +(not at~0, as in C). \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} \Deffunc{strfind} @@ -2035,6 +2130,10 @@ If the pattern specifies captures, the captured strings are returned as extra results. A third optional numerical argument specifies where to start the search; its default value is 1. +If \verb|init| is negative, +it is replaced by the length of the string minus its +absolute value plus 1. +Therefore, \M{-1} points to the last character of \verb|str|. A value of 1 as a fourth optional argument turns off the pattern matching facilities, so the function does a plain ``find substring'' operation, @@ -2049,9 +2148,9 @@ starting at \verb|i| and running until \verb|j|. If \verb|i| or \verb|j| are negative, they are replaced by the length of the string minus their absolute value plus 1. -Therefore, -1 points to the last character of \verb|s| -and -2 to the previous one. -If \verb|j| is absent, it is assumed to be equal to -1 +Therefore, \M{-1} points to the last character of \verb|s| +and \M{-2} to the previous one. +If \verb|j| is absent, it is assumed to be equal to \M{-1} (which is the same as the string length). In particular, the call \verb|strsub(s,1,j)| returns a prefix of \verb|s| @@ -2063,19 +2162,33 @@ with length \verb|i|. Receives a string and returns a copy of that string with all upper case letters changed to lower case. All other characters are left unchanged. +The definition of what is an upper case +letter depends on the current locale. \subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper} Receives a string and returns a copy of that string with all lower case letters changed to upper case. All other characters are left unchanged. +The definition of what is a lower case +letter depends on the current locale. \subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep} -Returns a string which is the concatenation of \verb|n| copies of +Returns a string that is the concatenation of \verb|n| copies of the string \verb|s|. \subsubsection*{\ff \T{ascii (s [, i])}}\Deffunc{ascii} -Returns the ASCII code of the character \verb|s[i]|. +Returns the internal numerical code of the character \verb|s[i]|. If \verb|i| is absent, then it is assumed to be 1. +If \verb|i| is negative, +it is replaced by the length of the string minus its +absolute value plus 1. +Therefore, \M{-1} points to the last character of \verb|s|. + +\subsubsection*{\ff \T{int2str (i1, i2, \ldots)}}\Deffunc{int2str} +Receives 0 or more integers. +Returns a string with length equal to the number of arguments, +wherein each character has ascii value equal +to its correspondent argument. \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format} \label{format} @@ -2122,6 +2235,9 @@ the appropriate format string. For example, \verb|"%*g"| can be simulated with \verb|"%"..width.."g"|. +\emph{Function \verb|format| can only be used with strings that do not +contain zeros.} + \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} \Deffunc{gsub} Returns a copy of \verb|s|, @@ -2137,7 +2253,7 @@ stands for the value of the n-th captured substring. If \verb|repl| is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, -in order (see below); +in order (see below). If the value returned by this function is a string, then it is used as the replacement string; otherwise, the replacement string is the empty string. @@ -2213,7 +2329,7 @@ represents the complement of char-set, where char-set is interpreted as above. \end{description} -The definitions of letter, space, etc depend on the current locale. +The definitions of letter, space, etc. depend on the current locale. In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. The second form should be preferred for more portable programs. @@ -2283,8 +2399,8 @@ The library provides the following functions: \Deffunc{mod}\Deffunc{sin}\Deffunc{sqrt}\Deffunc{tan} \Deffunc{random}\Deffunc{randomseed} \begin{verbatim} -abs acos asin atan atan2 ceil cos floor log log10 -max min mod sin sqrt tan random randomseed +abs acos asin atan atan2 ceil cos deg floor log log10 +max min mod rad sin sqrt tan random randomseed \end{verbatim} plus a global variable \IndexVerb{PI}. Most of them @@ -2297,7 +2413,7 @@ between radians and degrees. The function \verb|max| returns the maximum value of its numeric arguments. Similarly, \verb|min| computes the minimum. -Both can be used with an unlimited number of arguments. +Both can be used with 1, 2 or more arguments. The functions \verb|random| and \verb|randomseed| are interfaces to the simple random generator functions \verb|rand| and \verb|srand|, @@ -2305,7 +2421,7 @@ provided by ANSI C. The function \verb|random|, when called without arguments, returns a pseudo-random real number in the range \Math{[0,1)}. When called with a number \Math{n}, -returns a pseudo-random integer in the range \Math{[1,n]}. +\verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. \subsection{I/O Facilities} \label{libio} @@ -2347,7 +2463,7 @@ plus a string describing the error. \begin{quotation} \noindent \emph{System dependent}: if \verb|filename| starts with a \verb-|-, -then a \Index{piped input} is open, via function \IndexVerb{popen}. +then a \Index{piped input} is opened, via function \IndexVerb{popen}. Not all systems implement pipes. Moreover, the number of files that can be open at the same time is @@ -2375,7 +2491,7 @@ plus a string describing the error. \begin{quotation} \noindent \emph{System dependent}: if \verb|filename| starts with a \verb-|-, -then a \Index{piped output} is open, via function \IndexVerb{popen}. +then a \Index{piped output} is opened, via function \IndexVerb{popen}. Not all systems implement pipes. Moreover, the number of files that can be open at the same time is @@ -2391,7 +2507,8 @@ this function does not erase any previous content of the file. If this function fails, it returns \nil, plus a string describing the error. -Notice that function \verb|writeto| is available to close an output file. +Notice that function \verb|writeto| is +available to close an output file opened by \verb|appendto|. \subsubsection*{\ff \T{remove (filename)}}\Deffunc{remove} @@ -2557,13 +2674,13 @@ given function has been defined. If the ``function'' is in fact the main code of a chunk, then \verb|linedefined| is 0. If the function is a C function, -then \verb|linedefined| is -1, and \verb|filename| is \verb|"(C)"|. +then \verb|linedefined| is \M{-1}, and \verb|filename| is \verb|"(C)"|. The function \verb|lua_currentline| gives the current line where a given function is executing. It only works if the function has been compiled with debug information \see{pragma}. -When no line information is available, it returns -1. +When no line information is available, it returns \M{-1}. Function \verb|lua_getobjname| tries to find a reasonable name for a given function. @@ -2661,12 +2778,12 @@ accepting commands from standard input until an \verb|EOF|. Each line entered is immediately executed. \item[\T{-q}] same as \T{-i}, but without a prompt (quiet mode). \item[\T{-}] executes \verb|stdin| as a file. -\item[\T{var=value}] sets global \verb|var| with string \verb|value|. +\item[\T{var=value}] sets global \verb|var| with string \verb|"value"|. \item[\T{filename}] executes file \verb|filename| as a Lua chunk. \end{description} When called without arguments, Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, -and \verb|lua -| otherwise. +and as \verb|lua -| otherwise. All arguments are handled in order. For instance, an invocation like @@ -2675,13 +2792,13 @@ $ lua -i a=test prog.lua \end{verbatim} will first interact with the user until an \verb|EOF|, then will set \verb|a| to \verb|"test"|, -and finally will run file \verb|prog.lua|. +and finally will run the file \verb|prog.lua|. When in interactive mode, a multi-line statement can be written finishing intermediate lines with a backslash (\verb|\|). The prompt presented is the value of the global variable \verb|_PROMPT|. -For instance, the prompt can be changed like below: +Therefore, the prompt can be changed like below: \begin{verbatim} $ lua _PROMPT='myprompt> ' -i \end{verbatim} @@ -2712,8 +2829,8 @@ Here is a list of all these incompatibilities. \item To support multiple contexts, Lua 3.1 must be explicitly opened before used. However, all standard libraries check whether Lua is already opened, -so any program that opens at least one standard library before using -Lua API does not need to be modified. +so any program that opens at least one standard library before calling +Lua does not need to be modified. \item Function \verb|dostring| no longer accepts an optional second argument, with a temporary error method. @@ -2725,9 +2842,9 @@ Closures replace this feature with advantage. \item The syntax for function declaration is now more restricted; for instance, the old syntax \verb|function f[exp] (x) ... end| is not -accepted in 3.1. +accepted in Lua 3.1. In these cases, -programs should use an explicit assignment instead, like +programs should use an explicit assignment instead, such as \verb|f[exp] = function (x) ... end|. \item Old pre-compiled code is obsolete, and must be re-compiled.