diff options
| -rw-r--r-- | manual.tex | 1840 |
1 files changed, 1088 insertions, 752 deletions
| @@ -1,21 +1,23 @@ | |||
| 1 | % $Id: manual.tex,v 1.35 2000/04/14 17:47:55 roberto Exp roberto $ | 1 | % $Id: manual.tex,v 1.36 2000/04/17 19:23:48 roberto Exp roberto $ |
| 2 | 2 | ||
| 3 | \documentclass[11pt]{article} | 3 | \documentclass[11pt]{article} |
| 4 | \usepackage{fullpage,bnf} | 4 | \usepackage{fullpage,bnf} |
| 5 | \usepackage{graphicx} | ||
| 6 | %\usepackage{times} | ||
| 5 | 7 | ||
| 6 | \catcode`\_=12 | 8 | \catcode`\_=12 |
| 7 | 9 | ||
| 8 | \newcommand{\See}[1]{Section~\ref{#1}} | 10 | \newcommand{\See}[1]{Section~\ref{#1}} |
| 9 | \newcommand{\see}[1]{(see \See{#1})} | 11 | \newcommand{\see}[1]{(see \See{#1})} |
| 10 | \newcommand{\M}[1]{\emph{#1}} | 12 | \newcommand{\M}[1]{\rm\emph{#1}} |
| 11 | \newcommand{\T}[1]{{\tt #1}} | 13 | \newcommand{\T}[1]{{\tt #1}} |
| 12 | \newcommand{\Math}[1]{$#1$} | 14 | \newcommand{\Math}[1]{$#1$} |
| 13 | \newcommand{\nil}{{\bf nil}} | 15 | \newcommand{\nil}{{\bf nil}} |
| 14 | \newcommand{\Line}{\rule{\linewidth}{.5mm}} | ||
| 15 | \def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} | 16 | \def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} |
| 16 | 17 | ||
| 17 | \newcommand{\Index}[1]{#1\index{#1}} | 18 | \newcommand{\Index}[1]{#1\index{#1}} |
| 18 | \newcommand{\IndexVerb}[1]{\T{#1}\index{#1}} | 19 | \newcommand{\IndexVerb}[1]{\T{#1}\index{#1}} |
| 20 | \newcommand{\IndexEmph}[1]{\emph{#1}\index{#1}} | ||
| 19 | \newcommand{\Def}[1]{\emph{#1}\index{#1}} | 21 | \newcommand{\Def}[1]{\emph{#1}\index{#1}} |
| 20 | \newcommand{\Deffunc}[1]{\index{#1}} | 22 | \newcommand{\Deffunc}[1]{\index{#1}} |
| 21 | 23 | ||
| @@ -23,75 +25,46 @@ | |||
| 23 | 25 | ||
| 24 | \newcommand{\Version}{4.0} | 26 | \newcommand{\Version}{4.0} |
| 25 | 27 | ||
| 28 | % LHF | ||
| 29 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} | ||
| 30 | \newcommand{\NOTE}{\par\noindent\emph{NOTE}: } | ||
| 31 | |||
| 26 | \makeindex | 32 | \makeindex |
| 27 | 33 | ||
| 28 | \begin{document} | 34 | \begin{document} |
| 29 | 35 | ||
| 30 | \title{Reference Manual of the Programming Language Lua \Version} | 36 | %{=============================================================== |
| 31 | |||
| 32 | \author{% | ||
| 33 | Roberto Ierusalimschy\quad | ||
| 34 | Luiz Henrique de Figueiredo\quad | ||
| 35 | Waldemar Celes | ||
| 36 | \vspace{1.0ex}\\ | ||
| 37 | \smallskip | ||
| 38 | \small\tt lua@tecgraf.puc-rio.br | ||
| 39 | \vspace{2.0ex}\\ | ||
| 40 | %MCC 08/95 --- | ||
| 41 | \tecgraf\ --- Computer Science Department --- PUC-Rio | ||
| 42 | } | ||
| 43 | |||
| 44 | \date{{\small \tt\$Date: 2000/04/14 17:47:55 $ $}} | ||
| 45 | |||
| 46 | \maketitle | ||
| 47 | |||
| 48 | \thispagestyle{empty} | 37 | \thispagestyle{empty} |
| 49 | \pagestyle{empty} | 38 | \pagestyle{empty} |
| 50 | 39 | ||
| 51 | \begin{abstract} | 40 | { |
| 52 | \noindent | 41 | \parindent=0pt |
| 53 | Lua is a programming language originally designed for extending applications, | 42 | \vglue1.5in |
| 54 | but also frequently used as a general-purpose, stand-alone language. | 43 | {\LARGE\bf |
| 55 | Lua combines simple procedural syntax (similar to Pascal) | 44 | The Programming Language Lua} |
| 56 | with powerful data description constructs based on associative | 45 | \hfill |
| 57 | arrays and extensible semantics. | 46 | \vskip4pt \hrule height 4pt width \hsize \vskip4pt |
| 58 | Lua is dynamically typed, interpreted from opcodes, | 47 | \hfill |
| 59 | and has automatic memory management with garbage collection, | 48 | Reference Manual for Lua version \Version |
| 60 | making it ideal for configuration, scripting, and rapid prototyping. | 49 | \\ |
| 61 | 50 | \null | |
| 62 | This document describes version \Version\ of the Lua programming language | 51 | \hfill |
| 63 | and the API that allows interaction between Lua programs and their | 52 | Last revised on \today |
| 64 | host C programs. | 53 | \\ |
| 65 | \end{abstract} | 54 | \vfill |
| 66 | \vspace{4ex} | 55 | \centering |
| 67 | \begin{quotation} | 56 | \includegraphics[width=0.7\textwidth]{nolabel.ps} |
| 68 | \small | 57 | \vfill |
| 69 | \begin{center}{\bf Sum\'ario}\end{center} | 58 | \vskip4pt \hrule height 2pt width \hsize |
| 70 | \vspace{1ex} | 59 | } |
| 71 | \noindent | ||
| 72 | Lua \'e uma linguagem de programa\c{c}\~ao originalmente projetada para | ||
| 73 | extens\~ao de aplica\c{c}\~oes, | ||
| 74 | e que \'e tamb\'em frequentemente usada como uma linguagem de | ||
| 75 | prop\'osito geral. | ||
| 76 | Lua combina uma sintaxe procedural simples (similar a Pascal) | ||
| 77 | com poderosas facilidades para descri\c{c}\~ao de dados baseadas | ||
| 78 | em tabelas associativas e uma sem\^antica estens\'{\i}vel. | ||
| 79 | Lua tem tipagem din\^amica, \'e interpretada via opcodes, | ||
| 80 | e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo, | ||
| 81 | tornando-se ideal para configura\c{c}\~ao, scripting, | ||
| 82 | e prototipagem r\'apida. | ||
| 83 | |||
| 84 | Este documento descreve a vers\~ao \Version\ da linguagem de | ||
| 85 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite | ||
| 86 | a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | ||
| 87 | \end{quotation} | ||
| 88 | |||
| 89 | 60 | ||
| 90 | \newpage | 61 | \newpage |
| 91 | \begin{quotation} | 62 | \begin{quotation} |
| 92 | \parskip=10pt | 63 | \parskip=10pt |
| 93 | \noindent | ||
| 94 | \footnotesize | 64 | \footnotesize |
| 65 | \null\vfill | ||
| 66 | |||
| 67 | \noindent | ||
| 95 | Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved. | 68 | Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved. |
| 96 | 69 | ||
| 97 | \noindent | 70 | \noindent |
| @@ -127,10 +100,89 @@ Figueiredo at TeCGraf, PUC-Rio. | |||
| 127 | 100 | ||
| 128 | \noindent | 101 | \noindent |
| 129 | This implementation contains no third-party code. | 102 | This implementation contains no third-party code. |
| 130 | \end{quotation} | ||
| 131 | 103 | ||
| 104 | \noindent | ||
| 105 | Copies of this manual can be obtained at | ||
| 106 | \verb|http://www.tecgraf.puc-rio.br/lua/|. | ||
| 107 | \end{quotation} | ||
| 108 | %}=============================================================== | ||
| 132 | \newpage | 109 | \newpage |
| 133 | 110 | ||
| 111 | \title{Reference Manual of the Programming Language Lua \Version} | ||
| 112 | |||
| 113 | \author{% | ||
| 114 | Roberto Ierusalimschy\quad | ||
| 115 | Luiz Henrique de Figueiredo\quad | ||
| 116 | Waldemar Celes | ||
| 117 | \vspace{1.0ex}\\ | ||
| 118 | \smallskip | ||
| 119 | \small\tt lua@tecgraf.puc-rio.br | ||
| 120 | \vspace{2.0ex}\\ | ||
| 121 | %MCC 08/95 --- | ||
| 122 | \tecgraf\ --- Computer Science Department --- PUC-Rio | ||
| 123 | } | ||
| 124 | |||
| 125 | \date{{\small \tt\$Date: 2000/04/17 19:23:48 $ $}} | ||
| 126 | |||
| 127 | \maketitle | ||
| 128 | |||
| 129 | \thispagestyle{empty} | ||
| 130 | \pagestyle{empty} | ||
| 131 | |||
| 132 | \begin{abstract} | ||
| 133 | \noindent | ||
| 134 | Lua is a powerful, light-weight programming language | ||
| 135 | designed for extending applications. | ||
| 136 | Lua is also frequently used as a general-purpose, stand-alone language. | ||
| 137 | Lua combines simple procedural syntax | ||
| 138 | (similar to Pascal) | ||
| 139 | with | ||
| 140 | powerful data description constructs | ||
| 141 | based on associative arrays and extensible semantics. | ||
| 142 | Lua is | ||
| 143 | dynamically typed, | ||
| 144 | interpreted from bytecodes, | ||
| 145 | and has automatic memory management with garbage collection, | ||
| 146 | making it ideal for | ||
| 147 | configuration, | ||
| 148 | scripting, | ||
| 149 | and | ||
| 150 | rapid prototyping. | ||
| 151 | |||
| 152 | This document describes version \Version\ of the Lua programming language | ||
| 153 | and the API that allows interaction between Lua programs and their | ||
| 154 | host C programs. | ||
| 155 | \end{abstract} | ||
| 156 | |||
| 157 | \def\abstractname{Resumo} | ||
| 158 | \begin{abstract} | ||
| 159 | \noindent | ||
| 160 | Lua \'e uma linguagem de programa\c{c}\~ao | ||
| 161 | poderosa e leve, | ||
| 162 | projetada para extender aplica\c{c}\~oes. | ||
| 163 | Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral. | ||
| 164 | Lua combina programa\c{c}\~ao procedural | ||
| 165 | (com sintaxe semelhante \`a de Pascal) | ||
| 166 | com | ||
| 167 | poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados, | ||
| 168 | baseadas em tabelas associativas e sem\^antica extens\'\i vel. | ||
| 169 | Lua \'e | ||
| 170 | tipada dinamicamente, | ||
| 171 | interpretada a partir de \emph{bytecodes}, | ||
| 172 | e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo. | ||
| 173 | Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para | ||
| 174 | configura\c{c}\~ao, | ||
| 175 | automa\c{c}\~ao (\emph{scripting}) | ||
| 176 | e prototipagem r\'apida. | ||
| 177 | |||
| 178 | Este documento descreve a vers\~ao \Version\ da linguagem de | ||
| 179 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite | ||
| 180 | a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | ||
| 181 | \end{abstract} | ||
| 182 | |||
| 183 | \newpage | ||
| 184 | \null | ||
| 185 | \newpage | ||
| 134 | \tableofcontents | 186 | \tableofcontents |
| 135 | 187 | ||
| 136 | \newpage | 188 | \newpage |
| @@ -143,7 +195,7 @@ This implementation contains no third-party code. | |||
| 143 | Lua is an extension programming language designed to support | 195 | Lua is an extension programming language designed to support |
| 144 | general procedural programming with data description | 196 | general procedural programming with data description |
| 145 | facilities. | 197 | facilities. |
| 146 | Lua is intended to be used as a light-weight, but powerful, | 198 | Lua is intended to be used as a powerful, light-weight |
| 147 | configuration language for any program that needs one. | 199 | configuration language for any program that needs one. |
| 148 | 200 | ||
| 149 | Lua is implemented as a library, written in C. | 201 | Lua is implemented as a library, written in C. |
| @@ -152,8 +204,8 @@ it only works \emph{embedded} in a host client, | |||
| 152 | called the \emph{embedding} program. | 204 | called the \emph{embedding} program. |
| 153 | This host program can invoke functions to execute a piece of | 205 | This host program can invoke functions to execute a piece of |
| 154 | code in Lua, can write and read Lua variables, | 206 | code in Lua, can write and read Lua variables, |
| 155 | and can register C functions to be called by Lua code. | 207 | and can register C~functions to be called by Lua code. |
| 156 | Through the use of C functions, Lua can be augmented to cope with | 208 | Through the use of C~functions, Lua can be augmented to cope with |
| 157 | a wide range of different domains, | 209 | a wide range of different domains, |
| 158 | thus creating customized programming languages sharing a syntactical framework. | 210 | thus creating customized programming languages sharing a syntactical framework. |
| 159 | 211 | ||
| @@ -164,9 +216,28 @@ The implementation described in this manual is available | |||
| 164 | at the following URL's: | 216 | at the following URL's: |
| 165 | \begin{verbatim} | 217 | \begin{verbatim} |
| 166 | http://www.tecgraf.puc-rio.br/lua/ | 218 | http://www.tecgraf.puc-rio.br/lua/ |
| 167 | ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz | 219 | ftp://ftp.tecgraf.puc-rio.br/pub/lua/ |
| 168 | \end{verbatim} | 220 | \end{verbatim} |
| 169 | 221 | ||
| 222 | Like any other reference manual, | ||
| 223 | this document is dry in places. | ||
| 224 | For a discussion of the decisions behind the design of Lua, | ||
| 225 | see the papers below, | ||
| 226 | which are available at the web site above. | ||
| 227 | \begin{itemize} | ||
| 228 | \item | ||
| 229 | R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes. | ||
| 230 | Lua---an extensible extension language. | ||
| 231 | \emph{Software: Practice \& Experience} {\bf 26} \#6 (1996) 635--652. | ||
| 232 | \item | ||
| 233 | L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes. | ||
| 234 | The design and implementation of a language for extending applications. | ||
| 235 | \emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273--283. | ||
| 236 | \item | ||
| 237 | L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes. | ||
| 238 | Lua: an extensible embedded language. | ||
| 239 | \emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33. | ||
| 240 | \end{itemize} | ||
| 170 | 241 | ||
| 171 | \section{Environment and Chunks} | 242 | \section{Environment and Chunks} |
| 172 | 243 | ||
| @@ -177,7 +248,7 @@ is initialized with a call from the embedding program to | |||
| 177 | persists until a call to \verb|lua_close|, | 248 | persists until a call to \verb|lua_close|, |
| 178 | or the end of the embedding program. | 249 | or the end of the embedding program. |
| 179 | Optionally, a user can create multiple independent global | 250 | Optionally, a user can create multiple independent global |
| 180 | environments \see{mangstate}. | 251 | environments, and freely switch between them \see{mangstate}. |
| 181 | 252 | ||
| 182 | The global environment can be manipulated by Lua code or | 253 | The global environment can be manipulated by Lua code or |
| 183 | by the embedding program, | 254 | by the embedding program, |
| @@ -196,16 +267,18 @@ A chunk is simply a sequence of statements: | |||
| 196 | \produc{chunk}{\rep{stat} \opt{ret}} | 267 | \produc{chunk}{\rep{stat} \opt{ret}} |
| 197 | \end{Produc}% | 268 | \end{Produc}% |
| 198 | Statements are described in \See{stats}. | 269 | Statements are described in \See{stats}. |
| 199 | (As usual, \rep{\emph{a}} means 0 or more \emph{a}'s, | 270 | (The notation above is the usual extended BNF, |
| 200 | \opt{\emph{a}} means an optional \emph{a} and \oneormore{\emph{a}} means | 271 | in which |
| 201 | one or more \emph{a}'s.) | 272 | \rep{\emph{a}} means 0 or more \emph{a}'s, |
| 273 | \opt{\emph{a}} means an optional \emph{a}, and | ||
| 274 | \oneormore{\emph{a}} means one or more \emph{a}'s.) | ||
| 202 | 275 | ||
| 203 | A chunk may be in a file or in a string inside the host program. | 276 | A chunk may be in a file or in a string inside the host program. |
| 204 | A chunk may optionally end with a \verb|return| statement \see{return}. | 277 | A chunk may optionally end with a \verb|return| statement \see{return}. |
| 205 | When a chunk is executed, first all its code is pre-compiled, | 278 | When a chunk is executed, first all its code is pre-compiled, |
| 206 | then the statements are executed in sequential order. | 279 | and then the statements are executed in sequential order. |
| 207 | All modifications a chunk effects on the global environment persist | 280 | All modifications a chunk effects on the global environment persist |
| 208 | after the chunk end. | 281 | after the chunk ends. |
| 209 | 282 | ||
| 210 | Chunks may also be pre-compiled into binary form; | 283 | Chunks may also be pre-compiled into binary form; |
| 211 | see program \IndexVerb{luac} for details. | 284 | see program \IndexVerb{luac} for details. |
| @@ -216,11 +289,12 @@ Lua automatically detects the file type and acts accordingly. | |||
| 216 | 289 | ||
| 217 | \section{\Index{Types and Tags}} \label{TypesSec} | 290 | \section{\Index{Types and Tags}} \label{TypesSec} |
| 218 | 291 | ||
| 219 | Lua is a dynamically typed language. | 292 | Lua is a \emph{dynamically typed language}. |
| 220 | Variables do not have types; only values do. | 293 | This means that |
| 294 | variables do not have types; only values do. | ||
| 221 | Therefore, there are no type definitions in the language. | 295 | Therefore, there are no type definitions in the language. |
| 222 | All values carry their own type. | 296 | All values carry their own type. |
| 223 | Besides a type, all values also have a \Index{tag}. | 297 | Besides a type, all values also have a \IndexEmph{tag}. |
| 224 | 298 | ||
| 225 | There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, | 299 | There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, |
| 226 | \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. | 300 | \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. |
| @@ -230,18 +304,18 @@ whose main property is to be different from any other value. | |||
| 230 | while \emph{string} has the usual meaning. | 304 | while \emph{string} has the usual meaning. |
| 231 | Lua is \Index{eight-bit clean}, | 305 | Lua is \Index{eight-bit clean}, |
| 232 | and so strings may contain any 8-bit character, | 306 | and so strings may contain any 8-bit character, |
| 233 | \emph{including} embedded zeros (\verb|'\0'|). | 307 | \emph{including} embedded zeros (\verb|'\0'|) \see{lexical}. |
| 234 | The \verb|type| function returns a string describing the type | 308 | The \verb|type| function returns a string describing the type |
| 235 | of a given value \see{pdf-type}. | 309 | of a given value \see{pdf-type}. |
| 236 | 310 | ||
| 237 | Functions are considered first-class values in Lua. | 311 | Functions are considered \emph{first-class values} in Lua. |
| 238 | This means that functions can be stored in variables, | 312 | This means that functions can be stored in variables, |
| 239 | passed as arguments to other functions, and returned as results. | 313 | passed as arguments to other functions, and returned as results. |
| 240 | Lua can call (and manipulate) functions written in Lua and | 314 | Lua can call (and manipulate) functions written in Lua and |
| 241 | functions written in C. | 315 | functions written in C. |
| 242 | They can be distinguished by their tags: | 316 | The kinds of functions can be distinguished by their tags: |
| 243 | all Lua functions have the same tag, | 317 | all Lua functions have the same tag, |
| 244 | and all C functions have the same tag, | 318 | and all C~functions have the same tag, |
| 245 | which is different from the tag of Lua functions. | 319 | which is different from the tag of Lua functions. |
| 246 | The \verb|tag| function returns the tag | 320 | The \verb|tag| function returns the tag |
| 247 | of a given value \see{pdf-tag}. | 321 | of a given value \see{pdf-tag}. |
| @@ -263,7 +337,7 @@ Tables are the main data structuring mechanism in Lua. | |||
| 263 | To represent \Index{records}, Lua uses the field name as an index. | 337 | To represent \Index{records}, Lua uses the field name as an index. |
| 264 | The language supports this representation by | 338 | The language supports this representation by |
| 265 | providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. | 339 | providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. |
| 266 | Tables may also carry methods: | 340 | Tables may also carry \emph{methods}: |
| 267 | Because functions are first class values, | 341 | Because functions are first class values, |
| 268 | table fields may contain functions. | 342 | table fields may contain functions. |
| 269 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, | 343 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, |
| @@ -281,10 +355,10 @@ Tags are mainly used to select \emph{tag methods} when | |||
| 281 | some events occur. | 355 | some events occur. |
| 282 | Tag methods are the main mechanism for extending the | 356 | Tag methods are the main mechanism for extending the |
| 283 | semantics of Lua \see{tag-method}. | 357 | semantics of Lua \see{tag-method}. |
| 284 | Each of the types \M{nil}, \M{number} and \M{string} has a different tag. | 358 | Each of the types \M{nil}, \M{number}, and \M{string} has a different tag. |
| 285 | All values of each of these types have this same pre-defined tag. | 359 | All values of each of these types have the same pre-defined tag. |
| 286 | Values of type \M{function} can have two different tags, | 360 | Values of type \M{function} can have two different tags, |
| 287 | depending on whether they are Lua functions or C functions. | 361 | depending on whether they are Lua functions or C~functions. |
| 288 | Finally, | 362 | Finally, |
| 289 | values of type \M{userdata} and \M{table} have | 363 | values of type \M{userdata} and \M{table} have |
| 290 | variable tags, assigned by the program \see{tag-method}. | 364 | variable tags, assigned by the program \see{tag-method}. |
| @@ -296,40 +370,42 @@ there is the function \verb|settag| \see{pdf-newtag}. | |||
| 296 | 370 | ||
| 297 | \section{The Language} | 371 | \section{The Language} |
| 298 | 372 | ||
| 299 | This section describes the lexis, the syntax and the semantics of Lua. | 373 | This section describes the lexis, the syntax, and the semantics of Lua. |
| 300 | 374 | ||
| 301 | 375 | ||
| 302 | \subsection{Lexical Conventions} \label{lexical} | 376 | \subsection{Lexical Conventions} \label{lexical} |
| 303 | 377 | ||
| 304 | \Index{Identifiers} in Lua can be any string of letters, | 378 | \IndexEmph{Identifiers} in Lua can be any string of letters, |
| 305 | digits, and underscores, | 379 | digits, and underscores, |
| 306 | not beginning with a digit. | 380 | not beginning with a digit. |
| 307 | The definition of letter depends on the current locale: | 381 | This coincides with the definition of identifiers in most languages, |
| 382 | except that | ||
| 383 | the definition of letter depends on the current locale: | ||
| 308 | Any character considered alphabetic by the current locale | 384 | Any character considered alphabetic by the current locale |
| 309 | can be used in an identifier. | 385 | can be used in an identifier. |
| 310 | The following words are reserved, and cannot be used as identifiers: | 386 | The following words are \emph{reserved}, and cannot be used as identifiers: |
| 311 | \index{reserved words} | 387 | \index{reserved words} |
| 312 | \begin{verbatim} | 388 | \begin{verbatim} |
| 313 | and break do else | 389 | and break do else |
| 314 | elseif end for function | 390 | elseif end for function |
| 315 | if local nil not | 391 | if local nil not |
| 316 | or repeat return then | 392 | or repeat return then |
| 317 | until while | 393 | until while |
| 318 | \end{verbatim} | 394 | \end{verbatim} |
| 319 | Lua is a case-sensitive language: | 395 | Lua is a case-sensitive language: |
| 320 | \T{and} is a reserved word, but \T{And} and \T{\'and} | 396 | \T{and} is a reserved word, but \T{And} and \T{\'and} |
| 321 | (if the locale permits) are two other different identifiers. | 397 | (if the locale permits) are two different, valid identifiers. |
| 322 | As a convention, identifiers starting with underscore followed by | 398 | As a convention, identifiers starting with underscore followed by |
| 323 | uppercase letters (such as \verb|_INPUT|) | 399 | uppercase letters (such as \verb|_INPUT|) |
| 324 | are reserved for internal variables. | 400 | are reserved for internal variables. |
| 325 | 401 | ||
| 326 | The following strings denote other \Index{tokens}: | 402 | The following strings denote other \Index{tokens}: |
| 327 | \begin{verbatim} | 403 | \begin{verbatim} |
| 328 | ~= <= >= < > == = + - * / % | 404 | ~= <= >= < > == = + - * / % |
| 329 | ( ) { } [ ] ; , . .. ... | 405 | ( ) { } [ ] ; , . .. ... |
| 330 | \end{verbatim} | 406 | \end{verbatim} |
| 331 | 407 | ||
| 332 | \Index{Literal strings} can be delimited by matching single or double quotes, | 408 | \IndexEmph{Literal strings} can be delimited by matching single or double quotes, |
| 333 | and can contain the C-like escape sequences | 409 | and can contain the C-like escape sequences |
| 334 | \verb|'\a'| (bell), | 410 | \verb|'\a'| (bell), |
| 335 | \verb|'\b'| (backspace), | 411 | \verb|'\b'| (backspace), |
| @@ -341,14 +417,15 @@ and can contain the C-like escape sequences | |||
| 341 | \verb|'\\'|, (backslash), | 417 | \verb|'\\'|, (backslash), |
| 342 | \verb|'\"'|, (double quote), | 418 | \verb|'\"'|, (double quote), |
| 343 | \verb|'\''| (single quote), | 419 | \verb|'\''| (single quote), |
| 344 | and \verb|'\\n'| (that is, a backslash followed by a real newline, | 420 | and \verb|'\|\emph{newline}\verb|'| (that is, a backslash followed by a real newline, |
| 345 | which results in a newline in the string). | 421 | which results in a newline in the string). |
| 346 | A character in a string may also be specified by its numerical value, | 422 | A character in a string may also be specified by its numerical value, |
| 347 | through the escape sequence \verb|'\ddd'|, | 423 | through the escape sequence \verb|'\ddd'|, |
| 348 | where \verb|ddd| is a sequence of up to three \emph{decimal} digits. | 424 | where \verb|ddd| is a sequence of up to three \emph{decimal} digits. |
| 349 | Strings in Lua may contain any 8-bit value, including embedded zeros. | 425 | Strings in Lua may contain any 8-bit value, including embedded zeros, |
| 426 | which can be specified as \verb|'\000'|. | ||
| 350 | 427 | ||
| 351 | Literal strings can also be delimited by matching \verb|[[ ... ]]|. | 428 | Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. |
| 352 | Literals in this bracketed form may run for several lines, | 429 | Literals in this bracketed form may run for several lines, |
| 353 | may contain nested \verb|[[ ... ]]| pairs, | 430 | may contain nested \verb|[[ ... ]]| pairs, |
| 354 | and do not interpret escape sequences. | 431 | and do not interpret escape sequences. |
| @@ -376,29 +453,30 @@ in Unix systems \see{lua-sa}. | |||
| 376 | and an optional decimal exponent. | 453 | and an optional decimal exponent. |
| 377 | Examples of valid numerical constants are | 454 | Examples of valid numerical constants are |
| 378 | \begin{verbatim} | 455 | \begin{verbatim} |
| 379 | 3 3.0 3.1416 314.16e-2 0.31416E1 | 456 | 3 3.0 3.1416 314.16e-2 0.31416E1 |
| 380 | \end{verbatim} | 457 | \end{verbatim} |
| 381 | 458 | ||
| 382 | \subsection{The \Index{Pre-processor}} \label{pre-processor} | 459 | \subsection{The \Index{Pre-processor}} \label{pre-processor} |
| 383 | 460 | ||
| 384 | All lines that start with a \verb|$| sign are handled by a pre-processor. | 461 | All lines that start with a \verb|$| sign are handled by a pre-processor. |
| 385 | The \verb|$| sign must be immediately | 462 | The following directives are understood by the pre-processor: |
| 386 | followed by one of the following directives: | ||
| 387 | \begin{description} | 463 | \begin{description} |
| 388 | \item[\T{debug}] --- turn on debugging facilities \see{pragma}. | 464 | \item[\T{\$debug}] --- turn on debugging facilities \see{pragma}. |
| 389 | \item[\T{nodebug}] --- turn off debugging facilities \see{pragma}. | 465 | \item[\T{\$nodebug}] --- turn off debugging facilities \see{pragma}. |
| 390 | \item[\T{if \M{cond}}] --- starts a conditional part. | 466 | \item[\T{\$if \M{cond}}] --- start a conditional part. |
| 391 | If \M{cond} is false, then this part is skipped by the lexical analyzer. | 467 | If \M{cond} is false, then this part is skipped by the lexical analyzer. |
| 392 | \item[\T{ifnot \M{cond}}] --- starts a conditional part. | 468 | \item[\T{\$ifnot \M{cond}}] --- start a conditional part. |
| 393 | If \M{cond} is true, then this part is skipped by the lexical analyzer. | 469 | If \M{cond} is true, then this part is skipped by the lexical analyzer. |
| 394 | \item[\T{end}] --- ends a conditional part. | 470 | \item[\T{\$end}] --- end a conditional part. |
| 395 | \item[\T{else}] --- starts an ``else'' conditional part, | 471 | \item[\T{\$else}] --- start an ``else'' conditional part, |
| 396 | flipping the ``skip'' status. | 472 | flipping the ``skip'' status. |
| 397 | \item[\T{endinput}] --- ends the lexical parse of the file. | 473 | \item[\T{\$endinput}] --- end the lexical parse of the chunk. |
| 474 | For all purposes, | ||
| 475 | it is as if the chunk physically ended at this point. | ||
| 398 | \end{description} | 476 | \end{description} |
| 399 | 477 | ||
| 400 | Directives may be freely nested. | 478 | Directives may be freely nested. |
| 401 | Particularly, a \verb|$endinput| may occur inside a \verb|$if|; | 479 | In particular, a \verb|$endinput| may occur inside a \verb|$if|; |
| 402 | in that case, even the matching \verb|$end| is not parsed. | 480 | in that case, even the matching \verb|$end| is not parsed. |
| 403 | 481 | ||
| 404 | A \M{cond} part may be | 482 | A \M{cond} part may be |
| @@ -418,6 +496,11 @@ Any arithmetic operation applied to a string tries to convert | |||
| 418 | that string to a number, following the usual rules. | 496 | that string to a number, following the usual rules. |
| 419 | Conversely, whenever a number is used when a string is expected, | 497 | Conversely, whenever a number is used when a string is expected, |
| 420 | that number is converted to a string, in a reasonable format. | 498 | that number is converted to a string, in a reasonable format. |
| 499 | The format is chosen so that | ||
| 500 | a conversion from number to string then back to number | ||
| 501 | reproduces the original number \emph{exactly}. | ||
| 502 | Thus, | ||
| 503 | the conversion does not necessarily produces nice-looking text for some numbers. | ||
| 421 | For complete control on how numbers are converted to strings, | 504 | For complete control on how numbers are converted to strings, |
| 422 | use the \verb|format| function \see{format}. | 505 | use the \verb|format| function \see{format}. |
| 423 | 506 | ||
| @@ -427,15 +510,15 @@ use the \verb|format| function \see{format}. | |||
| 427 | Functions in Lua can return many values. | 510 | Functions in Lua can return many values. |
| 428 | Because there are no type declarations, | 511 | Because there are no type declarations, |
| 429 | when a function is called | 512 | when a function is called |
| 430 | the system does not know how many values a function will return, | 513 | the system does not know how many values the function will return, |
| 431 | or how many parameters it needs. | 514 | or how many parameters it needs. |
| 432 | Therefore, sometimes, a list of values must be \emph{adjusted}, at run time, | 515 | Therefore, sometimes, a list of values must be \emph{adjusted}, at run time, |
| 433 | to a given length. | 516 | to a given length. |
| 434 | If there are more values than are needed, | 517 | If there are more values than are needed, |
| 435 | then the excess values are thrown away. | 518 | then the excess values are thrown away. |
| 436 | If there are more needs than values, | 519 | If there are less values than are needed, |
| 437 | then the list is extended with as many \nil's as needed. | 520 | then the list is extended with as many \nil's as needed. |
| 438 | Adjustment occurs in multiple assignment \see{assignment} | 521 | This adjustment occurs in multiple assignments \see{assignment} |
| 439 | and function calls \see{functioncall}. | 522 | and function calls \see{functioncall}. |
| 440 | 523 | ||
| 441 | 524 | ||
| @@ -444,21 +527,22 @@ and function calls \see{functioncall}. | |||
| 444 | Lua supports an almost conventional set of \Index{statements}, | 527 | Lua supports an almost conventional set of \Index{statements}, |
| 445 | similar to those in Pascal or C. | 528 | similar to those in Pascal or C. |
| 446 | The conventional commands include | 529 | The conventional commands include |
| 447 | assignment, control structures and procedure calls. | 530 | assignment, control structures, and procedure calls. |
| 448 | Non-conventional commands include table constructors | 531 | Non-conventional commands include table constructors |
| 449 | \see{tableconstructor}, | 532 | \see{tableconstructor} |
| 450 | and local variable declarations \see{localvar}. | 533 | and local variable declarations \see{localvar}. |
| 451 | 534 | ||
| 452 | \subsubsection{Blocks} | 535 | \subsubsection{Blocks} |
| 453 | A \Index{block} is a list of statements, which are executed sequentially. | 536 | A \Index{block} is a list of statements, which are executed sequentially. |
| 454 | A statement may be have an optional label, | 537 | A statement may be have an optional \Index{label}, |
| 538 | which is syntactically an identifier, | ||
| 455 | and can be optionally followed by a semicolon: | 539 | and can be optionally followed by a semicolon: |
| 456 | \begin{Produc} | 540 | \begin{Produc} |
| 457 | \produc{block}{\opt{label} \rep{stat sc}} | 541 | \produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}} |
| 458 | \produc{sc}{\opt{\ter{;}}} | ||
| 459 | \produc{label}{\ter{$\vert$} name \ter{$\vert$}} | 542 | \produc{label}{\ter{$\vert$} name \ter{$\vert$}} |
| 460 | \end{Produc}% | 543 | \end{Produc}% |
| 461 | For syntactic reasons, \rwd{return} and | 544 | \NOTE |
| 545 | For syntactic reasons, the \rwd{return} and | ||
| 462 | \rwd{break} statements can only be written | 546 | \rwd{break} statements can only be written |
| 463 | as the last statement of a block. | 547 | as the last statement of a block. |
| 464 | 548 | ||
| @@ -467,7 +551,7 @@ A block may be explicitly delimited: | |||
| 467 | \produc{stat}{\rwd{do} block \rwd{end}} | 551 | \produc{stat}{\rwd{do} block \rwd{end}} |
| 468 | \end{Produc}% | 552 | \end{Produc}% |
| 469 | This is useful to control the scope of local variables \see{localvar}, | 553 | This is useful to control the scope of local variables \see{localvar}, |
| 470 | and to add a \rwd{return} or a \rwd{break} statement in the middle | 554 | and to add a \rwd{return} or \rwd{break} statement in the middle |
| 471 | of another block: | 555 | of another block: |
| 472 | \begin{verbatim} | 556 | \begin{verbatim} |
| 473 | do return end -- return is the last statement in this block | 557 | do return end -- return is the last statement in this block |
| @@ -476,7 +560,7 @@ of another block: | |||
| 476 | \subsubsection{\Index{Assignment}} \label{assignment} | 560 | \subsubsection{\Index{Assignment}} \label{assignment} |
| 477 | The language allows \Index{multiple assignment}. | 561 | The language allows \Index{multiple assignment}. |
| 478 | Therefore, the syntax for assignment | 562 | Therefore, the syntax for assignment |
| 479 | defines a list of variables on the left side, | 563 | defines a list of variables on the left side |
| 480 | and a list of expressions on the right side. | 564 | and a list of expressions on the right side. |
| 481 | Both lists have their elements separated by commas: | 565 | Both lists have their elements separated by commas: |
| 482 | \begin{Produc} | 566 | \begin{Produc} |
| @@ -486,12 +570,20 @@ Both lists have their elements separated by commas: | |||
| 486 | This statement first evaluates all values on the right side | 570 | This statement first evaluates all values on the right side |
| 487 | and eventual indices on the left side, | 571 | and eventual indices on the left side, |
| 488 | and then makes the assignments. | 572 | and then makes the assignments. |
| 489 | Therefore, it can be used to exchange two values, as in | 573 | So |
| 574 | \begin{verbatim} | ||
| 575 | i = 3 | ||
| 576 | i, a[i] = 4, 20 | ||
| 577 | \end{verbatim} | ||
| 578 | sets \verb|a[3]| to 20, but does not affect \verb|a[4]|. | ||
| 579 | |||
| 580 | Multiple assignment can be used to exchange two values, as in | ||
| 490 | \begin{verbatim} | 581 | \begin{verbatim} |
| 491 | x, y = y, x | 582 | x, y = y, x |
| 492 | \end{verbatim} | 583 | \end{verbatim} |
| 493 | The two lists may have different lengths. | 584 | |
| 494 | Before the assignment, the list of values is \emph{adjusted} to | 585 | The two lists in a multiple assignment may have different lengths. |
| 586 | Before the assignment, the list of values is adjusted to | ||
| 495 | the length of the list of variables \see{adjust}. | 587 | the length of the list of variables \see{adjust}. |
| 496 | 588 | ||
| 497 | A single name can denote a global variable, a local variable, | 589 | A single name can denote a global variable, a local variable, |
| @@ -504,7 +596,7 @@ Square brackets are used to index a table: | |||
| 504 | \produc{var}{simpleexp \ter{[} exp1 \ter{]}} | 596 | \produc{var}{simpleexp \ter{[} exp1 \ter{]}} |
| 505 | \end{Produc}% | 597 | \end{Produc}% |
| 506 | The \M{simpleexp} should result in a table value, | 598 | The \M{simpleexp} should result in a table value, |
| 507 | from where the field indexed by the expression | 599 | from where the field indexed by the expression \M{exp1} |
| 508 | value gets the assigned value. | 600 | value gets the assigned value. |
| 509 | 601 | ||
| 510 | The syntax \verb|var.NAME| is just syntactic sugar for | 602 | The syntax \verb|var.NAME| is just syntactic sugar for |
| @@ -517,47 +609,50 @@ The meaning of assignments and evaluations of global variables and | |||
| 517 | indexed variables can be changed by tag methods \see{tag-method}. | 609 | indexed variables can be changed by tag methods \see{tag-method}. |
| 518 | Actually, | 610 | Actually, |
| 519 | an assignment \verb|x = val|, where \verb|x| is a global variable, | 611 | an assignment \verb|x = val|, where \verb|x| is a global variable, |
| 520 | is equivalent to a call \verb|setglobal('x', val)|; | 612 | is equivalent to a call \verb|setglobal("x", val)|; |
| 521 | an assignment \verb|t[i] = val| is equivalent to | 613 | an assignment \verb|t[i] = val| is equivalent to |
| 522 | \verb|settable_event(t, i, val)|. | 614 | \verb|settable_event(t,i,val)|. |
| 523 | See \See{tag-method} for a complete description of these functions. | 615 | See \See{tag-method} for a complete description of these functions. |
| 524 | (Function \verb|setglobal| is pre-defined in Lua. | 616 | (The function \verb|setglobal| is pre-defined in Lua. |
| 525 | Function \T{settable\_event} is used only for explanatory purposes.) | 617 | The function \T{settable\_event} is used only for explanatory purposes.) |
| 526 | 618 | ||
| 527 | \subsubsection{Control Structures} | 619 | \subsubsection{Control Structures} |
| 528 | The \Index{condition expression} of a control structure may return any value. | 620 | The control structures |
| 529 | All values different from \nil\ are considered true; | 621 | \index{while-do}\index{repeat-until}\index{if-then-else}% |
| 530 | only \nil\ is considered false. | 622 | \T{if}, \T{while}, and \T{repeat} have the usual meaning and |
| 531 | \T{if}'s, \T{while}'s and \T{repeat}'s have the usual meaning. | 623 | familiar syntax: |
| 532 | |||
| 533 | \index{while-do}\index{repeat-until}\index{if-then-else} | ||
| 534 | \begin{Produc} | 624 | \begin{Produc} |
| 535 | \produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end} \OrNL | 625 | \produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end}} |
| 536 | \rwd{repeat} block \rwd{until} exp1 \OrNL | 626 | \produc{stat}{\rwd{repeat} block \rwd{until} exp1} |
| 537 | \rwd{if} exp1 \rwd{then} block | 627 | \produc{stat}{\rwd{if} exp1 \rwd{then} block |
| 538 | \rep{\rwd{elseif} exp1 \rwd{then} block} | 628 | \rep{\rwd{elseif} exp1 \rwd{then} block} |
| 539 | \opt{\rwd{else} block} \rwd{end}} | 629 | \opt{\rwd{else} block} \rwd{end}} |
| 540 | \end{Produc} | 630 | \end{Produc}% |
| 631 | The \Index{condition expression} \M{exp1} of a control structure may return any value. | ||
| 632 | All values different from \nil\ are considered true; | ||
| 633 | only \nil\ is considered false. | ||
| 541 | 634 | ||
| 542 | \index{return} | 635 | \index{return} |
| 543 | A \rwd{return} is used to return values from a function or from a chunk. | 636 | The \rwd{return} statement is used to return values from a function or from a chunk. |
| 544 | \label{return} | 637 | \label{return} |
| 545 | Because they may return more than one value, | 638 | Because functions or chunks may return more than one value, |
| 546 | the syntax for a \Index{return statement} is | 639 | the syntax for a \Index{return statement} is |
| 547 | \begin{Produc} | 640 | \begin{Produc} |
| 548 | \produc{stat}{\rwd{return} \opt{explist1}} | 641 | \produc{stat}{\rwd{return} \opt{explist1}} |
| 549 | \end{Produc} | 642 | \end{Produc}% |
| 550 | 643 | ||
| 551 | \index{break} | 644 | \index{break} |
| 552 | A \rwd{break} statement can be used to terminate the execution of a block, | 645 | The \rwd{break} statement can be used to terminate the execution of a block, |
| 553 | skipping to the next instruction after the block. | 646 | skipping to the next statement after the block: |
| 554 | \begin{Produc} | 647 | \begin{Produc} |
| 555 | \produc{stat}{\rwd{break} \opt{name}} | 648 | \produc{stat}{\rwd{break} \opt{name}} |
| 556 | \end{Produc} | 649 | \end{Produc}% |
| 557 | A \rwd{break} without a label ends the inner enclosing loop | 650 | A \rwd{break} without a label ends the innermost enclosing loop |
| 558 | (while, repeat, or for). | 651 | (while, repeat, or for). |
| 559 | A \rwd{break} with a label breaks the inner enclosing | 652 | A \rwd{break} with a label breaks the innermost enclosing |
| 560 | statement with that label. | 653 | statement with that label. |
| 654 | Thus, | ||
| 655 | labels do not have to be unique. | ||
| 561 | 656 | ||
| 562 | For syntactic reasons, \rwd{return} and \rwd{break} | 657 | For syntactic reasons, \rwd{return} and \rwd{break} |
| 563 | statements can only be written as the last statement of a block. | 658 | statements can only be written as the last statement of a block. |
| @@ -568,35 +663,36 @@ The \rwd{for} statement has the following syntax: | |||
| 568 | \begin{Produc} | 663 | \begin{Produc} |
| 569 | \produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} | 664 | \produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} |
| 570 | \rwd{do} block \rwd{end}} | 665 | \rwd{do} block \rwd{end}} |
| 571 | \end{Produc} | 666 | \end{Produc}% |
| 572 | A \rwd{for} statement like | 667 | A \rwd{for} statement like |
| 573 | \begin{verbatim} | 668 | \begin{verbatim} |
| 574 | for var=e1,e2,e3 do block end | 669 | for var=e1,e2,e3 do block end |
| 575 | \end{verbatim} | 670 | \end{verbatim} |
| 576 | is equivalent to the following code: | 671 | is equivalent to the following code: |
| 577 | \begin{verbatim} | 672 | \begin{verbatim} |
| 578 | do | 673 | do |
| 579 | local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) | 674 | local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) |
| 580 | if not (var and _limit and _step) then error() end | 675 | if not (var and _limit and _step) then error() end |
| 581 | while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do | 676 | while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do |
| 582 | block | 677 | block |
| 583 | var = var+_step | 678 | var = var+_step |
| 584 | end | 679 | end |
| 585 | end | 680 | end |
| 586 | \end{verbatim} | 681 | \end{verbatim} |
| 587 | Notice the following: | 682 | Notice the following: |
| 588 | \begin{itemize} | 683 | \begin{itemize}\itemsep=0pt |
| 589 | \item \verb|_limit| and \verb|_step| are invisible variables. | 684 | \item \verb|_limit| and \verb|_step| are invisible variables. |
| 590 | \item The behavior is undefined if you assign to \verb|var| inside | 685 | The names are here for explanatory purposes only. |
| 686 | \item The behavior is \emph{undefined} if you assign to \verb|var| inside | ||
| 591 | the block. | 687 | the block. |
| 592 | \item If the third expression (the step) is absent, it defaults to 1. | 688 | \item If the third expression (the step) is absent, then a step of 1 is used. |
| 593 | \item Both the limit and the step are evaluated only once, | 689 | \item Both the limit and the step are evaluated only once, |
| 594 | before the loop starts. | 690 | before the loop starts. |
| 595 | \item The variable \verb|var| is local to the statement; | 691 | \item The variable \verb|var| is local to the statement; |
| 596 | you cannot use its value after the \rwd{for}. | 692 | you cannot use its value after the \rwd{for} ends. |
| 597 | \item You can use \rwd{break} to exit a \rwd{for}. | 693 | \item You can use \rwd{break} to exit a \rwd{for}. |
| 598 | If you need the value of the index, | 694 | If you need the value of the index, |
| 599 | assign it to another variable before breaking. | 695 | then assign it to another variable before breaking. |
| 600 | \end{itemize} | 696 | \end{itemize} |
| 601 | 697 | ||
| 602 | \subsubsection{Function Calls as Statements} \label{funcstat} | 698 | \subsubsection{Function Calls as Statements} \label{funcstat} |
| @@ -610,8 +706,6 @@ Function calls are explained in \See{functioncall}. | |||
| 610 | 706 | ||
| 611 | \subsubsection{Local Declarations} \label{localvar} | 707 | \subsubsection{Local Declarations} \label{localvar} |
| 612 | \Index{Local variables} may be declared anywhere inside a block. | 708 | \Index{Local variables} may be declared anywhere inside a block. |
| 613 | Their scope begins after the declaration and lasts until the | ||
| 614 | end of the block. | ||
| 615 | The declaration may include an initial assignment: | 709 | The declaration may include an initial assignment: |
| 616 | \begin{Produc} | 710 | \begin{Produc} |
| 617 | \produc{stat}{\rwd{local} declist \opt{init}} | 711 | \produc{stat}{\rwd{local} declist \opt{init}} |
| @@ -622,6 +716,13 @@ If present, an initial assignment has the same semantics | |||
| 622 | of a multiple assignment. | 716 | of a multiple assignment. |
| 623 | Otherwise, all variables are initialized with \nil. | 717 | Otherwise, all variables are initialized with \nil. |
| 624 | 718 | ||
| 719 | The scope of local variables begins \emph{after} | ||
| 720 | the declaration and lasts until the end of the block. | ||
| 721 | Thus, the code | ||
| 722 | \verb|local print=print| | ||
| 723 | creates a local variable called \verb|print| whose | ||
| 724 | initial value is that of the \emph{global} variable of the same name. | ||
| 725 | |||
| 625 | 726 | ||
| 626 | \subsection{\Index{Expressions}} | 727 | \subsection{\Index{Expressions}} |
| 627 | 728 | ||
| @@ -630,8 +731,8 @@ The basic expressions in Lua are | |||
| 630 | \begin{Produc} | 731 | \begin{Produc} |
| 631 | \produc{exp}{\ter{(} exp \ter{)}} | 732 | \produc{exp}{\ter{(} exp \ter{)}} |
| 632 | \produc{exp}{\rwd{nil}} | 733 | \produc{exp}{\rwd{nil}} |
| 633 | \produc{exp}{\ter{number}} | 734 | \produc{exp}{number} |
| 634 | \produc{exp}{\ter{literal}} | 735 | \produc{exp}{literal} |
| 635 | \produc{exp}{function} | 736 | \produc{exp}{function} |
| 636 | \produc{exp}{simpleexp} | 737 | \produc{exp}{simpleexp} |
| 637 | \end{Produc}% | 738 | \end{Produc}% |
| @@ -639,19 +740,21 @@ The basic expressions in Lua are | |||
| 639 | \produc{simpleexp}{var} | 740 | \produc{simpleexp}{var} |
| 640 | \produc{simpleexp}{upvalue} | 741 | \produc{simpleexp}{upvalue} |
| 641 | \produc{simpleexp}{functioncall} | 742 | \produc{simpleexp}{functioncall} |
| 743 | \produc{simpleexp}{tableconstructor} | ||
| 642 | \end{Produc}% | 744 | \end{Produc}% |
| 643 | 745 | ||
| 644 | Numbers (numerical constants) and | 746 | Numbers (numerical constants) and |
| 645 | string literals are explained in \See{lexical}; | 747 | literal strings are explained in \See{lexical}; |
| 646 | variables are explained in \See{assignment}; | 748 | variables are explained in \See{assignment}; |
| 647 | upvalues are explained in \See{upvalue}; | 749 | upvalues are explained in \See{upvalue}; |
| 648 | function definitions (\M{function}) are explained in \See{func-def}; | 750 | function definitions (\M{function}) are explained in \See{func-def}; |
| 649 | function calls are explained in \See{functioncall}. | 751 | function calls are explained in \See{functioncall}. |
| 752 | Table constructors are explained in \See{tableconstructor}. | ||
| 650 | 753 | ||
| 651 | An access to a global variable \verb|x| is equivalent to a | 754 | An access to a global variable \verb|x| is equivalent to a |
| 652 | call \verb|getglobal('x')|; | 755 | call \verb|getglobal("x")|; |
| 653 | an access to an indexed variable \verb|t[i]| is equivalent to | 756 | an access to an indexed variable \verb|t[i]| is equivalent to |
| 654 | a call \verb|gettable_event(t, i)|. | 757 | a call \verb|gettable_event(t,i)|. |
| 655 | See \See{tag-method} for a description of these functions. | 758 | See \See{tag-method} for a description of these functions. |
| 656 | (Function \verb|getglobal| is pre-defined in Lua. | 759 | (Function \verb|getglobal| is pre-defined in Lua. |
| 657 | Function \T{gettable\_event} is used only for explanatory purposes.) | 760 | Function \T{gettable\_event} is used only for explanatory purposes.) |
| @@ -660,7 +763,7 @@ The non-terminal \M{exp1} is used to indicate that the values | |||
| 660 | returned by an expression must be adjusted to one single value: | 763 | returned by an expression must be adjusted to one single value: |
| 661 | \begin{Produc} | 764 | \begin{Produc} |
| 662 | \produc{exp1}{exp} | 765 | \produc{exp1}{exp} |
| 663 | \end{Produc} | 766 | \end{Produc}% |
| 664 | 767 | ||
| 665 | \subsubsection{Arithmetic Operators} | 768 | \subsubsection{Arithmetic Operators} |
| 666 | Lua supports the usual \Index{arithmetic operators}: | 769 | Lua supports the usual \Index{arithmetic operators}: |
| @@ -680,7 +783,7 @@ giving the expected meaning to \Index{exponentiation} | |||
| 680 | \subsubsection{Relational Operators} | 783 | \subsubsection{Relational Operators} |
| 681 | Lua provides the following \Index{relational operators}: | 784 | Lua provides the following \Index{relational operators}: |
| 682 | \begin{verbatim} | 785 | \begin{verbatim} |
| 683 | == ~= < > <= >= | 786 | == ~= < > <= >= |
| 684 | \end{verbatim} | 787 | \end{verbatim} |
| 685 | All these return \nil\ as false and a value different from \nil\ as true. | 788 | All these return \nil\ as false and a value different from \nil\ as true. |
| 686 | 789 | ||
| @@ -689,12 +792,13 @@ If they are different, then the result is \nil. | |||
| 689 | Otherwise, their values are compared. | 792 | Otherwise, their values are compared. |
| 690 | Numbers and strings are compared in the usual way. | 793 | Numbers and strings are compared in the usual way. |
| 691 | Tables, userdata, and functions are compared by reference, | 794 | Tables, userdata, and functions are compared by reference, |
| 692 | that is, two tables are considered equal only if they are the same table. | 795 | that is, two tables are considered equal only if they are the \emph{same} table. |
| 693 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). | 796 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). |
| 694 | 797 | ||
| 798 | \NOTE | ||
| 695 | The conversion rules of \See{coercion} | 799 | The conversion rules of \See{coercion} |
| 696 | \emph{do not} apply to equality comparisons. | 800 | \emph{do not} apply to equality comparisons. |
| 697 | Thus, \verb|"0"==0| evaluates to false, | 801 | Thus, \verb|"0"==0| evaluates to \emph{false}, |
| 698 | and \verb|t[0]| and \verb|t["0"]| denote different | 802 | and \verb|t[0]| and \verb|t["0"]| denote different |
| 699 | entries in a table. | 803 | entries in a table. |
| 700 | 804 | ||
| @@ -702,19 +806,19 @@ The order operators work as follows. | |||
| 702 | If both arguments are numbers, then they are compared as such. | 806 | If both arguments are numbers, then they are compared as such. |
| 703 | Otherwise, if both arguments are strings, | 807 | Otherwise, if both arguments are strings, |
| 704 | then their values are compared using lexicographical order. | 808 | then their values are compared using lexicographical order. |
| 705 | Otherwise, the \verb|"lt"| tag method is called \see{tag-method}. | 809 | Otherwise, the ``lt'' tag method is called \see{tag-method}. |
| 706 | 810 | ||
| 707 | \subsubsection{Logical Operators} | 811 | \subsubsection{Logical Operators} |
| 708 | The \Index{logical operators} are | 812 | The \Index{logical operators} are |
| 709 | \index{and}\index{or}\index{not} | 813 | \index{and}\index{or}\index{not} |
| 710 | \begin{verbatim} | 814 | \begin{verbatim} |
| 711 | and or not | 815 | and or not |
| 712 | \end{verbatim} | 816 | \end{verbatim} |
| 713 | Like control structures, all logical operators | 817 | Like control structures, all logical operators |
| 714 | consider \nil\ as false and anything else as true. | 818 | consider \nil\ as false and anything else as true. |
| 715 | The operator \verb|and| returns \nil\ if its first argument is \nil; | 819 | The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; |
| 716 | otherwise, it returns its second argument. | 820 | otherwise, it returns its second argument. |
| 717 | The operator \verb|or| returns its first argument | 821 | The disjunction operator \verb|or| returns its first argument |
| 718 | if it is different from \nil; | 822 | if it is different from \nil; |
| 719 | otherwise, it returns its second argument. | 823 | otherwise, it returns its second argument. |
| 720 | Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, | 824 | Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, |
| @@ -722,17 +826,18 @@ that is, | |||
| 722 | the second operand is evaluated only when necessary. | 826 | the second operand is evaluated only when necessary. |
| 723 | 827 | ||
| 724 | There are two useful Lua idioms with logical operators. | 828 | There are two useful Lua idioms with logical operators. |
| 725 | The first is \verb|x = x or v|, | 829 | The first idiom is \verb|x = x or v|, |
| 726 | which is equivalent to | 830 | which is equivalent to |
| 727 | \begin{verbatim} | 831 | \begin{verbatim} |
| 728 | if x == nil then x = v end | 832 | if x == nil then x = v end |
| 729 | \end{verbatim} | 833 | \end{verbatim} |
| 730 | i.e., it sets \verb|x| to a default value \verb|v| when | 834 | i.e., it sets \verb|x| to a default value \verb|v| when |
| 731 | \verb|x| is not set. | 835 | \verb|x| is not set. |
| 732 | The other is \verb|x = a and b or c|, | 836 | The other idiom is \verb|x = a and b or c|, |
| 733 | which is equivalent to | 837 | which should be read as \verb|x = a and (b or c)|, |
| 838 | is equivalent to | ||
| 734 | \begin{verbatim} | 839 | \begin{verbatim} |
| 735 | if a then x = b else x = c end | 840 | if a then x = b else x = c end |
| 736 | \end{verbatim} | 841 | \end{verbatim} |
| 737 | provided that \verb|b| is not \nil. | 842 | provided that \verb|b| is not \nil. |
| 738 | 843 | ||
| @@ -747,21 +852,23 @@ Otherwise, the ``concat'' tag method is called \see{tag-method}. | |||
| 747 | \Index{Operator precedence} follows the table below, | 852 | \Index{Operator precedence} follows the table below, |
| 748 | from the lower to the higher priority: | 853 | from the lower to the higher priority: |
| 749 | \begin{verbatim} | 854 | \begin{verbatim} |
| 750 | and or | 855 | and or |
| 751 | < > <= >= ~= == | 856 | < > <= >= ~= == |
| 752 | .. | 857 | .. |
| 753 | + - | 858 | + - |
| 754 | * / | 859 | * / |
| 755 | not - (unary) | 860 | not - (unary) |
| 756 | ^ | 861 | ^ |
| 757 | \end{verbatim} | 862 | \end{verbatim} |
| 758 | All binary operators are left associative, | 863 | All binary operators are left associative, |
| 759 | except for \verb|^| (exponentiation), | 864 | except for \verb|^| (exponentiation), |
| 760 | which is right associative. | 865 | which is right associative. |
| 866 | \NOTE | ||
| 761 | The pre-compiler may rearrange the order of evaluation of | 867 | The pre-compiler may rearrange the order of evaluation of |
| 762 | associative operators (such as \verb|..| or \verb|+|), | 868 | associative operators (such as~\verb|..| or~\verb|+|), |
| 763 | as long as these optimizations do not change normal results. | 869 | as long as these optimizations do not change normal results. |
| 764 | However, they may change some results if you define non-associative | 870 | However, these optimizations may change some results |
| 871 | if you define non-associative | ||
| 765 | tag methods for these operators. | 872 | tag methods for these operators. |
| 766 | 873 | ||
| 767 | \subsubsection{Table Constructors} \label{tableconstructor} | 874 | \subsubsection{Table Constructors} \label{tableconstructor} |
| @@ -769,15 +876,14 @@ Table \Index{constructors} are expressions that create tables; | |||
| 769 | every time a constructor is evaluated, a new table is created. | 876 | every time a constructor is evaluated, a new table is created. |
| 770 | Constructors can be used to create empty tables, | 877 | Constructors can be used to create empty tables, |
| 771 | or to create a table and initialize some fields. | 878 | or to create a table and initialize some fields. |
| 772 | |||
| 773 | The general syntax for constructors is | 879 | The general syntax for constructors is |
| 774 | \begin{Produc} | 880 | \begin{Produc} |
| 775 | \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} | 881 | \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} |
| 776 | \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist | 882 | \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist |
| 777 | \Or ffieldlist \ter{;} lfieldlist} | 883 | \Or ffieldlist \ter{;} lfieldlist} |
| 778 | \produc{lfieldlist}{\opt{lfieldlist1}} | 884 | \produc{lfieldlist}{\opt{lfieldlist1}} |
| 779 | \produc{ffieldlist}{\opt{ffieldlist1}} | 885 | \produc{ffieldlist}{\opt{ffieldlist1}} |
| 780 | \end{Produc} | 886 | \end{Produc}% |
| 781 | 887 | ||
| 782 | The form \emph{lfieldlist1} is used to initialize lists: | 888 | The form \emph{lfieldlist1} is used to initialize lists: |
| 783 | \begin{Produc} | 889 | \begin{Produc} |
| @@ -826,11 +932,11 @@ in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. | |||
| 826 | Both forms may have an optional trailing comma, | 932 | Both forms may have an optional trailing comma, |
| 827 | and can be used in the same constructor separated by | 933 | and can be used in the same constructor separated by |
| 828 | a semi-collon. | 934 | a semi-collon. |
| 829 | For example, all forms below are correct: | 935 | For example, all forms below are correct. |
| 830 | \begin{verbatim} | 936 | \begin{verbatim} |
| 831 | x = {;} | 937 | x = {;} |
| 832 | x = {'a', 'b',} | 938 | x = {"a", "b",} |
| 833 | x = {type='list'; 'a', 'b'} | 939 | x = {type="list"; "a", "b"} |
| 834 | x = {f(0), f(1), f(2),; n=3,} | 940 | x = {f(0), f(1), f(2),; n=3,} |
| 835 | \end{verbatim} | 941 | \end{verbatim} |
| 836 | 942 | ||
| @@ -890,16 +996,17 @@ If the function is called in a place that can hold many values | |||
| 890 | then no adjustment is made. | 996 | then no adjustment is made. |
| 891 | The only places that can hold many values | 997 | The only places that can hold many values |
| 892 | is the last (or the only) expression in an assignment, | 998 | is the last (or the only) expression in an assignment, |
| 893 | in an argument list, or in a return statement; | 999 | in an argument list, or in a return statement. |
| 894 | see examples below. | 1000 | Here are some examples. |
| 895 | \begin{verbatim} | 1001 | \begin{verbatim} |
| 896 | f(); -- adjusted to 0 | 1002 | f(); -- adjusted to 0 |
| 897 | g(f(), x); -- f() is adjusted to 1 result | 1003 | g(f(), x); -- f() is adjusted to 1 result |
| 898 | g(x, f()); -- g gets x plus all values returned by f() | 1004 | g(x, f()); -- g gets x plus all values returned by f() |
| 899 | a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) | 1005 | a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) |
| 900 | a,b,c = x, f(); -- f() is adjusted to 2 | 1006 | a,b,c = x, f(); -- f() is adjusted to 2 |
| 901 | a,b,c = f(); -- f() is adjusted to 3 | 1007 | a,b,c = f(); -- f() is adjusted to 3 |
| 902 | return f(); -- returns all values returned by f() | 1008 | return f(); -- returns all values returned by f() |
| 1009 | return x,y,f(); -- returns a, b, and all values returned by f() | ||
| 903 | \end{verbatim} | 1010 | \end{verbatim} |
| 904 | 1011 | ||
| 905 | \subsubsection{\Index{Function Definitions}} \label{func-def} | 1012 | \subsubsection{\Index{Function Definitions}} \label{func-def} |
| @@ -910,29 +1017,29 @@ The syntax for function definition is | |||
| 910 | block \rwd{end}} | 1017 | block \rwd{end}} |
| 911 | \produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} | 1018 | \produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} |
| 912 | block \rwd{end}} | 1019 | block \rwd{end}} |
| 913 | \produc{funcname}{name \Or name \ter{.} name} | 1020 | \produc{funcname}{name \Or name \ter{.} name \Or name \ter{:} name} |
| 914 | \end{Produc} | 1021 | \end{Produc}% |
| 915 | The statement | 1022 | The statement |
| 916 | \begin{verbatim} | 1023 | \begin{verbatim} |
| 917 | function f (...) | 1024 | function f () |
| 918 | ... | 1025 | ... |
| 919 | end | 1026 | end |
| 920 | \end{verbatim} | 1027 | \end{verbatim} |
| 921 | is just syntactic sugar for | 1028 | is just syntactic sugar for |
| 922 | \begin{verbatim} | 1029 | \begin{verbatim} |
| 923 | f = function (...) | 1030 | f = function () |
| 924 | ... | 1031 | ... |
| 925 | end | 1032 | end |
| 926 | \end{verbatim} | 1033 | \end{verbatim} |
| 927 | and | 1034 | and the statement |
| 928 | \begin{verbatim} | 1035 | \begin{verbatim} |
| 929 | function o.f (...) | 1036 | function o.f () |
| 930 | ... | 1037 | ... |
| 931 | end | 1038 | end |
| 932 | \end{verbatim} | 1039 | \end{verbatim} |
| 933 | is syntactic sugar for | 1040 | is syntactic sugar for |
| 934 | \begin{verbatim} | 1041 | \begin{verbatim} |
| 935 | o.f = function (...) | 1042 | o.f = function () |
| 936 | ... | 1043 | ... |
| 937 | end | 1044 | end |
| 938 | \end{verbatim} | 1045 | \end{verbatim} |
| @@ -954,53 +1061,55 @@ initialized with the argument values: | |||
| 954 | \begin{Produc} | 1061 | \begin{Produc} |
| 955 | \produc{parlist1}{\ter{\ldots}} | 1062 | \produc{parlist1}{\ter{\ldots}} |
| 956 | \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} | 1063 | \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} |
| 957 | \end{Produc} | 1064 | \end{Produc}% |
| 958 | \label{vararg} | 1065 | \label{vararg} |
| 959 | When a function is called, | 1066 | When a function is called, |
| 960 | the list of \Index{arguments} is adjusted to | 1067 | the list of \Index{arguments} is adjusted to |
| 961 | the length of the list of parameters \see{adjust}, | 1068 | the length of the list of parameters \see{adjust}, |
| 962 | unless the function is a \Def{vararg} function, | 1069 | unless the function is a \Def{vararg} function, |
| 1070 | which is | ||
| 963 | indicated by the dots (\ldots) at the end of its parameter list. | 1071 | indicated by the dots (\ldots) at the end of its parameter list. |
| 964 | A vararg function does not adjust its argument list; | 1072 | A vararg function does not adjust its argument list; |
| 965 | instead, it collects any extra arguments into an implicit parameter, | 1073 | instead, it collects all extra arguments into an implicit parameter, |
| 966 | called \IndexVerb{arg}. | 1074 | called \IndexVerb{arg}. |
| 967 | This parameter is always initialized as a table, | 1075 | The value of \verb|arg| is a table, |
| 968 | with a field \verb|n| whose value is the number of extra arguments, | 1076 | with a field~\verb|n| whose value is the number of extra arguments, |
| 969 | and the extra arguments at positions 1,~2,~\ldots. | 1077 | and the extra arguments at positions 1,~2,~\ldots,\M{n}. |
| 970 | 1078 | ||
| 971 | As an example, suppose definitions like: | 1079 | As an example, consider the following definitions: |
| 972 | \begin{verbatim} | 1080 | \begin{verbatim} |
| 973 | function f(a, b) end | 1081 | function f(a, b) end |
| 974 | function g(a, b, ...) end | 1082 | function g(a, b, ...) end |
| 975 | function r() return 1,2,3 end | 1083 | function r() return 1,2,3 end |
| 976 | \end{verbatim} | 1084 | \end{verbatim} |
| 977 | Then, we have the following mapping from arguments to parameters: | 1085 | Then, we have the following mapping from arguments to parameters: |
| 978 | \begin{verbatim} | 1086 | \begin{verbatim} |
| 979 | CALL PARAMETERS | 1087 | CALL PARAMETERS |
| 980 | 1088 | ||
| 981 | f(3) a=3, b=nil | 1089 | f(3) a=3, b=nil |
| 982 | f(3, 4) a=3, b=4 | 1090 | f(3, 4) a=3, b=4 |
| 983 | f(3, 4, 5) a=3, b=4 | 1091 | f(3, 4, 5) a=3, b=4 |
| 984 | f(r(), 10) a=1, b=10 | 1092 | f(r(), 10) a=1, b=10 |
| 985 | f(r()) a=1, b=2 | 1093 | f(r()) a=1, b=2 |
| 986 | 1094 | ||
| 987 | g(3) a=3, b=nil, arg={n=0} | 1095 | g(3) a=3, b=nil, arg={n=0} |
| 988 | g(3, 4) a=3, b=4, arg={n=0} | 1096 | g(3, 4) a=3, b=4, arg={n=0} |
| 989 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} | 1097 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} |
| 990 | g(5, r()) a=5, b=1, arg={2, 3; n=2} | 1098 | g(5, r()) a=5, b=1, arg={2, 3; n=2} |
| 991 | \end{verbatim} | 1099 | \end{verbatim} |
| 992 | 1100 | ||
| 993 | Results are returned using the \verb|return| statement \see{return}. | 1101 | Results are returned using the \verb|return| statement \see{return}. |
| 994 | If control reaches the end of a function without a return instruction, | 1102 | If control reaches the end of a function |
| 1103 | without encountering a \rwd{return} statement, | ||
| 995 | then the function returns with no results. | 1104 | then the function returns with no results. |
| 996 | 1105 | ||
| 997 | There is a special syntax for defining \Index{methods}, | 1106 | The syntax |
| 998 | that is, functions that have an implicit extra parameter \IndexVerb{self}: | ||
| 999 | \begin{Produc} | 1107 | \begin{Produc} |
| 1000 | \produc{function}{\rwd{function} name \ter{:} name \ter{(} \opt{parlist1} | 1108 | \produc{funcname}{name \ter{:} name} |
| 1001 | \ter{)} block \rwd{end}} | ||
| 1002 | \end{Produc}% | 1109 | \end{Produc}% |
| 1003 | Thus, a declaration like | 1110 | is used for defining \Index{methods}, |
| 1111 | that is, functions that have an implicit extra parameter \IndexVerb{self}: | ||
| 1112 | Thus, the statement | ||
| 1004 | \begin{verbatim} | 1113 | \begin{verbatim} |
| 1005 | function v:f (...) | 1114 | function v:f (...) |
| 1006 | ... | 1115 | ... |
| @@ -1022,28 +1131,31 @@ previously initialized with a table value. | |||
| 1022 | 1131 | ||
| 1023 | A function body may refer to its own local variables | 1132 | A function body may refer to its own local variables |
| 1024 | (which include its parameters) and to global variables, | 1133 | (which include its parameters) and to global variables, |
| 1025 | as long as they are not shadowed by local | 1134 | as long as they are not \emph{shadowed} by local |
| 1026 | variables from enclosing functions. | 1135 | variables from enclosing functions. |
| 1027 | A function \emph{cannot} access a local | 1136 | A function \emph{cannot} access a local |
| 1028 | variable from an enclosing function, | 1137 | variable from an enclosing function, |
| 1029 | since such variables may no longer exist when the function is called. | 1138 | since such variables may no longer exist when the function is called. |
| 1030 | However, a function may access the \emph{value} of a local variable | 1139 | However, a function may access the \emph{value} of a local variable |
| 1031 | from an enclosing function, using \emph{upvalues}. | 1140 | from an enclosing function, using \emph{upvalues}, |
| 1032 | 1141 | whose syntax is | |
| 1033 | \begin{Produc} | 1142 | \begin{Produc} |
| 1034 | \produc{upvalue}{\ter{\%} name} | 1143 | \produc{upvalue}{\ter{\%} name} |
| 1035 | \end{Produc} | 1144 | \end{Produc}% |
| 1036 | An upvalue is somewhat similar to a variable expression, | 1145 | An upvalue is somewhat similar to a variable expression, |
| 1037 | but whose value is frozen when the function wherein it | 1146 | but whose value is \emph{frozen} when the function wherein it |
| 1038 | appears is instantiated. | 1147 | appears is instantiated. |
| 1039 | The name used in an upvalue may be the name of any variable visible | 1148 | The name used in an upvalue may be the name of any variable visible |
| 1040 | at the point where the function is defined. | 1149 | at the point where the function is defined, |
| 1150 | that is | ||
| 1151 | global variables and local variables from the immediately enclosing function. | ||
| 1041 | 1152 | ||
| 1042 | Here are some examples: | 1153 | Here are some examples: |
| 1043 | \begin{verbatim} | 1154 | \begin{verbatim} |
| 1044 | a,b,c = 1,2,3 -- global variables | 1155 | a,b,c = 1,2,3 -- global variables |
| 1156 | local d | ||
| 1045 | function f (x) | 1157 | function f (x) |
| 1046 | local b -- x and b are local to f | 1158 | local b -- x and b are local to f; b shadows the global b |
| 1047 | local g = function (a) | 1159 | local g = function (a) |
| 1048 | local y -- a and y are local to g | 1160 | local y -- a and y are local to g |
| 1049 | p = a -- OK, access local 'a' | 1161 | p = a -- OK, access local 'a' |
| @@ -1052,11 +1164,50 @@ Here are some examples: | |||
| 1052 | p = %b -- OK, access frozen value of 'b' (local to 'f') | 1164 | p = %b -- OK, access frozen value of 'b' (local to 'f') |
| 1053 | p = %c -- OK, access frozen value of global 'c' | 1165 | p = %c -- OK, access frozen value of global 'c' |
| 1054 | p = %y -- ERROR: 'y' is not visible where 'g' is defined | 1166 | p = %y -- ERROR: 'y' is not visible where 'g' is defined |
| 1167 | p = %d -- ERROR: 'd' is not visible where 'g' is defined | ||
| 1055 | end -- g | 1168 | end -- g |
| 1056 | end -- f | 1169 | end -- f |
| 1057 | \end{verbatim} | 1170 | \end{verbatim} |
| 1058 | 1171 | ||
| 1059 | 1172 | ||
| 1173 | \subsection{Error Handling} \label{error} | ||
| 1174 | |||
| 1175 | Because Lua is an extension language, | ||
| 1176 | all Lua actions start from C~code in the host program | ||
| 1177 | calling a function from the Lua library. | ||
| 1178 | Whenever an error occurs during Lua compilation or execution, | ||
| 1179 | the function \verb|_ERRORMESSAGE| is called \Deffunc{_ERRORMESSAGE} | ||
| 1180 | (provided it is different from \nil), | ||
| 1181 | and then the corresponding function from the library | ||
| 1182 | (\verb|lua_dofile|, \verb|lua_dostring|, | ||
| 1183 | \verb|lua_dobuffer|, or \verb|lua_callfunction|) | ||
| 1184 | is terminated, returning an error condition. | ||
| 1185 | |||
| 1186 | The only argument to \verb|_ERRORMESSAGE| is a string | ||
| 1187 | describing the error. | ||
| 1188 | The default definition for | ||
| 1189 | this function calls \verb|_ALERT|, \Deffunc{_ALERT} | ||
| 1190 | which prints the message to \verb|stderr| \see{alert}. | ||
| 1191 | The standard I/O library redefines \verb|_ERRORMESSAGE|, | ||
| 1192 | and uses the debug facilities \see{debugI} | ||
| 1193 | to print some extra information, | ||
| 1194 | such as a call stack traceback. | ||
| 1195 | |||
| 1196 | To provide more information about errors, | ||
| 1197 | Lua programs should include the compilation pragma \verb|$debug|, | ||
| 1198 | \index{debug pragma}\label{pragma} | ||
| 1199 | or be loaded from the host after calling \verb|lua_setdebug(1)| | ||
| 1200 | \see{debugI}. | ||
| 1201 | When an error occurs in a chunk compiled with this option, | ||
| 1202 | the I/O error-message routine is able to print the number of the | ||
| 1203 | lines where the calls (and the error) were made. | ||
| 1204 | |||
| 1205 | Lua code can explicitly generate an error by calling the built-in | ||
| 1206 | function \verb|error| \see{pdf-error}. | ||
| 1207 | Lua code can ``catch'' an error using the built-in function | ||
| 1208 | \verb|call| \see{pdf-call}. | ||
| 1209 | |||
| 1210 | |||
| 1060 | \subsection{Tag Methods} \label{tag-method} | 1211 | \subsection{Tag Methods} \label{tag-method} |
| 1061 | 1212 | ||
| 1062 | Lua provides a powerful mechanism to extend its semantics, | 1213 | Lua provides a powerful mechanism to extend its semantics, |
| @@ -1075,7 +1226,7 @@ Its first parameter is the tag, the second parameter is the event name | |||
| 1075 | (a string; see below), | 1226 | (a string; see below), |
| 1076 | and the third parameter is the new method (a function), | 1227 | and the third parameter is the new method (a function), |
| 1077 | or \nil\ to restore the default behavior for the pair. | 1228 | or \nil\ to restore the default behavior for the pair. |
| 1078 | The function returns the previous tag method for that pair. | 1229 | The \verb|settagmethod| function returns the previous tag method for that pair. |
| 1079 | Another function, \IndexVerb{gettagmethod}, | 1230 | Another function, \IndexVerb{gettagmethod}, |
| 1080 | receives a tag and an event name and returns the | 1231 | receives a tag and an event name and returns the |
| 1081 | current method associated with the pair. | 1232 | current method associated with the pair. |
| @@ -1084,9 +1235,9 @@ Tag methods are called in the following events, | |||
| 1084 | identified by the given names. | 1235 | identified by the given names. |
| 1085 | The semantics of tag methods is better explained by a Lua function | 1236 | The semantics of tag methods is better explained by a Lua function |
| 1086 | describing the behavior of the interpreter at each event. | 1237 | describing the behavior of the interpreter at each event. |
| 1087 | The function not only shows when a tag method is called, | 1238 | This function not only shows when a tag method is called, |
| 1088 | but also its arguments, its results, and the default behavior. | 1239 | but also its arguments, its results, and the default behavior. |
| 1089 | Please notice that the code shown here is only illustrative; | 1240 | The code shown here is only \emph{illustrative}; |
| 1090 | the real behavior is hard coded in the interpreter, | 1241 | the real behavior is hard coded in the interpreter, |
| 1091 | and it is much more efficient than this simulation. | 1242 | and it is much more efficient than this simulation. |
| 1092 | All functions used in these descriptions | 1243 | All functions used in these descriptions |
| @@ -1111,6 +1262,8 @@ If it also fails, then it gets a tag method from tag~0: | |||
| 1111 | gettagmethod(0, event) | 1262 | gettagmethod(0, event) |
| 1112 | end | 1263 | end |
| 1113 | \end{verbatim} | 1264 | \end{verbatim} |
| 1265 | Using this function, | ||
| 1266 | the tag method for the ``add' event is | ||
| 1114 | \begin{verbatim} | 1267 | \begin{verbatim} |
| 1115 | function add_event (op1, op2) | 1268 | function add_event (op1, op2) |
| 1116 | local o1, o2 = tonumber(op1), tonumber(op2) | 1269 | local o1, o2 = tonumber(op1), tonumber(op2) |
| @@ -1131,18 +1284,18 @@ If it also fails, then it gets a tag method from tag~0: | |||
| 1131 | 1284 | ||
| 1132 | \item[``sub'':]\index{sub event} | 1285 | \item[``sub'':]\index{sub event} |
| 1133 | called when a \verb|-| operation is applied to non numerical operands. | 1286 | called when a \verb|-| operation is applied to non numerical operands. |
| 1134 | Behavior similar to the \verb|"add"| event. | 1287 | Behavior similar to the ``add'' event. |
| 1135 | 1288 | ||
| 1136 | \item[``mul'':]\index{mul event} | 1289 | \item[``mul'':]\index{mul event} |
| 1137 | called when a \verb|*| operation is applied to non numerical operands. | 1290 | called when a \verb|*| operation is applied to non numerical operands. |
| 1138 | Behavior similar to the \verb|"add"| event. | 1291 | Behavior similar to the ``add'' event. |
| 1139 | 1292 | ||
| 1140 | \item[``div'':]\index{div event} | 1293 | \item[``div'':]\index{div event} |
| 1141 | called when a \verb|/| operation is applied to non numerical operands. | 1294 | called when a \verb|/| operation is applied to non numerical operands. |
| 1142 | Behavior similar to the \verb|"add"| event. | 1295 | Behavior similar to the ``add'' event. |
| 1143 | 1296 | ||
| 1144 | \item[``pow'':]\index{pow event} | 1297 | \item[``pow'':]\index{pow event} |
| 1145 | called when a \verb|^| operation is applied. | 1298 | called when a \verb|^| operation (exponentiation) is applied. |
| 1146 | \begin{verbatim} | 1299 | \begin{verbatim} |
| 1147 | function pow_event (op1, op2) | 1300 | function pow_event (op1, op2) |
| 1148 | local tm = getbinmethod(op1, op2, "pow") | 1301 | local tm = getbinmethod(op1, op2, "pow") |
| @@ -1157,7 +1310,7 @@ called when a \verb|^| operation is applied. | |||
| 1157 | \end{verbatim} | 1310 | \end{verbatim} |
| 1158 | 1311 | ||
| 1159 | \item[``unm'':]\index{unm event} | 1312 | \item[``unm'':]\index{unm event} |
| 1160 | called when an unary \verb|-| operation is applied to a non numerical operand. | 1313 | called when a unary \verb|-| operation is applied to a non numerical operand. |
| 1161 | \begin{verbatim} | 1314 | \begin{verbatim} |
| 1162 | function unm_event (op) | 1315 | function unm_event (op) |
| 1163 | local o = tonumber(op) | 1316 | local o = tonumber(op) |
| @@ -1228,12 +1381,14 @@ called when a concatenation is applied to non string operands. | |||
| 1228 | \item[``index'':]\index{index event} | 1381 | \item[``index'':]\index{index event} |
| 1229 | called when Lua tries to retrieve the value of an index | 1382 | called when Lua tries to retrieve the value of an index |
| 1230 | not present in a table. | 1383 | not present in a table. |
| 1231 | See event \verb|"gettable"| for its semantics. | 1384 | See event ``gettable'' for its semantics. |
| 1232 | 1385 | ||
| 1233 | \item[``getglobal'':]\index{getglobal event} | 1386 | \item[``getglobal'':]\index{getglobal event} |
| 1234 | called whenever Lua needs the value of a global variable. | 1387 | called whenever Lua needs the value of a global variable. |
| 1235 | This method can only be set for \nil\ and for tags | 1388 | This method can only be set for \nil\ and for tags |
| 1236 | created by \verb|newtag|. | 1389 | created by \verb|newtag|. |
| 1390 | Note that | ||
| 1391 | the tag is that of the \emph{current value} of the global variable. | ||
| 1237 | \begin{verbatim} | 1392 | \begin{verbatim} |
| 1238 | function getglobal (varname) | 1393 | function getglobal (varname) |
| 1239 | local value = rawgetglobal(varname) | 1394 | local value = rawgetglobal(varname) |
| @@ -1262,7 +1417,7 @@ userdata with default tags. | |||
| 1262 | end | 1417 | end |
| 1263 | end | 1418 | end |
| 1264 | \end{verbatim} | 1419 | \end{verbatim} |
| 1265 | Notice: the function \verb|setglobal| is pre-defined in Lua \see{predefined}. | 1420 | The function \verb|setglobal| is pre-defined in Lua \see{predefined}. |
| 1266 | 1421 | ||
| 1267 | \item[``gettable'':]\index{gettable event} | 1422 | \item[``gettable'':]\index{gettable event} |
| 1268 | called whenever Lua accesses an indexed variable. | 1423 | called whenever Lua accesses an indexed variable. |
| @@ -1325,9 +1480,9 @@ called when Lua tries to call a non function value. | |||
| 1325 | \end{verbatim} | 1480 | \end{verbatim} |
| 1326 | 1481 | ||
| 1327 | \item[``gc'':]\index{gc event} | 1482 | \item[``gc'':]\index{gc event} |
| 1328 | called when Lua is ``garbage collecting'' an userdata. | 1483 | called when Lua is ``garbage collecting'' a userdata. |
| 1329 | This tag method can be set only from C, | 1484 | This tag method can be set only from~C, |
| 1330 | and cannot be set for an userdata with default tag. | 1485 | and cannot be set for a userdata with default tag. |
| 1331 | For each userdata to be collected, | 1486 | For each userdata to be collected, |
| 1332 | Lua does the equivalent of the following function: | 1487 | Lua does the equivalent of the following function: |
| 1333 | \begin{verbatim} | 1488 | \begin{verbatim} |
| @@ -1345,73 +1500,39 @@ Lua does the equivalent of the call \verb|gc_event(nil)|. | |||
| 1345 | 1500 | ||
| 1346 | 1501 | ||
| 1347 | 1502 | ||
| 1348 | \subsection{Error Handling} \label{error} | ||
| 1349 | |||
| 1350 | Because Lua is an extension language, | ||
| 1351 | all Lua actions start from C code in the host program | ||
| 1352 | calling a function from the Lua library. | ||
| 1353 | Whenever an error occurs during Lua compilation or execution, | ||
| 1354 | function \verb|_ERRORMESSAGE| is called \Deffunc{_ERRORMESSAGE} | ||
| 1355 | (provided it is different from \nil), | ||
| 1356 | and then the corresponding function from the library | ||
| 1357 | (\verb|lua_dofile|, \verb|lua_dostring|, | ||
| 1358 | \verb|lua_dobuffer|, or \verb|lua_callfunction|) | ||
| 1359 | is terminated, returning an error condition. | ||
| 1360 | |||
| 1361 | The only argument to \verb|_ERRORMESSAGE| is a string | ||
| 1362 | describing the error. | ||
| 1363 | The default definition for | ||
| 1364 | this function calls \verb|_ALERT|, \Deffunc{_ALERT} | ||
| 1365 | which prints the message to \verb|stderr| \see{alert}. | ||
| 1366 | The standard I/O library redefines \verb|_ERRORMESSAGE|, | ||
| 1367 | and uses the debug facilities \see{debugI} | ||
| 1368 | to print some extra information, | ||
| 1369 | such as the call stack. | ||
| 1370 | |||
| 1371 | To provide more information about errors, | ||
| 1372 | Lua programs should include the compilation pragma \verb|$debug|. | ||
| 1373 | \index{debug pragma}\label{pragma} | ||
| 1374 | When an error occurs in a chunk compiled with this option, | ||
| 1375 | the I/O error-message routine is able to print the number of the | ||
| 1376 | lines where the calls (and the error) were made. | ||
| 1377 | |||
| 1378 | Lua code can explicitly generate an error by calling the built-in | ||
| 1379 | function \verb|error| \see{pdf-error}. | ||
| 1380 | Lua code can ``catch'' an error using the built-in function | ||
| 1381 | \verb|call| \see{pdf-call}. | ||
| 1382 | |||
| 1383 | |||
| 1384 | 1503 | ||
| 1385 | \section{The Application Program Interface} | 1504 | \section{The Application Program Interface} |
| 1386 | 1505 | ||
| 1387 | This section describes the API for Lua, that is, | 1506 | This section describes the API for Lua, that is, |
| 1388 | the set of C functions available to the host program to communicate | 1507 | the set of C~functions available to the host program to communicate |
| 1389 | with the Lua library. | 1508 | with the Lua library. |
| 1390 | The API functions can be classified in the following categories: | 1509 | The API functions can be classified into the following categories: |
| 1391 | \begin{enumerate} | 1510 | \begin{enumerate} |
| 1392 | \item managing states; | 1511 | \item managing states; |
| 1393 | \item exchanging values between C and Lua; | 1512 | \item exchanging values between C and Lua; |
| 1394 | \item executing Lua code; | 1513 | \item executing Lua code; |
| 1395 | \item manipulating (reading and writing) Lua objects; | 1514 | \item manipulating (reading and writing) Lua objects; |
| 1396 | \item calling Lua functions; | 1515 | \item calling Lua functions; |
| 1397 | \item defining C functions to be called by Lua; | 1516 | \item defining C~functions to be called by Lua; |
| 1398 | \item manipulating references to Lua Objects. | 1517 | \item manipulating references to Lua Objects. |
| 1399 | \end{enumerate} | 1518 | \end{enumerate} |
| 1400 | All API functions and related types and constants | 1519 | All API functions and related types and constants |
| 1401 | are declared in the header file \verb|lua.h|. | 1520 | are declared in the header file \verb|lua.h|. |
| 1402 | 1521 | ||
| 1522 | \NOTE | ||
| 1403 | Even when we use the term \emph{function}, | 1523 | Even when we use the term \emph{function}, |
| 1404 | \emph{any facility in the API may be provided as a macro instead}. | 1524 | \emph{any facility in the API may be provided as a macro instead}. |
| 1405 | Any of such macros uses once and only once each of its arguments. | 1525 | All such macros use each of its arguments exactly once, |
| 1526 | and so do not generate hidden side-effects. | ||
| 1406 | 1527 | ||
| 1407 | 1528 | ||
| 1408 | \subsection{States} \label{mangstate} | 1529 | \subsection{States} \label{mangstate} |
| 1409 | 1530 | ||
| 1410 | The Lua library is reentrant. | 1531 | The Lua library is reentrant: |
| 1411 | It does not have any global variable. | 1532 | it does not have any global variable. |
| 1412 | The whole state of the Lua interpreter | 1533 | The whole state of the Lua interpreter |
| 1413 | (global variables, stack, tag methods, etc) | 1534 | (global variables, stack, tag methods, etc.) |
| 1414 | is stored in a dynamic structure \Deffunc{lua_State}; | 1535 | is stored in a dynamic structure; \Deffunc{lua_State} |
| 1415 | this state must be passed as the first argument to almost | 1536 | this state must be passed as the first argument to almost |
| 1416 | every function in the library. | 1537 | every function in the library. |
| 1417 | 1538 | ||
| @@ -1421,19 +1542,19 @@ This is done by calling\Deffunc{lua_newstate} | |||
| 1421 | \begin{verbatim} | 1542 | \begin{verbatim} |
| 1422 | lua_State *lua_newstate (const char *s, ...); | 1543 | lua_State *lua_newstate (const char *s, ...); |
| 1423 | \end{verbatim} | 1544 | \end{verbatim} |
| 1424 | The arguments to this function is a list of name-value options, | 1545 | The arguments to this function form a list of name-value options, |
| 1425 | terminated with \verb|NULL|. | 1546 | terminated with \verb|NULL|. |
| 1426 | Currently, the function accepts the following options: | 1547 | Currently, the function accepts the following options: |
| 1427 | \begin{itemize} | 1548 | \begin{itemize} |
| 1428 | \item \verb|"stack"| - the stack size. | 1549 | \item \verb|"stack"| --- the stack size. |
| 1429 | Each function call needs one stack position for each local variable | 1550 | Each function call needs one stack position for each local variable |
| 1430 | and temporary variables, plus one position. | 1551 | and temporary variables, plus one position for book-keeping. |
| 1431 | The stack must also have at least ten extra positions available. | 1552 | The stack must also have at least ten extra positions available. |
| 1432 | For very small implementations, without recursive functions, | 1553 | For very small implementations, without recursive functions, |
| 1433 | a size of 100 should be enough. | 1554 | a stack size of 100 should be enough. |
| 1434 | The default is 1K. | 1555 | The default stack size is 1024. |
| 1435 | 1556 | ||
| 1436 | \item \verb|"builtin"| - the value is a boolean (0 or 1) that | 1557 | \item \verb|"builtin"| --- the value is a boolean (0 or 1) that |
| 1437 | indicates whether the predefined functions should be loaded or not. | 1558 | indicates whether the predefined functions should be loaded or not. |
| 1438 | The default is to load those functions. | 1559 | The default is to load those functions. |
| 1439 | \end{itemize} | 1560 | \end{itemize} |
| @@ -1441,7 +1562,7 @@ For instance, the call | |||
| 1441 | \begin{verbatim} | 1562 | \begin{verbatim} |
| 1442 | lua_State *L = lua_newstate(NULL); | 1563 | lua_State *L = lua_newstate(NULL); |
| 1443 | \end{verbatim} | 1564 | \end{verbatim} |
| 1444 | creates a new state with a stack of 1K positions, | 1565 | creates a new state with a stack of 1024 positions |
| 1445 | and with the predefined functions loaded; | 1566 | and with the predefined functions loaded; |
| 1446 | the call | 1567 | the call |
| 1447 | \begin{verbatim} | 1568 | \begin{verbatim} |
| @@ -1455,13 +1576,18 @@ To release a state, you call | |||
| 1455 | void lua_close (lua_State *L); | 1576 | void lua_close (lua_State *L); |
| 1456 | \end{verbatim} | 1577 | \end{verbatim} |
| 1457 | This function destroys all objects in the current Lua environment | 1578 | This function destroys all objects in the current Lua environment |
| 1458 | (calling the correspondent garbage collector tag methods), | 1579 | (calling the corresponding garbage collection tag methods) |
| 1459 | and frees all dynamic memory used by the state. | 1580 | and frees all dynamic memory used by the state. |
| 1460 | Usually, you do not need to call this function, | 1581 | Usually, you do not need to call this function, |
| 1461 | because these resources are naturally released when the program ends. | 1582 | because all resources are naturally released when the program ends. |
| 1583 | On the other hand, | ||
| 1584 | long-running programs --- | ||
| 1585 | like a daemon or web server, for example --- | ||
| 1586 | might need to release states as soon as they are not needed, | ||
| 1587 | to avoid growing too big. | ||
| 1462 | 1588 | ||
| 1463 | With the exception of \verb|lua_newstate|, | 1589 | With the exception of \verb|lua_newstate|, |
| 1464 | all functions in the API get at its first argument a state. | 1590 | all functions in the API need a state as their first argument. |
| 1465 | However, most applications use a single state. | 1591 | However, most applications use a single state. |
| 1466 | To avoid the burden of passing this only state explicitly to all | 1592 | To avoid the burden of passing this only state explicitly to all |
| 1467 | functions, and also to keep compatibility with old versions of Lua, | 1593 | functions, and also to keep compatibility with old versions of Lua, |
| @@ -1491,14 +1617,13 @@ in this case, the corresponding macro is | |||
| 1491 | \begin{verbatim} | 1617 | \begin{verbatim} |
| 1492 | #define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0)))) | 1618 | #define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0)))) |
| 1493 | \end{verbatim} | 1619 | \end{verbatim} |
| 1494 | It checks whether the global state has been initialized; | 1620 | This code checks whether the global state has been initialized; |
| 1495 | if not, it creates a new state with default settings and | 1621 | if not, it creates a new state with default settings and |
| 1496 | assigns it to \verb|lua_newstate|. | 1622 | assigns it to \verb|lua_newstate|. |
| 1497 | 1623 | ||
| 1498 | By default, those macros are all active. | 1624 | By default, the single-state macros are all active. |
| 1499 | If you will use multiple states, | 1625 | If you need to use multiple states, |
| 1500 | and therefore will want to provide the state | 1626 | and therefore will provide the state argument explicitly in each call, |
| 1501 | argument explicitly for each call, | ||
| 1502 | you should define \IndexVerb{LUA_REENTRANT} before | 1627 | you should define \IndexVerb{LUA_REENTRANT} before |
| 1503 | including \verb|lua.h| in your code: | 1628 | including \verb|lua.h| in your code: |
| 1504 | \begin{verbatim} | 1629 | \begin{verbatim} |
| @@ -1520,7 +1645,7 @@ which works like an abstract type in C that can hold any Lua value. | |||
| 1520 | Values of type \verb|lua_Object| have no meaning outside Lua; | 1645 | Values of type \verb|lua_Object| have no meaning outside Lua; |
| 1521 | for instance, | 1646 | for instance, |
| 1522 | you cannot compare two \verb|lua_Object's| directly. | 1647 | you cannot compare two \verb|lua_Object's| directly. |
| 1523 | Instead, you should use the next function: | 1648 | Instead, you should use the following function: |
| 1524 | \Deffunc{lua_equal} | 1649 | \Deffunc{lua_equal} |
| 1525 | \begin{verbatim} | 1650 | \begin{verbatim} |
| 1526 | int lua_equal (lua_Object o1, lua_Object o2); | 1651 | int lua_equal (lua_Object o1, lua_Object o2); |
| @@ -1533,21 +1658,21 @@ the following functions are available: | |||
| 1533 | \Deffunc{lua_isfunction} | 1658 | \Deffunc{lua_isfunction} |
| 1534 | \Deffunc{lua_type} | 1659 | \Deffunc{lua_type} |
| 1535 | \begin{verbatim} | 1660 | \begin{verbatim} |
| 1536 | int lua_isnil (lua_Object object); | 1661 | int lua_isnil (lua_Object object); |
| 1537 | int lua_isnumber (lua_Object object); | 1662 | int lua_isnumber (lua_Object object); |
| 1538 | int lua_isstring (lua_Object object); | 1663 | int lua_isstring (lua_Object object); |
| 1539 | int lua_istable (lua_Object object); | 1664 | int lua_istable (lua_Object object); |
| 1540 | int lua_isfunction (lua_Object object); | 1665 | int lua_isfunction (lua_Object object); |
| 1541 | int lua_iscfunction (lua_Object object); | 1666 | int lua_iscfunction (lua_Object object); |
| 1542 | int lua_isuserdata (lua_Object object); | 1667 | int lua_isuserdata (lua_Object object); |
| 1543 | const char *lua_type (lua_Object obj); | 1668 | const char *lua_type (lua_Object object); |
| 1544 | \end{verbatim} | 1669 | \end{verbatim} |
| 1545 | The \verb|lua_is*| functions return 1 if the object is compatible | 1670 | The \verb|lua_is*| functions return 1 if the object is compatible |
| 1546 | with the given type, and 0 otherwise. | 1671 | with the given type, and 0 otherwise. |
| 1547 | The function \verb|lua_isnumber| accepts numbers and numerical strings, | 1672 | The function \verb|lua_isnumber| accepts numbers and numerical strings, |
| 1548 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, | 1673 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, |
| 1549 | and \verb|lua_isfunction| accepts Lua functions and C functions. | 1674 | and \verb|lua_isfunction| accepts Lua functions and C~functions. |
| 1550 | To distinguish between Lua functions and C functions, | 1675 | To distinguish between Lua functions and C~functions, |
| 1551 | you should use \verb|lua_iscfunction|. | 1676 | you should use \verb|lua_iscfunction|. |
| 1552 | To distinguish between numbers and numerical strings, | 1677 | To distinguish between numbers and numerical strings, |
| 1553 | you can use \verb|lua_type|. | 1678 | you can use \verb|lua_type|. |
| @@ -1557,14 +1682,14 @@ describing the type of the given object: | |||
| 1557 | \verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|. | 1682 | \verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|. |
| 1558 | 1683 | ||
| 1559 | To get the tag of a \verb|lua_Object|, | 1684 | To get the tag of a \verb|lua_Object|, |
| 1560 | the following function is available: | 1685 | use the following function: |
| 1561 | \Deffunc{lua_tag} | 1686 | \Deffunc{lua_tag} |
| 1562 | \begin{verbatim} | 1687 | \begin{verbatim} |
| 1563 | int lua_tag (lua_Object object); | 1688 | int lua_tag (lua_Object object); |
| 1564 | \end{verbatim} | 1689 | \end{verbatim} |
| 1565 | 1690 | ||
| 1566 | To translate a value from type \verb|lua_Object| to a specific C type, | 1691 | To translate a value from type \verb|lua_Object| to a specific C type, |
| 1567 | you can use | 1692 | you can use the following conversion functions: |
| 1568 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} | 1693 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} |
| 1569 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} | 1694 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} |
| 1570 | \begin{verbatim} | 1695 | \begin{verbatim} |
| @@ -1593,9 +1718,13 @@ Because Lua has garbage collection, | |||
| 1593 | there is no guarantee that the pointer returned by \verb|lua_getstring| | 1718 | there is no guarantee that the pointer returned by \verb|lua_getstring| |
| 1594 | will be valid after the block ends | 1719 | will be valid after the block ends |
| 1595 | \see{GC}. | 1720 | \see{GC}. |
| 1721 | So, | ||
| 1722 | if you need the string later on, | ||
| 1723 | you should duplicate it with something like | ||
| 1724 | \verb|memcpy(malloc(lua_strlen(o),lua_getstring(o)))|. | ||
| 1596 | 1725 | ||
| 1597 | \verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. | 1726 | \verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function. |
| 1598 | This \verb|lua_Object| must have type \emph{CFunction}; | 1727 | This \verb|lua_Object| must be a C~function; |
| 1599 | otherwise, \verb|lua_getcfunction| returns \verb|NULL|. | 1728 | otherwise, \verb|lua_getcfunction| returns \verb|NULL|. |
| 1600 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. | 1729 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. |
| 1601 | 1730 | ||
| @@ -1603,27 +1732,7 @@ The type \verb|lua_CFunction| is explained in \See{LuacallC}. | |||
| 1603 | This \verb|lua_Object| must have type \emph{userdata}; | 1732 | This \verb|lua_Object| must have type \emph{userdata}; |
| 1604 | otherwise, \verb|lua_getuserdata| returns \verb|NULL|. | 1733 | otherwise, \verb|lua_getuserdata| returns \verb|NULL|. |
| 1605 | 1734 | ||
| 1606 | \subsection{Garbage Collection}\label{GC} | 1735 | \subsection{Communication between Lua and C}\label{Lua-C-protocol} |
| 1607 | Because Lua has automatic memory management and garbage collection, | ||
| 1608 | a \verb|lua_Object| has a limited scope, | ||
| 1609 | and is only valid inside the \emph{block} where it has been created. | ||
| 1610 | A C function called from Lua is a block, | ||
| 1611 | and its parameters are valid only until its end. | ||
| 1612 | It is good programming practice to convert Lua objects to C values | ||
| 1613 | as soon as they are available, | ||
| 1614 | and never to store \verb|lua_Object|s in C global variables. | ||
| 1615 | |||
| 1616 | A garbage collection cycle can be forced by: | ||
| 1617 | \Deffunc{lua_collectgarbage} | ||
| 1618 | \begin{verbatim} | ||
| 1619 | long lua_collectgarbage (long limit); | ||
| 1620 | \end{verbatim} | ||
| 1621 | This function returns the number of objects collected. | ||
| 1622 | The argument \verb|limit| makes the next cycle occur only | ||
| 1623 | after that number of new objects have been created. | ||
| 1624 | If \verb|limit| is 0, | ||
| 1625 | then Lua uses an adaptive heuristics to set this limit. | ||
| 1626 | |||
| 1627 | 1736 | ||
| 1628 | All communication between Lua and C is done through two | 1737 | All communication between Lua and C is done through two |
| 1629 | abstract data types, called \Def{lua2C} and \Def{C2lua}. | 1738 | abstract data types, called \Def{lua2C} and \Def{C2lua}. |
| @@ -1633,8 +1742,8 @@ parameters when Lua calls C and results when C calls Lua. | |||
| 1633 | The structure C2lua is used in the reverse direction: | 1742 | The structure C2lua is used in the reverse direction: |
| 1634 | parameters when C calls Lua and results when Lua calls C. | 1743 | parameters when C calls Lua and results when Lua calls C. |
| 1635 | 1744 | ||
| 1636 | The structure lua2C is an abstract array, | 1745 | The structure lua2C is an \emph{abstract array} |
| 1637 | which can be indexed with the function: | 1746 | that can be indexed with the function: |
| 1638 | \Deffunc{lua_lua2C} | 1747 | \Deffunc{lua_lua2C} |
| 1639 | \begin{verbatim} | 1748 | \begin{verbatim} |
| 1640 | lua_Object lua_lua2C (int number); | 1749 | lua_Object lua_lua2C (int number); |
| @@ -1642,12 +1751,12 @@ lua_Object lua_lua2C (int number); | |||
| 1642 | where \verb|number| starts with 1. | 1751 | where \verb|number| starts with 1. |
| 1643 | When called with a number larger than the array size, | 1752 | When called with a number larger than the array size, |
| 1644 | this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. | 1753 | this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. |
| 1645 | In this way, it is possible to write C functions that receive | 1754 | In this way, it is possible to write C~functions that receive |
| 1646 | a variable number of parameters, | 1755 | a variable number of parameters, |
| 1647 | and to call Lua functions that return a variable number of results. | 1756 | and to call Lua functions that return a variable number of results. |
| 1648 | Note that the structure lua2C cannot be directly modified by C code. | 1757 | Note that the structure lua2C cannot be directly modified by C code. |
| 1649 | 1758 | ||
| 1650 | The second structure, C2lua, is an abstract stack. | 1759 | The structure C2lua is an \emph{abstract stack}. |
| 1651 | Pushing elements into this stack | 1760 | Pushing elements into this stack |
| 1652 | is done with the following functions: | 1761 | is done with the following functions: |
| 1653 | \Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} | 1762 | \Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} |
| @@ -1670,7 +1779,7 @@ In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring| | |||
| 1670 | make an internal copy of the given string. | 1779 | make an internal copy of the given string. |
| 1671 | Function \verb|lua_pushstring| can only be used to push proper C strings | 1780 | Function \verb|lua_pushstring| can only be used to push proper C strings |
| 1672 | (that is, strings that end with a zero and do not contain embedded zeros); | 1781 | (that is, strings that end with a zero and do not contain embedded zeros); |
| 1673 | otherwise you should use the more generic \verb|lua_pushlstring|. | 1782 | otherwise you should use the more general \verb|lua_pushlstring|. |
| 1674 | The function | 1783 | The function |
| 1675 | \Deffunc{lua_pop} | 1784 | \Deffunc{lua_pop} |
| 1676 | \begin{verbatim} | 1785 | \begin{verbatim} |
| @@ -1682,10 +1791,48 @@ and pops it. | |||
| 1682 | As a general rule, all API functions pop from the stack | 1791 | As a general rule, all API functions pop from the stack |
| 1683 | all elements they use. | 1792 | all elements they use. |
| 1684 | 1793 | ||
| 1794 | When C code calls Lua repeatedly, as in a loop, | ||
| 1795 | objects returned by these calls can accumulate, | ||
| 1796 | and may cause a stack overflow. | ||
| 1797 | To avoid this, | ||
| 1798 | nested blocks can be defined with the functions | ||
| 1799 | \begin{verbatim} | ||
| 1800 | void lua_beginblock (void); | ||
| 1801 | void lua_endblock (void); | ||
| 1802 | \end{verbatim} | ||
| 1803 | After the end of the block, | ||
| 1804 | all \verb|lua_Object|'s created inside it are released. | ||
| 1805 | The use of explicit nested blocks is good programming practice | ||
| 1806 | and is strongly encouraged. | ||
| 1807 | |||
| 1808 | \subsection{Garbage Collection}\label{GC} | ||
| 1809 | Because Lua has automatic memory management and garbage collection, | ||
| 1810 | a \verb|lua_Object| has a limited scope, | ||
| 1811 | and is only valid inside the \emph{block} where it has been created. | ||
| 1812 | A C~function called from Lua is a block, | ||
| 1813 | and its parameters are valid only until its end. | ||
| 1814 | It is good programming practice to convert Lua objects to C values | ||
| 1815 | as soon as they are available, | ||
| 1816 | and never to store \verb|lua_Object|s in C global variables. | ||
| 1817 | |||
| 1818 | A garbage collection cycle can be forced by: | ||
| 1819 | \Deffunc{lua_collectgarbage} | ||
| 1820 | \begin{verbatim} | ||
| 1821 | long lua_collectgarbage (long limit); | ||
| 1822 | \end{verbatim} | ||
| 1823 | This function returns the number of objects collected. | ||
| 1824 | The argument \verb|limit| makes the next cycle occur only | ||
| 1825 | after that number of new objects have been created. | ||
| 1826 | If \verb|limit| is 0, | ||
| 1827 | then Lua uses an adaptive heuristics to set this limit. | ||
| 1828 | |||
| 1829 | |||
| 1830 | \subsection{Userdata and Tags}\label{C-tags} | ||
| 1831 | |||
| 1685 | Because userdata are objects, | 1832 | Because userdata are objects, |
| 1686 | the function \verb|lua_pushusertag| may create a new userdata. | 1833 | the function \verb|lua_pushusertag| may create a new userdata. |
| 1687 | If Lua has a userdata with the given value (\verb|void*|) and tag, | 1834 | If Lua has a userdata with the given value (\verb|void*|) and tag, |
| 1688 | that userdata is pushed. | 1835 | then that userdata is pushed. |
| 1689 | Otherwise, a new userdata is created, with the given value and tag. | 1836 | Otherwise, a new userdata is created, with the given value and tag. |
| 1690 | If this function is called with | 1837 | If this function is called with |
| 1691 | \verb|tag| equal to \verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG}, | 1838 | \verb|tag| equal to \verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG}, |
| @@ -1696,33 +1843,19 @@ with tag equal to 0. | |||
| 1696 | 1843 | ||
| 1697 | Userdata can have different tags, | 1844 | Userdata can have different tags, |
| 1698 | whose semantics are only known to the host program. | 1845 | whose semantics are only known to the host program. |
| 1699 | Tags are created with the function: | 1846 | Tags are created with the function |
| 1700 | \Deffunc{lua_newtag} | 1847 | \Deffunc{lua_newtag} |
| 1701 | \begin{verbatim} | 1848 | \begin{verbatim} |
| 1702 | int lua_newtag (void); | 1849 | int lua_newtag (void); |
| 1703 | \end{verbatim} | 1850 | \end{verbatim} |
| 1704 | The function \verb|lua_settag| changes the tag of | 1851 | The function \verb|lua_settag| changes the tag of |
| 1705 | the object on the top of C2lua (and pops it); | 1852 | the object on the top of C2lua (and pops it); |
| 1706 | the object must be a userdata or a table. | 1853 | the object must be a userdata or a table: |
| 1707 | \Deffunc{lua_settag} | 1854 | \Deffunc{lua_settag} |
| 1708 | \begin{verbatim} | 1855 | \begin{verbatim} |
| 1709 | void lua_settag (int tag); | 1856 | void lua_settag (int tag); |
| 1710 | \end{verbatim} | 1857 | \end{verbatim} |
| 1711 | \verb|tag| must be a value created with \verb|lua_newtag|. | 1858 | The given \verb|tag| must be a value created with \verb|lua_newtag|. |
| 1712 | |||
| 1713 | When C code calls Lua repeatedly, as in a loop, | ||
| 1714 | objects returned by these calls can accumulate, | ||
| 1715 | and may cause a stack overflow. | ||
| 1716 | To avoid this, | ||
| 1717 | nested blocks can be defined with the functions: | ||
| 1718 | \begin{verbatim} | ||
| 1719 | void lua_beginblock (void); | ||
| 1720 | void lua_endblock (void); | ||
| 1721 | \end{verbatim} | ||
| 1722 | After the end of the block, | ||
| 1723 | all \verb|lua_Object|'s created inside it are released. | ||
| 1724 | The use of explicit nested blocks is good programming practice | ||
| 1725 | and is strongly encouraged. | ||
| 1726 | 1859 | ||
| 1727 | \subsection{Executing Lua Code} | 1860 | \subsection{Executing Lua Code} |
| 1728 | A host program can execute Lua chunks written in a file or in a string | 1861 | A host program can execute Lua chunks written in a file or in a string |
| @@ -1737,19 +1870,25 @@ All these functions return an error code: | |||
| 1737 | 0, in case of success; non zero, in case of errors. | 1870 | 0, in case of success; non zero, in case of errors. |
| 1738 | More specifically, \verb|lua_dofile| returns 2 if for any reason | 1871 | More specifically, \verb|lua_dofile| returns 2 if for any reason |
| 1739 | it could not open the file. | 1872 | it could not open the file. |
| 1873 | (In this case, | ||
| 1874 | you may want to | ||
| 1875 | check \verb|errno|, | ||
| 1876 | call \verb|strerror|, | ||
| 1877 | or call \verb|perror| to tell the user what went wrong.) | ||
| 1740 | When called with argument \verb|NULL|, | 1878 | When called with argument \verb|NULL|, |
| 1741 | \verb|lua_dofile| executes the \verb|stdin| stream. | 1879 | \verb|lua_dofile| executes the \verb|stdin| stream. |
| 1742 | Functions \verb|lua_dofile| and \verb|lua_dobuffer| | 1880 | Functions \verb|lua_dofile| and \verb|lua_dobuffer| |
| 1743 | are both able to execute pre-compiled chunks. | 1881 | are both able to execute pre-compiled chunks. |
| 1744 | They automatically detect whether the chunk is text or binary, | 1882 | They automatically detect whether the chunk is text or binary, |
| 1745 | and load it accordingly (see program \IndexVerb{luac}). | 1883 | and load it accordingly (see program \IndexVerb{luac}). |
| 1746 | Function \verb|lua_dostring| executes only source code. | 1884 | Function \verb|lua_dostring| executes only source code, |
| 1885 | given in textual form. | ||
| 1747 | 1886 | ||
| 1748 | The third parameter to \verb|lua_dobuffer| (\verb|name|) | 1887 | The third parameter to \verb|lua_dobuffer| (\verb|name|) |
| 1749 | is the ``name of the chunk'', | 1888 | is the ``name of the chunk'', |
| 1750 | used in error messages and debug information. | 1889 | used in error messages and debug information. |
| 1751 | If \verb|name| is \verb|NULL|, | 1890 | If \verb|name| is \verb|NULL|, |
| 1752 | Lua gives a default name to the chunk. | 1891 | then Lua gives a default name to the chunk. |
| 1753 | 1892 | ||
| 1754 | These functions return, in structure lua2C, | 1893 | These functions return, in structure lua2C, |
| 1755 | any values eventually returned by the chunks. | 1894 | any values eventually returned by the chunks. |
| @@ -1758,12 +1897,13 @@ They also empty the stack C2lua. | |||
| 1758 | 1897 | ||
| 1759 | \subsection{Manipulating Lua Objects} | 1898 | \subsection{Manipulating Lua Objects} |
| 1760 | To read the value of any global Lua variable, | 1899 | To read the value of any global Lua variable, |
| 1761 | one uses the function: | 1900 | one uses the function |
| 1762 | \Deffunc{lua_getglobal} | 1901 | \Deffunc{lua_getglobal} |
| 1763 | \begin{verbatim} | 1902 | \begin{verbatim} |
| 1764 | lua_Object lua_getglobal (const char *varname); | 1903 | lua_Object lua_getglobal (const char *varname); |
| 1765 | \end{verbatim} | 1904 | \end{verbatim} |
| 1766 | As in Lua, this function may trigger a tag method. | 1905 | As in Lua, this function may trigger a tag method |
| 1906 | for the ``getglobal'' event. | ||
| 1767 | To read the real value of any global variable, | 1907 | To read the real value of any global variable, |
| 1768 | without invoking any tag method, | 1908 | without invoking any tag method, |
| 1769 | use the \emph{raw} version: | 1909 | use the \emph{raw} version: |
| @@ -1773,12 +1913,13 @@ lua_Object lua_rawgetglobal (const char *varname); | |||
| 1773 | \end{verbatim} | 1913 | \end{verbatim} |
| 1774 | 1914 | ||
| 1775 | To store a value previously pushed onto C2lua in a global variable, | 1915 | To store a value previously pushed onto C2lua in a global variable, |
| 1776 | there is the function: | 1916 | there is the function |
| 1777 | \Deffunc{lua_setglobal} | 1917 | \Deffunc{lua_setglobal} |
| 1778 | \begin{verbatim} | 1918 | \begin{verbatim} |
| 1779 | void lua_setglobal (const char *varname); | 1919 | void lua_setglobal (const char *varname); |
| 1780 | \end{verbatim} | 1920 | \end{verbatim} |
| 1781 | As in Lua, this function may trigger a tag method. | 1921 | As in Lua, this function may trigger a tag method |
| 1922 | for the ``setglobal'' event. | ||
| 1782 | To set the real value of any global variable, | 1923 | To set the real value of any global variable, |
| 1783 | without invoking any tag method, | 1924 | without invoking any tag method, |
| 1784 | use the \emph{raw} version: | 1925 | use the \emph{raw} version: |
| @@ -1795,7 +1936,8 @@ lua_Object lua_gettable (void); | |||
| 1795 | \end{verbatim} | 1936 | \end{verbatim} |
| 1796 | pops a table and an index from the stack C2lua, | 1937 | pops a table and an index from the stack C2lua, |
| 1797 | and returns the contents of the table at that index. | 1938 | and returns the contents of the table at that index. |
| 1798 | As in Lua, this operation may trigger a tag method. | 1939 | As in Lua, this operation may trigger a tag method |
| 1940 | for the ``gettable'' event. | ||
| 1799 | To get the real value of any table index, | 1941 | To get the real value of any table index, |
| 1800 | without invoking any tag method, | 1942 | without invoking any tag method, |
| 1801 | use the \emph{raw} version: | 1943 | use the \emph{raw} version: |
| @@ -1805,14 +1947,15 @@ lua_Object lua_rawgettable (void); | |||
| 1805 | \end{verbatim} | 1947 | \end{verbatim} |
| 1806 | 1948 | ||
| 1807 | To store a value in an index, | 1949 | To store a value in an index, |
| 1808 | the program must push the table, the index, | 1950 | the program must push the table, the index, and the value onto C2lua |
| 1809 | and the value onto C2lua, | 1951 | (in this order), |
| 1810 | and then call the function | 1952 | and then call the function |
| 1811 | \Deffunc{lua_settable} | 1953 | \Deffunc{lua_settable} |
| 1812 | \begin{verbatim} | 1954 | \begin{verbatim} |
| 1813 | void lua_settable (void); | 1955 | void lua_settable (void); |
| 1814 | \end{verbatim} | 1956 | \end{verbatim} |
| 1815 | Again, the tag method for ``settable'' may be called. | 1957 | As in Lua, this operation may trigger a tag method |
| 1958 | for the ``settable'' event. | ||
| 1816 | To set the real value of any table index, | 1959 | To set the real value of any table index, |
| 1817 | without invoking any tag method, | 1960 | without invoking any tag method, |
| 1818 | use the \emph{raw} version: | 1961 | use the \emph{raw} version: |
| @@ -1846,11 +1989,11 @@ Finally, the results are returned in structure lua2C | |||
| 1846 | (recall that a Lua function may return many values), | 1989 | (recall that a Lua function may return many values), |
| 1847 | and can be retrieved with the macro \verb|lua_getresult|, | 1990 | and can be retrieved with the macro \verb|lua_getresult|, |
| 1848 | \Deffunc{lua_getresult} | 1991 | \Deffunc{lua_getresult} |
| 1849 | which is just another name to function \verb|lua_lua2C|. | 1992 | which is just another name for the function \verb|lua_lua2C|. |
| 1850 | Note that function \verb|lua_callfunction| | 1993 | Note that \verb|lua_callfunction| |
| 1851 | pops all elements from the C2lua stack. | 1994 | pops all elements from the C2lua stack. |
| 1852 | 1995 | ||
| 1853 | The following example shows how a C program may do the | 1996 | The following example shows how the host program may do the |
| 1854 | equivalent to the Lua code: | 1997 | equivalent to the Lua code: |
| 1855 | \begin{verbatim} | 1998 | \begin{verbatim} |
| 1856 | a,b = f("how", t.x, 4) | 1999 | a,b = f("how", t.x, 4) |
| @@ -1869,18 +2012,19 @@ equivalent to the Lua code: | |||
| 1869 | \end{verbatim} | 2012 | \end{verbatim} |
| 1870 | 2013 | ||
| 1871 | Some special Lua functions have exclusive interfaces. | 2014 | Some special Lua functions have exclusive interfaces. |
| 1872 | A C function can generate a Lua error calling the function | 2015 | The host program can generate a Lua error calling the function |
| 1873 | \Deffunc{lua_error} | 2016 | \Deffunc{lua_error} |
| 1874 | \begin{verbatim} | 2017 | \begin{verbatim} |
| 1875 | void lua_error (const char *message); | 2018 | void lua_error (const char *message); |
| 1876 | \end{verbatim} | 2019 | \end{verbatim} |
| 1877 | This function never returns. | 2020 | This function never returns. |
| 1878 | If the C function has been called from Lua, | 2021 | If \verb|lua_error| is called from a C~function that has been called from Lua, |
| 1879 | then the corresponding Lua execution terminates, | 2022 | then the corresponding Lua execution terminates, |
| 1880 | as if an error had occurred inside Lua code. | 2023 | as if an error had occurred inside Lua code. |
| 1881 | Otherwise, the whole host program terminates with a call to \verb|exit(1)|. | 2024 | Otherwise, the whole host program terminates with a call to \verb|exit(1)|. |
| 1882 | The \verb|message| is passed to the error handler function, | 2025 | Before terminating execution, |
| 1883 | \verb|_ERRORMESSAGE|. | 2026 | the \verb|message| is passed to the error handler function, |
| 2027 | \verb|_ERRORMESSAGE| \see{error}. | ||
| 1884 | If \verb|message| is \verb|NULL|, | 2028 | If \verb|message| is \verb|NULL|, |
| 1885 | then \verb|_ERRORMESSAGE| is not called. | 2029 | then \verb|_ERRORMESSAGE| is not called. |
| 1886 | 2030 | ||
| @@ -1915,7 +2059,7 @@ and the second is a \emph{cursor}; | |||
| 1915 | this cursor starts in 0, | 2059 | this cursor starts in 0, |
| 1916 | and for each call the function returns a value to | 2060 | and for each call the function returns a value to |
| 1917 | be used in the next call, | 2061 | be used in the next call, |
| 1918 | or 0 to signal the end of the traverse. | 2062 | or 0 to signal the end of the traversal. |
| 1919 | The function also returns, in the Lua2C array, | 2063 | The function also returns, in the Lua2C array, |
| 1920 | a key-value pair from the table. | 2064 | a key-value pair from the table. |
| 1921 | A typical traversal looks like the following code: | 2065 | A typical traversal looks like the following code: |
| @@ -1936,9 +2080,9 @@ A typical traversal looks like the following code: | |||
| 1936 | \end{verbatim} | 2080 | \end{verbatim} |
| 1937 | The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the | 2081 | The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the |
| 1938 | results of each iteration from the stack. | 2082 | results of each iteration from the stack. |
| 1939 | Without them, a traversal of a large table will overflow the stack. | 2083 | Without them, a traversal of a large table may overflow the stack. |
| 1940 | 2084 | ||
| 1941 | To traverse the global variables, you use \Deffunc{lua_nextvar} | 2085 | To traverse the global variables, use \Deffunc{lua_nextvar} |
| 1942 | \begin{verbatim} | 2086 | \begin{verbatim} |
| 1943 | const char *lua_nextvar (const char *varname); | 2087 | const char *lua_nextvar (const char *varname); |
| 1944 | \end{verbatim} | 2088 | \end{verbatim} |
| @@ -1964,8 +2108,8 @@ A typical traversal looks like the following code: | |||
| 1964 | 2108 | ||
| 1965 | 2109 | ||
| 1966 | \subsection{Defining C Functions} \label{LuacallC} | 2110 | \subsection{Defining C Functions} \label{LuacallC} |
| 1967 | To register a C function to Lua, | 2111 | To register a C~function to Lua, |
| 1968 | there is the following macro: | 2112 | there is the following convenience macro: |
| 1969 | \Deffunc{lua_register} | 2113 | \Deffunc{lua_register} |
| 1970 | \begin{verbatim} | 2114 | \begin{verbatim} |
| 1971 | #define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n)) | 2115 | #define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n)) |
| @@ -1983,39 +2127,42 @@ typedef void (*lua_CFunction) (void); | |||
| 1983 | that is, a pointer to a function with no parameters and no results. | 2127 | that is, a pointer to a function with no parameters and no results. |
| 1984 | 2128 | ||
| 1985 | In order to communicate properly with Lua, | 2129 | In order to communicate properly with Lua, |
| 1986 | a C function must follow a protocol, | 2130 | a C~function must follow a protocol, |
| 1987 | which defines the way parameters and results are passed. | 2131 | which defines the way parameters and results are passed. |
| 1988 | 2132 | ||
| 1989 | A C function receives its arguments in structure lua2C; | 2133 | A C~function receives its arguments in structure lua2C; |
| 1990 | to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} | 2134 | to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} |
| 1991 | again just another name for \verb|lua_lua2C|. | 2135 | again just another name for \verb|lua_lua2C|. |
| 1992 | To return values, a C function just pushes them onto the stack C2lua, | 2136 | To return values, a C~function just pushes them onto the stack C2lua, |
| 1993 | in direct order \see{valuesCLua}. | 2137 | in direct order \see{valuesCLua}. |
| 1994 | Like a Lua function, a C function called by Lua can also return | 2138 | Like a Lua function, a C~function called by Lua can also return |
| 1995 | many results. | 2139 | many results. |
| 1996 | 2140 | ||
| 1997 | When a C function is created, | 2141 | When a C~function is created, |
| 1998 | it is possible to associate some \emph{upvalues} to it, | 2142 | it is possible to associate some \emph{upvalues} to it |
| 2143 | \see{upvalue}, | ||
| 1999 | thus creating a C closure; | 2144 | thus creating a C closure; |
| 2000 | then these values are passed to the function whenever it is called, | 2145 | these values are passed to the function whenever it is called, |
| 2001 | as common arguments. | 2146 | as common arguments. |
| 2002 | To associate upvalues to a function, | 2147 | To associate upvalues to a C~function, |
| 2003 | first these values must be pushed on C2lua. | 2148 | first these values must be pushed on C2lua. |
| 2004 | Then the function \Deffunc{lua_pushcclosure} | 2149 | Then the function \Deffunc{lua_pushcclosure} |
| 2005 | \begin{verbatim} | 2150 | \begin{verbatim} |
| 2006 | void lua_pushcclosure (lua_CFunction fn, int n); | 2151 | void lua_pushcclosure (lua_CFunction fn, int n); |
| 2007 | \end{verbatim} | 2152 | \end{verbatim} |
| 2008 | is used to put the C function on C2lua, | 2153 | is used to put the C~function on C2lua, |
| 2009 | with the argument \verb|n| telling how many upvalues must be | 2154 | with the argument \verb|n| telling how many upvalues must be |
| 2010 | associated with the function; | 2155 | associated with the function; |
| 2011 | in fact, the macro \verb|lua_pushcfunction| is defined as | 2156 | in fact, the macro \verb|lua_pushcfunction| is defined as |
| 2012 | \verb|lua_pushcclosure| with \verb|n| set to 0. | 2157 | \verb|lua_pushcclosure| with \verb|n| set to 0. |
| 2013 | Then, any time the function is called, | 2158 | Then, whenever the C~function is called, |
| 2014 | these upvalues are inserted as the first arguments to the function, | 2159 | these upvalues are inserted as the first arguments \M{n} to the function, |
| 2015 | before the actual arguments provided in the call. | 2160 | before the actual arguments provided in the call. |
| 2016 | 2161 | ||
| 2017 | For some examples of C functions, see files \verb|lstrlib.c|, | 2162 | For some examples of C~functions, see files \verb|lstrlib.c|, |
| 2018 | \verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. | 2163 | \verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. |
| 2164 | In particular, | ||
| 2165 | \verb|liolib.c| defines C~closures with file handles are upvalues. | ||
| 2019 | 2166 | ||
| 2020 | \subsection{References to Lua Objects} | 2167 | \subsection{References to Lua Objects} |
| 2021 | 2168 | ||
| @@ -2034,15 +2181,15 @@ void lua_unref (int ref); | |||
| 2034 | The function \verb|lua_ref| creates a reference | 2181 | The function \verb|lua_ref| creates a reference |
| 2035 | to the object that is on the top of the stack, | 2182 | to the object that is on the top of the stack, |
| 2036 | and returns this reference. | 2183 | and returns this reference. |
| 2037 | For a \nil{} object, | 2184 | For a \nil\ object, |
| 2038 | the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL} | 2185 | the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL} |
| 2039 | otherwise, it is a non-negative integer. | 2186 | otherwise, it is a non-negative integer. |
| 2040 | The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} | 2187 | The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} |
| 2041 | is different from any valid reference. | 2188 | is different from any valid reference. |
| 2042 | If \verb|lock| is true, the object is \emph{locked}: | 2189 | If \verb|lock| is true, then the object is \emph{locked}: |
| 2043 | this means the object will not be garbage collected. | 2190 | this means the object will not be garbage collected. |
| 2044 | Note that an unlocked reference may be garbage collected. | 2191 | \emph{Unlocked references may be garbage collected}. |
| 2045 | Whenever the referenced object is needed, | 2192 | Whenever the referenced object is needed in~C, |
| 2046 | a call to \verb|lua_getref| | 2193 | a call to \verb|lua_getref| |
| 2047 | returns a handle to it; | 2194 | returns a handle to it; |
| 2048 | if the object has been collected, | 2195 | if the object has been collected, |
| @@ -2081,6 +2228,28 @@ and \verb|lua_iolibopen|, declared in \verb|lualib.h|. | |||
| 2081 | 2228 | ||
| 2082 | \subsection{Predefined Functions} \label{predefined} | 2229 | \subsection{Predefined Functions} \label{predefined} |
| 2083 | 2230 | ||
| 2231 | \subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} | ||
| 2232 | Prints its only string argument to \IndexVerb{stderr}. | ||
| 2233 | All error messages in Lua are printed through the function stored | ||
| 2234 | in the \verb|_ALERT| global variable | ||
| 2235 | \see{error}. | ||
| 2236 | Therefore, a program may assign another function to this variable | ||
| 2237 | to change the way such messages are shown | ||
| 2238 | (for instance, for systems without \verb|stderr|). | ||
| 2239 | |||
| 2240 | \subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert} | ||
| 2241 | Issues an \emph{``assertion failed!''} error | ||
| 2242 | when its argument \verb|v| is \nil. | ||
| 2243 | This function is equivalent to the following Lua function: | ||
| 2244 | \begin{verbatim} | ||
| 2245 | function assert (v, m) | ||
| 2246 | if not v then | ||
| 2247 | m = m or "" | ||
| 2248 | error("assertion failed! " .. m) | ||
| 2249 | end | ||
| 2250 | end | ||
| 2251 | \end{verbatim} | ||
| 2252 | |||
| 2084 | \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} | 2253 | \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} |
| 2085 | \label{pdf-call} | 2254 | \label{pdf-call} |
| 2086 | Calls function \verb|func| with | 2255 | Calls function \verb|func| with |
| @@ -2092,24 +2261,24 @@ The call is equivalent to | |||
| 2092 | where \verb|n| is the result of \verb|getn(arg)| \see{getn}. | 2261 | where \verb|n| is the result of \verb|getn(arg)| \see{getn}. |
| 2093 | 2262 | ||
| 2094 | By default, | 2263 | By default, |
| 2095 | all results from \verb|func| are just returned by the call. | 2264 | all results from \verb|func| are simply returned by \verb|call|. |
| 2096 | If the string \verb|mode| contains \verb|"p"|, | 2265 | If the string \verb|mode| contains \verb|"p"|, |
| 2097 | the results are \emph{packed} in a single table.\index{packed results} | 2266 | then the results are \emph{packed} in a single table.\index{packed results} |
| 2098 | That is, \verb|call| returns just one table; | 2267 | That is, \verb|call| returns just one table; |
| 2099 | at index \verb|n|, the table has the total number of results | 2268 | at index \verb|n|, the table has the total number of results |
| 2100 | from the call; | 2269 | from the call; |
| 2101 | the first result is at index 1, etc. | 2270 | the first result is at index 1, etc. |
| 2102 | For instance, the following calls produce the following results: | 2271 | For instance, the following calls produce the following results: |
| 2103 | \begin{verbatim} | 2272 | \begin{verbatim} |
| 2104 | a = call(sin, {5}) --> a = 0.0871557 = sin(5) | 2273 | a = call(sin, {5}) --> a = 0.0871557 = sin(5) |
| 2105 | a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) | 2274 | a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) |
| 2106 | a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1} | 2275 | a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1} |
| 2107 | t = {x=1} | 2276 | t = {x=1} |
| 2108 | a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} | 2277 | a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} |
| 2109 | \end{verbatim} | 2278 | \end{verbatim} |
| 2110 | 2279 | ||
| 2111 | By default, | 2280 | By default, |
| 2112 | if an error occurs during the function call, | 2281 | if an error occurs during the call to \verb|func|, |
| 2113 | the error is propagated. | 2282 | the error is propagated. |
| 2114 | If the string \verb|mode| contains \verb|"x"|, | 2283 | If the string \verb|mode| contains \verb|"x"|, |
| 2115 | then the call is \emph{protected}.\index{protected calls} | 2284 | then the call is \emph{protected}.\index{protected calls} |
| @@ -2118,26 +2287,31 @@ regardless of what happens during the call. | |||
| 2118 | Instead, it returns \nil\ to signal the error | 2287 | Instead, it returns \nil\ to signal the error |
| 2119 | (besides calling the appropriated error handler). | 2288 | (besides calling the appropriated error handler). |
| 2120 | 2289 | ||
| 2121 | If provided, | 2290 | If \verb|errhandler| is provided, |
| 2122 | \verb|errhandler| is temporarily set as the error function | 2291 | the error function \verb|_ERRORMESSAGE| is temporarily set \verb|errhandler|, |
| 2123 | \verb|_ERRORMESSAGE|, while \verb|func| runs. | 2292 | while \verb|func| runs. |
| 2124 | In particular, if \verb|errhandler| is \nil, | 2293 | In particular, if \verb|errhandler| is \nil, |
| 2125 | no error messages will be issued during the execution of the called function. | 2294 | no error messages will be issued during the execution of the called function. |
| 2126 | 2295 | ||
| 2127 | \subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage} | 2296 | \subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage} |
| 2128 | Forces a garbage collection cycle. | 2297 | Forces a garbage collection cycle. |
| 2129 | Returns the number of objects collected. | 2298 | Returns the number of objects collected. |
| 2130 | An optional argument, \verb|limit|, is a number that | 2299 | The optional argument \verb|limit| is a number that |
| 2131 | makes the next cycle occur only after that number of new | 2300 | makes the next cycle occur only after that number of new |
| 2132 | objects have been created. | 2301 | objects have been created. |
| 2133 | If \verb|limit| is absent or equal to 0, | 2302 | If \verb|limit| is absent or equal to 0, |
| 2134 | Lua uses an adaptive algorithm to set this limit. | 2303 | then Lua uses an adaptive algorithm to set this limit. |
| 2135 | \verb|collectgarbage| is equivalent to | 2304 | \verb|collectgarbage| is equivalent to |
| 2136 | the API function \verb|lua_collectgarbage|. | 2305 | the API function \verb|lua_collectgarbage|. |
| 2137 | 2306 | ||
| 2307 | \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} | ||
| 2308 | \Deffunc{copytagmethods} | ||
| 2309 | Copies all tag methods from one tag to another; | ||
| 2310 | it returns \verb|tagto|. | ||
| 2311 | |||
| 2138 | \subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile} | 2312 | \subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile} |
| 2139 | Receives a file name, | 2313 | Receives a file name, |
| 2140 | opens the file, and executes the file contents as a Lua chunk, | 2314 | opens the named file, and executes its contents as a Lua chunk, |
| 2141 | or as pre-compiled chunks. | 2315 | or as pre-compiled chunks. |
| 2142 | When called without arguments, | 2316 | When called without arguments, |
| 2143 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). | 2317 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). |
| @@ -2151,14 +2325,140 @@ It issues an error when called with a non string argument. | |||
| 2151 | \subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring} | 2325 | \subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring} |
| 2152 | Executes a given string as a Lua chunk. | 2326 | Executes a given string as a Lua chunk. |
| 2153 | If there is any error executing the string, | 2327 | If there is any error executing the string, |
| 2154 | \verb|dostring| returns \nil. | 2328 | then \verb|dostring| returns \nil. |
| 2155 | Otherwise, it returns the values returned by the chunk, | 2329 | Otherwise, it returns the values returned by the chunk, |
| 2156 | or a non \nil\ value if the chunk returns no values. | 2330 | or a non \nil\ value if the chunk returns no values. |
| 2157 | An optional second parameter (\verb|chunkname|) | 2331 | The optional parameter \verb|chunkname| |
| 2158 | is the ``name of the chunk'', | 2332 | is the ``name of the chunk'', |
| 2159 | used in error messages and debug information. | 2333 | used in error messages and debug information. |
| 2160 | \verb|dostring| is equivalent to the API function \verb|lua_dostring|. | 2334 | \verb|dostring| is equivalent to the API function \verb|lua_dostring|. |
| 2161 | 2335 | ||
| 2336 | \subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error} | ||
| 2337 | Calls the error handler \see{error} and then terminates | ||
| 2338 | the last protected function called | ||
| 2339 | (in~C: \verb|lua_dofile|, \verb|lua_dostring|, | ||
| 2340 | \verb|lua_dobuffer|, or \verb|lua_callfunction|; | ||
| 2341 | in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). | ||
| 2342 | If \verb|message| is \nil, then the error handler is not called. | ||
| 2343 | Function \verb|error| never returns. | ||
| 2344 | \verb|error| is equivalent to the API function \verb|lua_error|. | ||
| 2345 | |||
| 2346 | \subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} | ||
| 2347 | Executes the given \verb|function| over all elements of \verb|table|. | ||
| 2348 | For each element, the function is called with the index and | ||
| 2349 | respective value as arguments. | ||
| 2350 | If the function returns any non-\nil\ value, | ||
| 2351 | then the loop is broken, and this value is returned | ||
| 2352 | as the final value of \verb|foreach|. | ||
| 2353 | |||
| 2354 | This function could be defined in Lua: | ||
| 2355 | \begin{verbatim} | ||
| 2356 | function foreach (t, f) | ||
| 2357 | local i, v = nil | ||
| 2358 | while 1 do | ||
| 2359 | i, v = next(t, i) | ||
| 2360 | if not i then break end | ||
| 2361 | local res = f(i, v) | ||
| 2362 | if res then return res end | ||
| 2363 | end | ||
| 2364 | end | ||
| 2365 | \end{verbatim} | ||
| 2366 | |||
| 2367 | You may change the \emph{values} of existing fields in the table during the traversal, | ||
| 2368 | but | ||
| 2369 | if you create new indices, | ||
| 2370 | then | ||
| 2371 | the semantics of \verb|foreach| is undefined. | ||
| 2372 | |||
| 2373 | |||
| 2374 | \subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} | ||
| 2375 | Executes the given \verb|function| over the | ||
| 2376 | numerical indices of \verb|table|. | ||
| 2377 | For each index, the function is called with the index and | ||
| 2378 | respective value as arguments. | ||
| 2379 | Indices are visited in sequential order, | ||
| 2380 | from 1 to \verb|n|, | ||
| 2381 | where \verb|n| is the result of \verb|getn(table)| \see{getn}. | ||
| 2382 | If the function returns any non-\nil\ value, | ||
| 2383 | then the loop is broken, and this value is returned | ||
| 2384 | as the final value of \verb|foreachi|. | ||
| 2385 | |||
| 2386 | This function could be defined in Lua: | ||
| 2387 | \begin{verbatim} | ||
| 2388 | function foreachi (t, f) | ||
| 2389 | for i=1,getn(t) do | ||
| 2390 | local res = f(i, t[i]) | ||
| 2391 | if res then return res end | ||
| 2392 | end | ||
| 2393 | end | ||
| 2394 | \end{verbatim} | ||
| 2395 | |||
| 2396 | You may change the \emph{values} of existing fields in the table during the traversal, | ||
| 2397 | but | ||
| 2398 | if you create new indices (even non-numeric), | ||
| 2399 | then | ||
| 2400 | the semantics of \verb|foreachi| is undefined. | ||
| 2401 | |||
| 2402 | \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} | ||
| 2403 | Executes \verb|function| over all global variables. | ||
| 2404 | For each variable, | ||
| 2405 | the function is called with its name and its value as arguments. | ||
| 2406 | If the function returns any non-nil value, | ||
| 2407 | then the loop is broken, and this value is returned | ||
| 2408 | as the final value of \verb|foreachvar|. | ||
| 2409 | |||
| 2410 | This function could be defined in Lua: | ||
| 2411 | \begin{verbatim} | ||
| 2412 | function foreachvar (f) | ||
| 2413 | local n, v = nil | ||
| 2414 | while 1 do | ||
| 2415 | n, v = nextvar(n) | ||
| 2416 | if not n then break end | ||
| 2417 | local res = f(n, v) | ||
| 2418 | if res then return res end | ||
| 2419 | end | ||
| 2420 | end | ||
| 2421 | \end{verbatim} | ||
| 2422 | |||
| 2423 | You may change the values of existing global variables during the traversal, | ||
| 2424 | but | ||
| 2425 | if you create new global variables, | ||
| 2426 | then | ||
| 2427 | the semantics of \verb|foreachvar| is undefined. | ||
| 2428 | |||
| 2429 | |||
| 2430 | \subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal} | ||
| 2431 | Gets the value of a global variable, | ||
| 2432 | or calls a tag method for ``getgloball''. | ||
| 2433 | Its full semantics is explained in \See{tag-method}. | ||
| 2434 | The string \verb|name| does not need to be a | ||
| 2435 | syntactically valid variable name. | ||
| 2436 | |||
| 2437 | \subsubsection*{\ff \T{getn (table)}}\Deffunc{getn}\label{getn} | ||
| 2438 | Returns the ``size'' of a table, when seen as a list. | ||
| 2439 | If the table has an \verb|n| field with a numeric value, | ||
| 2440 | this value is its ``size''. | ||
| 2441 | Otherwise, the size is the largest numerical index with a non-nil | ||
| 2442 | value in the table. | ||
| 2443 | This function could be defined in Lua: | ||
| 2444 | \begin{verbatim} | ||
| 2445 | function getn (t) | ||
| 2446 | if type(t.n) == 'number' then return t.n end | ||
| 2447 | local max, i = 0, nil | ||
| 2448 | while 1 do | ||
| 2449 | i = next(t, i) | ||
| 2450 | if not i then break end | ||
| 2451 | if type(i) == 'number' and i>max then max=i end | ||
| 2452 | end | ||
| 2453 | return max | ||
| 2454 | end | ||
| 2455 | \end{verbatim} | ||
| 2456 | |||
| 2457 | \subsubsection*{\ff \T{gettagmethod (tag, event)}} | ||
| 2458 | \Deffunc{gettagmethod} | ||
| 2459 | Returns the current tag method | ||
| 2460 | for a given pair \M{(tag, event)}. | ||
| 2461 | |||
| 2162 | \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} | 2462 | \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} |
| 2163 | Returns a new tag. | 2463 | Returns a new tag. |
| 2164 | \verb|newtag| is equivalent to the API function \verb|lua_newtag|. | 2464 | \verb|newtag| is equivalent to the API function \verb|lua_newtag|. |
| @@ -2170,23 +2470,26 @@ is an index in this table. | |||
| 2170 | It returns the next index of the table and the | 2470 | It returns the next index of the table and the |
| 2171 | value associated with the index. | 2471 | value associated with the index. |
| 2172 | When called with \nil\ as its second argument, | 2472 | When called with \nil\ as its second argument, |
| 2173 | the function returns the first index | 2473 | \verb|next| returns the first index |
| 2174 | of the table (and its associated value). | 2474 | of the table and its associated value. |
| 2175 | When called with the last index, | 2475 | When called with the last index, |
| 2176 | or with \nil\ in an empty table, | 2476 | or with \nil\ in an empty table, |
| 2177 | it returns \nil. | 2477 | it returns \nil. |
| 2178 | If the second argument is absent, it is interpreted as \nil. | 2478 | If the second argument is absent, then it is interpreted as \nil. |
| 2179 | 2479 | ||
| 2180 | Lua has no declaration of fields; | 2480 | Lua has no declaration of fields; |
| 2181 | semantically, there is no difference between a | 2481 | semantically, there is no difference between a |
| 2182 | field not present in a table or a field with value \nil. | 2482 | field not present in a table or a field with value \nil. |
| 2183 | Therefore, the function only considers fields with non \nil\ values. | 2483 | Therefore, \verb|next| only considers fields with non \nil\ values. |
| 2184 | The order in which the indices are enumerated is not specified, | 2484 | The order in which the indices are enumerated is not specified, |
| 2185 | \emph{even for numeric indices} | 2485 | \emph{even for numeric indices} |
| 2186 | (to traverse a table in numeric order, | 2486 | (to traverse a table in numeric order, |
| 2187 | use a counter or the function \verb|foreachi|). | 2487 | use a counter or the function \verb|foreachi|). |
| 2188 | If you create new indices in a table while | 2488 | |
| 2189 | traversing it, | 2489 | You may change the \emph{values} of existing fields in the table during the traversal, |
| 2490 | but | ||
| 2491 | if you create new indices, | ||
| 2492 | then | ||
| 2190 | the semantics of \verb|next| is undefined. | 2493 | the semantics of \verb|next| is undefined. |
| 2191 | 2494 | ||
| 2192 | \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} | 2495 | \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} |
| @@ -2194,18 +2497,16 @@ This function is similar to the function \verb|next|, | |||
| 2194 | but iterates instead over the global variables. | 2497 | but iterates instead over the global variables. |
| 2195 | Its single argument is the name of a global variable, | 2498 | Its single argument is the name of a global variable, |
| 2196 | or \nil\ to get a first name. | 2499 | or \nil\ to get a first name. |
| 2197 | If this argument is absent, it is interpreted as \nil. | 2500 | If this argument is absent, then it is interpreted as \nil. |
| 2198 | Similarly to \verb|next|, it returns the name of another variable | 2501 | Like \verb|next|, \verb|nextvar| returns the name of another variable |
| 2199 | and its value, | 2502 | and its value, |
| 2200 | or \nil\ if there are no more variables. | 2503 | or \nil\ if there are no more variables. |
| 2201 | If you create new global variables during the traversal, | ||
| 2202 | the semantics of \verb|nextvar| is undefined. | ||
| 2203 | 2504 | ||
| 2204 | \subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} | 2505 | You may change the \emph{values} of existing global variables during the traversal, |
| 2205 | Receives an argument of any type and | 2506 | but |
| 2206 | converts it to a string in a reasonable format. | 2507 | if you create new global variables, |
| 2207 | For complete control on how numbers are converted, | 2508 | then |
| 2208 | use function \verb|format|. | 2509 | the semantics of \verb|nextvar| is undefined. |
| 2209 | 2510 | ||
| 2210 | \subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print} | 2511 | \subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print} |
| 2211 | Receives any number of arguments, | 2512 | Receives any number of arguments, |
| @@ -2215,77 +2516,11 @@ but only as a quick way to show a value, | |||
| 2215 | for instance for debugging. | 2516 | for instance for debugging. |
| 2216 | See \See{libio} for functions for formatted output. | 2517 | See \See{libio} for functions for formatted output. |
| 2217 | 2518 | ||
| 2218 | \subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} | 2519 | \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} |
| 2219 | Prints its only string argument to \IndexVerb{stderr}. | 2520 | Gets the value of a global variable, |
| 2220 | All error messages in Lua are printed through the function stored | 2521 | without invoking any tag method. |
| 2221 | in the \verb|_ALERT| global variable. | 2522 | The string \verb|name| does not need to be a |
| 2222 | Therefore, a program may assign another function to this variable | 2523 | syntactically valid variable name. |
| 2223 | to change the way such messages are shown | ||
| 2224 | (for instance, for systems without \verb|stderr|). | ||
| 2225 | |||
| 2226 | \subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber} | ||
| 2227 | Receives one argument, | ||
| 2228 | and tries to convert it to a number. | ||
| 2229 | If the argument is already a number or a string convertible | ||
| 2230 | to a number, then \verb|tonumber| returns that number; | ||
| 2231 | otherwise, it returns \nil. | ||
| 2232 | |||
| 2233 | An optional argument specifies the base to interpret the numeral. | ||
| 2234 | The base may be any integer between 2 and 36 inclusive. | ||
| 2235 | In bases above 10, the letter `A' (either upper or lower case) | ||
| 2236 | represents 10, `B' represents 11, and so forth, with `Z' representing 35. | ||
| 2237 | |||
| 2238 | In base 10 (the default), the number may have a decimal part, | ||
| 2239 | as well as an optional exponent part \see{coercion}. | ||
| 2240 | In other bases, only unsigned integers are accepted. | ||
| 2241 | |||
| 2242 | \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} | ||
| 2243 | Allows Lua to test the type of a value. | ||
| 2244 | It receives one argument, and returns its type, coded as a string. | ||
| 2245 | The possible results of this function are | ||
| 2246 | \verb|"nil"| (a string, not the value \nil), | ||
| 2247 | \verb|"number"|, | ||
| 2248 | \verb|"string"|, | ||
| 2249 | \verb|"table"|, | ||
| 2250 | \verb|"function"|, | ||
| 2251 | and \verb|"userdata"|. | ||
| 2252 | |||
| 2253 | \subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag} | ||
| 2254 | Allows Lua to test the tag of a value \see{TypesSec}. | ||
| 2255 | It receives one argument, and returns its tag (a number). | ||
| 2256 | \verb|tag| is equivalent to the API function \verb|lua_tag|. | ||
| 2257 | |||
| 2258 | \subsubsection*{\ff \T{settag (t, tag)}}\Deffunc{settag} | ||
| 2259 | Sets the tag of a given table \see{TypesSec}. | ||
| 2260 | \verb|tag| must be a value created with \verb|newtag| | ||
| 2261 | \see{pdf-newtag}. | ||
| 2262 | It returns the value of its first argument (the table). | ||
| 2263 | For security reasons, | ||
| 2264 | it is impossible to change the tag of a userdata from Lua. | ||
| 2265 | |||
| 2266 | |||
| 2267 | \subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert} | ||
| 2268 | Issues an \emph{``assertion failed!''} error | ||
| 2269 | when its argument is \nil. | ||
| 2270 | This function is equivalent to the following Lua function: | ||
| 2271 | \begin{verbatim} | ||
| 2272 | function assert (v, m) | ||
| 2273 | if not v then | ||
| 2274 | m = m or "" | ||
| 2275 | error("assertion failed! " .. m) | ||
| 2276 | end | ||
| 2277 | end | ||
| 2278 | \end{verbatim} | ||
| 2279 | |||
| 2280 | \subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error} | ||
| 2281 | Calls the error handler and then terminates | ||
| 2282 | the last protected function called | ||
| 2283 | (in~C: \verb|lua_dofile|, \verb|lua_dostring|, | ||
| 2284 | \verb|lua_dobuffer|, or \verb|lua_callfunction|; | ||
| 2285 | in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). | ||
| 2286 | If \verb|message| is \nil, the error handler is not called. | ||
| 2287 | Function \verb|error| never returns. | ||
| 2288 | \verb|error| is equivalent to the API function \verb|lua_error|. | ||
| 2289 | 2524 | ||
| 2290 | \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} | 2525 | \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} |
| 2291 | Gets the real value of \verb|table[index]|, | 2526 | Gets the real value of \verb|table[index]|, |
| @@ -2293,6 +2528,15 @@ without invoking any tag method. | |||
| 2293 | \verb|table| must be a table, | 2528 | \verb|table| must be a table, |
| 2294 | and \verb|index| is any value different from \nil. | 2529 | and \verb|index| is any value different from \nil. |
| 2295 | 2530 | ||
| 2531 | \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} | ||
| 2532 | Sets the named global variable to the given value, | ||
| 2533 | without invoking any tag method. | ||
| 2534 | The string \verb|name| does not need to be a | ||
| 2535 | syntactically valid variable name. | ||
| 2536 | Therefore, | ||
| 2537 | this function can be used to set global variables with strange names like | ||
| 2538 | \verb|"m v 1"| or \verb|"34"|. | ||
| 2539 | |||
| 2296 | \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} | 2540 | \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} |
| 2297 | Sets the real value of \verb|table[index]| to \verb|value|, | 2541 | Sets the real value of \verb|table[index]| to \verb|value|, |
| 2298 | without invoking any tag method. | 2542 | without invoking any tag method. |
| @@ -2300,142 +2544,67 @@ without invoking any tag method. | |||
| 2300 | \verb|index| is any value different from \nil, | 2544 | \verb|index| is any value different from \nil, |
| 2301 | and \verb|value| is any Lua value. | 2545 | and \verb|value| is any Lua value. |
| 2302 | 2546 | ||
| 2303 | \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} | ||
| 2304 | Assigns the given value to a global variable. | ||
| 2305 | The string \verb|name| does not need to be a | ||
| 2306 | syntactically valid variable name. | ||
| 2307 | Therefore, | ||
| 2308 | this function can set global variables with strange names like | ||
| 2309 | \verb|"m v 1"| or \verb|34|. | ||
| 2310 | |||
| 2311 | \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} | 2547 | \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} |
| 2312 | Assigns the given value to a global variable, | 2548 | Sets the named global variable to the given value, |
| 2313 | or calls a tag method. | 2549 | or calls a tag method for ``setgloball''. |
| 2314 | Its full semantics is explained in \See{tag-method}. | 2550 | Its full semantics is explained in \See{tag-method}. |
| 2315 | The string \verb|name| does not need to be a | 2551 | The string \verb|name| does not need to be a |
| 2316 | syntactically valid variable name. | 2552 | syntactically valid variable name. |
| 2317 | 2553 | ||
| 2318 | \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} | 2554 | \subsubsection*{\ff \T{settag (t, tag)}}\Deffunc{settag} |
| 2319 | Retrieves the value of a global variable. | 2555 | Sets the tag of a given table \see{TypesSec}. |
| 2320 | The string \verb|name| does not need to be a | 2556 | \verb|tag| must be a value created with \verb|newtag| |
| 2321 | syntactically valid variable name. | 2557 | \see{pdf-newtag}. |
| 2322 | 2558 | It returns the value of its first argument (the table). | |
| 2323 | \subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal} | 2559 | For the safety of host programs, |
| 2324 | Retrieves the value of a global variable, | 2560 | it is impossible to change the tag of a userdata from Lua. |
| 2325 | or calls a tag method. | ||
| 2326 | Its full semantics is explained in \See{tag-method}. | ||
| 2327 | The string \verb|name| does not need to be a | ||
| 2328 | syntactically valid variable name. | ||
| 2329 | 2561 | ||
| 2330 | \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} | 2562 | \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} |
| 2331 | \Deffunc{settagmethod} | 2563 | \Deffunc{settagmethod} |
| 2332 | Sets a new tag method to the given pair \M{(tag, event)}. | 2564 | Sets a new tag method to the given pair \M{(tag, event)}. |
| 2333 | It returns the old method. | 2565 | It returns the old method. |
| 2334 | If \verb|newmethod| is \nil, | 2566 | If \verb|newmethod| is \nil, |
| 2335 | \verb|settagmethod| restores the default behavior for the given event. | 2567 | then \verb|settagmethod| restores the default behavior for the given event. |
| 2336 | |||
| 2337 | \subsubsection*{\ff \T{gettagmethod (tag, event)}} | ||
| 2338 | \Deffunc{gettagmethod} | ||
| 2339 | Returns the current tag method | ||
| 2340 | for a given pair \M{(tag, event)}. | ||
| 2341 | |||
| 2342 | \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} | ||
| 2343 | \Deffunc{copytagmethods} | ||
| 2344 | Copies all tag methods from one tag to another; | ||
| 2345 | it returns \verb|tagto|. | ||
| 2346 | |||
| 2347 | \subsubsection*{\ff \T{getn (table)}}\Deffunc{getn}\label{getn} | ||
| 2348 | Returns the ``size'' of a table, when seen as a list. | ||
| 2349 | If the table has an \verb|n| field with a numeric value, | ||
| 2350 | this is its ``size''. | ||
| 2351 | Otherwise, the size is the largest numerical index with a non-nil | ||
| 2352 | value in the table. | ||
| 2353 | This function could be defined in Lua: | ||
| 2354 | \begin{verbatim} | ||
| 2355 | function getn (t) | ||
| 2356 | if type(t.n) == 'number' then return t.n end | ||
| 2357 | local max, i = 0, nil | ||
| 2358 | while 1 do | ||
| 2359 | i = next(t, i) | ||
| 2360 | if not i then break end | ||
| 2361 | if type(i) == 'number' and i>max then max=i end | ||
| 2362 | end | ||
| 2363 | return max | ||
| 2364 | end | ||
| 2365 | \end{verbatim} | ||
| 2366 | |||
| 2367 | 2568 | ||
| 2368 | \subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} | 2569 | \subsubsection*{\ff \T{sort (table [, comp])}}\Deffunc{sort} |
| 2369 | Executes the given \verb|function| over all elements of \verb|table|. | 2570 | Sorts table elements in a given order, \emph{in-place}, |
| 2370 | For each element, the function is called with the index and | 2571 | from \verb|table[1]| to \verb|table[n]|, |
| 2371 | respective value as arguments. | 2572 | where \verb|n| is the result of \verb|getn(table)| \see{getn}. |
| 2372 | If the function returns any non-\nil\ value, | 2573 | If \verb|comp| is given, |
| 2373 | the loop is broken, and the value is returned | 2574 | it must be a function that receives two table elements, |
| 2374 | as the final value of \verb|foreach|. | 2575 | and returns true when the first is less than the second |
| 2375 | 2576 | (so that \verb|not comp(a[i+1], a[i])| will be true after the sort). | |
| 2376 | This function could be defined in Lua: | 2577 | If \verb|comp| is not given, |
| 2377 | \begin{verbatim} | 2578 | the standard Lua operator \verb|<| is used instead. |
| 2378 | function foreach (t, f) | ||
| 2379 | local i, v = nil | ||
| 2380 | while 1 do | ||
| 2381 | i, v = next(t, i) | ||
| 2382 | if not i then break end | ||
| 2383 | local res = f(i, v) | ||
| 2384 | if res then return res end | ||
| 2385 | end | ||
| 2386 | end | ||
| 2387 | \end{verbatim} | ||
| 2388 | 2579 | ||
| 2389 | If you create new indices in a table while | 2580 | \subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag} |
| 2390 | traversing it, | 2581 | Allows Lua programs to test the tag of a value \see{TypesSec}. |
| 2391 | the semantics of \verb|foreach| is undefined. | 2582 | It receives one argument, and returns its tag (a number). |
| 2583 | \verb|tag| is equivalent to the API function \verb|lua_tag|. | ||
| 2392 | 2584 | ||
| 2585 | \subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber} | ||
| 2586 | Receives one argument, | ||
| 2587 | and tries to convert it to a number. | ||
| 2588 | If the argument is already a number or a string convertible | ||
| 2589 | to a number, then \verb|tonumber| returns that number; | ||
| 2590 | otherwise, it returns \nil. | ||
| 2393 | 2591 | ||
| 2394 | \subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} | 2592 | An optional argument specifies the base to interpret the numeral. |
| 2395 | Executes the given \verb|function| over the | 2593 | The base may be any integer between 2 and 36, inclusive. |
| 2396 | numerical indices of \verb|table|. | 2594 | In bases above~10, the letter `A' (either upper or lower case) |
| 2397 | For each index, the function is called with the index and | 2595 | represents~10, `B' represents~11, and so forth, with `Z' representing 35. |
| 2398 | respective value as arguments. | ||
| 2399 | Indices are visited in sequential order, | ||
| 2400 | from 1 to \verb|n|, | ||
| 2401 | where \verb|n| is the result of \verb|getn(table)| \see{getn}. | ||
| 2402 | If the function returns any non-\nil\ value, | ||
| 2403 | the loop is broken, and the value is returned | ||
| 2404 | as the final value of \verb|foreachi|. | ||
| 2405 | 2596 | ||
| 2406 | This function could be defined in Lua: | 2597 | In base 10 (the default), the number may have a decimal part, |
| 2407 | \begin{verbatim} | 2598 | as well as an optional exponent part \see{coercion}. |
| 2408 | function foreachi (t, f) | 2599 | In other bases, only unsigned integers are accepted. |
| 2409 | for i=1,getn(t) do | ||
| 2410 | local res = f(i, t[i]) | ||
| 2411 | if res then return res end | ||
| 2412 | end | ||
| 2413 | end | ||
| 2414 | \end{verbatim} | ||
| 2415 | 2600 | ||
| 2416 | \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} | 2601 | \subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} |
| 2417 | Executes \verb|function| over all global variables. | 2602 | Receives an argument of any type and |
| 2418 | For each variable, | 2603 | converts it to a string in a reasonable format. |
| 2419 | the function is called with its name and its value as arguments. | 2604 | For complete control on how numbers are converted, |
| 2420 | If the function returns any non-nil value, | 2605 | use function \verb|format|. |
| 2421 | the loop is broken, and the value is returned | ||
| 2422 | as the final value of \verb|foreachvar|. | ||
| 2423 | 2606 | ||
| 2424 | This function could be defined in Lua: | ||
| 2425 | \begin{verbatim} | ||
| 2426 | function foreachvar (f) | ||
| 2427 | local n, v = nil | ||
| 2428 | while 1 do | ||
| 2429 | n, v = nextvar(n) | ||
| 2430 | if not n then break end | ||
| 2431 | local res = f(n, v) | ||
| 2432 | if res then return res end | ||
| 2433 | end | ||
| 2434 | end | ||
| 2435 | \end{verbatim} | ||
| 2436 | 2607 | ||
| 2437 | If you create new global variables during the traversal, | ||
| 2438 | the semantics of \verb|foreachvar| is undefined. | ||
| 2439 | 2608 | ||
| 2440 | \subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert} | 2609 | \subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert} |
| 2441 | 2610 | ||
| @@ -2445,12 +2614,11 @@ The default value for \verb|pos| is \verb|n+1|, | |||
| 2445 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, | 2614 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, |
| 2446 | so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end | 2615 | so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end |
| 2447 | of table \verb|t|. | 2616 | of table \verb|t|. |
| 2448 | 2617 | This function also sets or increments the field \verb|n| of the table | |
| 2449 | This function also sets or increments the field \verb|n| of the table, | ||
| 2450 | to \verb|n+1|. | 2618 | to \verb|n+1|. |
| 2451 | 2619 | ||
| 2452 | This function is equivalent to the following Lua function, | 2620 | This function is equivalent to the following Lua function, |
| 2453 | except that the table accesses are all raw (that is, without tag methods): | 2621 | except that the table accesses are all \emph{raw} (that is, without tag methods): |
| 2454 | \begin{verbatim} | 2622 | \begin{verbatim} |
| 2455 | function tinsert (t, ...) | 2623 | function tinsert (t, ...) |
| 2456 | local pos, value | 2624 | local pos, value |
| @@ -2473,16 +2641,15 @@ except that the table accesses are all raw (that is, without tag methods): | |||
| 2473 | Removes from \verb|table| the element at position \verb|pos|, | 2641 | Removes from \verb|table| the element at position \verb|pos|, |
| 2474 | shifting other elements to close the space, if necessary. | 2642 | shifting other elements to close the space, if necessary. |
| 2475 | Returns the value of the removed element. | 2643 | Returns the value of the removed element. |
| 2476 | The default value for \verb|pos| is \verb|n| | 2644 | The default value for \verb|pos| is \verb|n|, |
| 2477 | (where \verb|n| is the result of \verb|getn(table)| \see{getn}), | 2645 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, |
| 2478 | so that a call \verb|tremove(t)| removes the last element | 2646 | so that a call \verb|tremove(t)| removes the last element |
| 2479 | of table \verb|t|. | 2647 | of table \verb|t|. |
| 2480 | 2648 | This function also sets or decrements the field \verb|n| of the table | |
| 2481 | This function also sets or decrements the field \verb|n| of the table, | ||
| 2482 | to \verb|n-1|. | 2649 | to \verb|n-1|. |
| 2483 | 2650 | ||
| 2484 | This function is equivalent to the following Lua function, | 2651 | This function is equivalent to the following Lua function, |
| 2485 | except that the table accesses are all raw (that is, without tag methods): | 2652 | except that the table accesses are all \emph{raw} (that is, without tag methods): |
| 2486 | \begin{verbatim} | 2653 | \begin{verbatim} |
| 2487 | function tremove (t, pos) | 2654 | function tremove (t, pos) |
| 2488 | local n = getn(t) | 2655 | local n = getn(t) |
| @@ -2498,16 +2665,17 @@ except that the table accesses are all raw (that is, without tag methods): | |||
| 2498 | end | 2665 | end |
| 2499 | \end{verbatim} | 2666 | \end{verbatim} |
| 2500 | 2667 | ||
| 2501 | \subsubsection*{\ff \T{sort (table [, comp])}}\Deffunc{sort} | 2668 | \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} |
| 2502 | Sorts table elements in a given order, \emph{in-place}, | 2669 | Allows Lua programs to test the type of a value. |
| 2503 | from \verb|table[1]| to \verb|table[n]|, | 2670 | It receives one argument, and returns its type, coded as a string. |
| 2504 | where \verb|n| is the result of \verb|getn(table)| \see{getn}. | 2671 | The possible results of this function are |
| 2505 | If \verb|comp| is given, | 2672 | \verb|"nil"| (a string, not the value \nil), |
| 2506 | it must be a function that receives two table elements, | 2673 | \verb|"number"|, |
| 2507 | and returns true when the first is less than the second | 2674 | \verb|"string"|, |
| 2508 | (so that \verb|not comp(a[i+1], a[i])| will be true after the sort). | 2675 | \verb|"table"|, |
| 2509 | If \verb|comp| is not given, | 2676 | \verb|"function"|, |
| 2510 | the standard Lua operator \verb|<| is used instead. | 2677 | and \verb|"userdata"|. |
| 2678 | \verb|type| is equivalent to the API function \verb|lua_type|. | ||
| 2511 | 2679 | ||
| 2512 | 2680 | ||
| 2513 | \subsection{String Manipulation} | 2681 | \subsection{String Manipulation} |
| @@ -2516,6 +2684,26 @@ such as finding and extracting substrings and pattern matching. | |||
| 2516 | When indexing a string, the first character is at position~1 | 2684 | When indexing a string, the first character is at position~1 |
| 2517 | (not at~0, as in C). | 2685 | (not at~0, as in C). |
| 2518 | 2686 | ||
| 2687 | \subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte} | ||
| 2688 | Returns the internal numerical code of the character \verb|s[i]|. | ||
| 2689 | If \verb|i| is absent, then it is assumed to be 1. | ||
| 2690 | If \verb|i| is negative, | ||
| 2691 | it is replaced by the length of the string minus its | ||
| 2692 | absolute value plus 1. | ||
| 2693 | Therefore, \Math{-1} points to the last character of \verb|s|. | ||
| 2694 | |||
| 2695 | \NOTE | ||
| 2696 | \emph{numerical codes are not necessarily portable across platforms}. | ||
| 2697 | |||
| 2698 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar} | ||
| 2699 | Receives 0 or more integers. | ||
| 2700 | Returns a string with length equal to the number of arguments, | ||
| 2701 | wherein each character has the internal numerical code equal | ||
| 2702 | to its correspondent argument. | ||
| 2703 | |||
| 2704 | \NOTE | ||
| 2705 | \emph{numerical codes are not necessarily portable across platforms}. | ||
| 2706 | |||
| 2519 | \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} | 2707 | \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} |
| 2520 | \Deffunc{strfind} | 2708 | \Deffunc{strfind} |
| 2521 | Looks for the first \emph{match} of | 2709 | Looks for the first \emph{match} of |
| @@ -2523,7 +2711,7 @@ Looks for the first \emph{match} of | |||
| 2523 | If it finds one, then it returns the indices on \verb|str| | 2711 | If it finds one, then it returns the indices on \verb|str| |
| 2524 | where this occurrence starts and ends; | 2712 | where this occurrence starts and ends; |
| 2525 | otherwise, it returns \nil. | 2713 | otherwise, it returns \nil. |
| 2526 | If the pattern specifies captures, | 2714 | If the pattern specifies captures (see \verb|gsub| below), |
| 2527 | the captured strings are returned as extra results. | 2715 | the captured strings are returned as extra results. |
| 2528 | A third optional numerical argument specifies where to start the search; | 2716 | A third optional numerical argument specifies where to start the search; |
| 2529 | its default value is 1. | 2717 | its default value is 1. |
| @@ -2538,6 +2726,19 @@ with no characters in \verb|pattern| being considered ``magic''. | |||
| 2538 | 2726 | ||
| 2539 | \subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} | 2727 | \subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} |
| 2540 | Receives a string and returns its length. | 2728 | Receives a string and returns its length. |
| 2729 | The empty string \verb|""| has length 0. | ||
| 2730 | Embedded zeros are counted. | ||
| 2731 | |||
| 2732 | \subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower} | ||
| 2733 | Receives a string and returns a copy of that string with all | ||
| 2734 | upper case letters changed to lower case. | ||
| 2735 | All other characters are left unchanged. | ||
| 2736 | The definition of what is an upper-case | ||
| 2737 | letter depends on the current locale. | ||
| 2738 | |||
| 2739 | \subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep} | ||
| 2740 | Returns a string that is the concatenation of \verb|n| copies of | ||
| 2741 | the string \verb|s|. | ||
| 2541 | 2742 | ||
| 2542 | \subsubsection*{\ff \T{strsub (s, i [, j])}}\Deffunc{strsub} | 2743 | \subsubsection*{\ff \T{strsub (s, i [, j])}}\Deffunc{strsub} |
| 2543 | Returns another string, which is a substring of \verb|s|, | 2744 | Returns another string, which is a substring of \verb|s|, |
| @@ -2555,13 +2756,6 @@ with length \verb|j|, | |||
| 2555 | and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| | 2756 | and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| |
| 2556 | with length \verb|i|. | 2757 | with length \verb|i|. |
| 2557 | 2758 | ||
| 2558 | \subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower} | ||
| 2559 | Receives a string and returns a copy of that string with all | ||
| 2560 | upper case letters changed to lower case. | ||
| 2561 | All other characters are left unchanged. | ||
| 2562 | The definition of what is an upper case | ||
| 2563 | letter depends on the current locale. | ||
| 2564 | |||
| 2565 | \subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper} | 2759 | \subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper} |
| 2566 | Receives a string and returns a copy of that string with all | 2760 | Receives a string and returns a copy of that string with all |
| 2567 | lower case letters changed to upper case. | 2761 | lower case letters changed to upper case. |
| @@ -2569,42 +2763,20 @@ All other characters are left unchanged. | |||
| 2569 | The definition of what is a lower case | 2763 | The definition of what is a lower case |
| 2570 | letter depends on the current locale. | 2764 | letter depends on the current locale. |
| 2571 | 2765 | ||
| 2572 | \subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep} | ||
| 2573 | Returns a string that is the concatenation of \verb|n| copies of | ||
| 2574 | the string \verb|s|. | ||
| 2575 | |||
| 2576 | \subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte} | ||
| 2577 | Returns the internal numerical code of the character \verb|s[i]|. | ||
| 2578 | If \verb|i| is absent, then it is assumed to be 1. | ||
| 2579 | If \verb|i| is negative, | ||
| 2580 | it is replaced by the length of the string minus its | ||
| 2581 | absolute value plus 1. | ||
| 2582 | Therefore, \Math{-1} points to the last character of \verb|s|. | ||
| 2583 | |||
| 2584 | Note that numerical codes are not necessarily portable across platforms. | ||
| 2585 | |||
| 2586 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar} | ||
| 2587 | Receives 0 or more integers. | ||
| 2588 | Returns a string with length equal to the number of arguments, | ||
| 2589 | wherein each character has the internal numerical code equal | ||
| 2590 | to its correspondent argument. | ||
| 2591 | |||
| 2592 | Note that numerical codes are not necessarily portable across platforms. | ||
| 2593 | |||
| 2594 | \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format} | 2766 | \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format} |
| 2595 | \label{format} | 2767 | \label{format} |
| 2596 | Returns a formatted version of its variable number of arguments | 2768 | Returns a formatted version of its variable number of arguments |
| 2597 | following the description given in its first argument (which must be a string). | 2769 | following the description given in its first argument (which must be a string). |
| 2598 | The format string follows the same rules as the \verb|printf| family of | 2770 | The format string follows the same rules as the \verb|printf| family of |
| 2599 | standard C functions. | 2771 | standard C~functions. |
| 2600 | The only differences are that the options/modifiers | 2772 | The only differences are that the options/modifiers |
| 2601 | \verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|, | 2773 | \verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|, |
| 2602 | and \verb|h| are not supported, | 2774 | and \verb|h| are not supported, |
| 2603 | and there is an extra option, \verb|q|. | 2775 | and there is an extra option, \verb|q|. |
| 2604 | This option formats a string in a form suitable to be safely read | 2776 | The \verb|q| option formats a string in a form suitable to be safely read |
| 2605 | back by the Lua interpreter: | 2777 | back by the Lua interpreter: |
| 2606 | The string is written between double quotes, | 2778 | The string is written between double quotes, |
| 2607 | and all double quotes, returns and backslashes in the string | 2779 | and all double quotes, returns, and backslashes in the string |
| 2608 | are correctly escaped when written. | 2780 | are correctly escaped when written. |
| 2609 | For instance, the call | 2781 | For instance, the call |
| 2610 | \begin{verbatim} | 2782 | \begin{verbatim} |
| @@ -2616,7 +2788,7 @@ will produce the string: | |||
| 2616 | new line" | 2788 | new line" |
| 2617 | \end{verbatim} | 2789 | \end{verbatim} |
| 2618 | 2790 | ||
| 2619 | Conversions can be applied to the n-th argument in the argument list, | 2791 | Conversions can be applied to the \M{n}-th argument in the argument list, |
| 2620 | rather than the next unused argument. | 2792 | rather than the next unused argument. |
| 2621 | In this case, the conversion character \verb|%| is replaced | 2793 | In this case, the conversion character \verb|%| is replaced |
| 2622 | by the sequence \verb|%d$|, where \verb|d| is a | 2794 | by the sequence \verb|%d$|, where \verb|d| is a |
| @@ -2635,13 +2807,14 @@ the appropriate format string. | |||
| 2635 | For example, \verb|"%*g"| can be simulated with | 2807 | For example, \verb|"%*g"| can be simulated with |
| 2636 | \verb|"%"..width.."g"|. | 2808 | \verb|"%"..width.."g"|. |
| 2637 | 2809 | ||
| 2638 | \emph{Note: function \T{format} can only be used with strings that do not | 2810 | \NOTE |
| 2639 | contain zeros (0).} | 2811 | \emph{Neither the format string nor the string values to be formatted with |
| 2812 | \T{format} can contain embedded zeros.} | ||
| 2640 | 2813 | ||
| 2641 | \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} | 2814 | \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} |
| 2642 | \Deffunc{gsub} | 2815 | \Deffunc{gsub} |
| 2643 | Returns a copy of \verb|s|, | 2816 | Returns a copy of \verb|s|, |
| 2644 | where all occurrences of the pattern \verb|pat| have been | 2817 | in which all occurrences of the pattern \verb|pat| have been |
| 2645 | replaced by a replacement string specified by \verb|repl|. | 2818 | replaced by a replacement string specified by \verb|repl|. |
| 2646 | This function also returns, as a second value, | 2819 | This function also returns, as a second value, |
| 2647 | the total number of substitutions made. | 2820 | the total number of substitutions made. |
| @@ -2649,7 +2822,7 @@ the total number of substitutions made. | |||
| 2649 | If \verb|repl| is a string, then its value is used for replacement. | 2822 | If \verb|repl| is a string, then its value is used for replacement. |
| 2650 | Any sequence in \verb|repl| of the form \verb|%n| | 2823 | Any sequence in \verb|repl| of the form \verb|%n| |
| 2651 | with \verb|n| between 1 and 9 | 2824 | with \verb|n| between 1 and 9 |
| 2652 | stands for the value of the n-th captured substring. | 2825 | stands for the value of the \M{n}-th captured substring. |
| 2653 | 2826 | ||
| 2654 | If \verb|repl| is a function, then this function is called every time a | 2827 | If \verb|repl| is a function, then this function is called every time a |
| 2655 | match occurs, with all captured substrings passed as arguments, | 2828 | match occurs, with all captured substrings passed as arguments, |
| @@ -2658,7 +2831,7 @@ If the value returned by this function is a string, | |||
| 2658 | then it is used as the replacement string; | 2831 | then it is used as the replacement string; |
| 2659 | otherwise, the replacement string is the empty string. | 2832 | otherwise, the replacement string is the empty string. |
| 2660 | 2833 | ||
| 2661 | A last optional parameter \verb|n| limits | 2834 | The last, optional parameter \verb|n| limits |
| 2662 | the maximum number of substitutions to occur. | 2835 | the maximum number of substitutions to occur. |
| 2663 | For instance, when \verb|n| is 1 only the first occurrence of | 2836 | For instance, when \verb|n| is 1 only the first occurrence of |
| 2664 | \verb|pat| is replaced. | 2837 | \verb|pat| is replaced. |
| @@ -2713,18 +2886,19 @@ The following combinations are allowed in describing a character class: | |||
| 2713 | \item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character) --- | 2886 | \item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character) --- |
| 2714 | represents the character \M{x}. | 2887 | represents the character \M{x}. |
| 2715 | This is the standard way to escape the magic characters \verb|()%.[]*-?|. | 2888 | This is the standard way to escape the magic characters \verb|()%.[]*-?|. |
| 2716 | It is strongly recommended that any control character (even the non magic), | 2889 | It is strongly recommended that any control character (even the non magic) |
| 2717 | when used to represent itself in a pattern, should be preceded by a \verb|%|. | 2890 | should be preceded by a \verb|%| |
| 2891 | when used to represent itself in a pattern, | ||
| 2718 | 2892 | ||
| 2719 | \item[\T{[char-set]}] --- | 2893 | \item[\T{[char-set]}] --- |
| 2720 | Represents the class which is the union of all | 2894 | represents the class which is the union of all |
| 2721 | characters in char-set. | 2895 | characters in char-set. |
| 2722 | A range of characters may be specified by | 2896 | A range of characters may be specified by |
| 2723 | separating the end characters of the range with a \verb|-|. | 2897 | separating the end characters of the range with a \verb|-|. |
| 2724 | All classes \verb|%|\emph{x} described above can also be used as | 2898 | All classes \verb|%|\emph{x} described above may also be used as |
| 2725 | components in a char-set. | 2899 | components in a char-set. |
| 2726 | All other characters in char-set represent themselves. | 2900 | All other characters in char-set represent themselves. |
| 2727 | E.g., \verb|[%w_]| (or \verb|[_%w]|) | 2901 | For example, \verb|[%w_]| (or \verb|[_%w]|) |
| 2728 | represents all alphanumeric characters plus the underscore, | 2902 | represents all alphanumeric characters plus the underscore, |
| 2729 | \verb|[0-7]| represents the octal digits, | 2903 | \verb|[0-7]| represents the octal digits, |
| 2730 | and \verb|[0-7%l%-]| represents the octal digits plus | 2904 | and \verb|[0-7%l%-]| represents the octal digits plus |
| @@ -2739,7 +2913,7 @@ represents the complement of char-set, | |||
| 2739 | where char-set is interpreted as above. | 2913 | where char-set is interpreted as above. |
| 2740 | \end{description} | 2914 | \end{description} |
| 2741 | For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), | 2915 | For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), |
| 2742 | the correspondent upper-case letter represents the complement of the class. | 2916 | the corresponding upper-case letter represents the complement of the class. |
| 2743 | For instance, \verb|%S| represents all non-space characters. | 2917 | For instance, \verb|%S| represents all non-space characters. |
| 2744 | 2918 | ||
| 2745 | The definitions of letter, space, etc. depend on the current locale. | 2919 | The definitions of letter, space, etc. depend on the current locale. |
| @@ -2770,14 +2944,14 @@ a single character class followed by \verb|?|, | |||
| 2770 | which matches 0 or 1 occurrence of a character in the class; | 2944 | which matches 0 or 1 occurrence of a character in the class; |
| 2771 | \item | 2945 | \item |
| 2772 | \T{\%\M{n}}, for \M{n} between 1 and 9; | 2946 | \T{\%\M{n}}, for \M{n} between 1 and 9; |
| 2773 | such item matches a sub-string equal to the n-th captured string | 2947 | such item matches a sub-string equal to the \M{n}-th captured string |
| 2774 | (see below); | 2948 | (see below); |
| 2775 | \item | 2949 | \item |
| 2776 | \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; | 2950 | \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; |
| 2777 | such item matches strings that start with \M{x}, end with \M{y}, | 2951 | such item matches strings that start with~\M{x}, end with~\M{y}, |
| 2778 | and where the \M{x} and \M{y} are \emph{balanced}. | 2952 | and where the \M{x} and \M{y} are \emph{balanced}. |
| 2779 | That means that, if one reads the string from left to write, | 2953 | This means that, if one reads the string from left to right, |
| 2780 | counting plus 1 for an \M{x} and minus 1 for a \M{y}, | 2954 | counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y}, |
| 2781 | the ending \M{y} is the first where the count reaches 0. | 2955 | the ending \M{y} is the first where the count reaches 0. |
| 2782 | For instance, the item \verb|%b()| matches expressions with | 2956 | For instance, the item \verb|%b()| matches expressions with |
| 2783 | balanced parentheses. | 2957 | balanced parentheses. |
| @@ -2789,9 +2963,11 @@ A \verb|^| at the beginning of a pattern anchors the match at the | |||
| 2789 | beginning of the subject string. | 2963 | beginning of the subject string. |
| 2790 | A \verb|$| at the end of a pattern anchors the match at the | 2964 | A \verb|$| at the end of a pattern anchors the match at the |
| 2791 | end of the subject string. | 2965 | end of the subject string. |
| 2966 | At other positions, | ||
| 2967 | \verb|^| and \verb|$| have no special meaning and represent themselves. | ||
| 2792 | 2968 | ||
| 2793 | \paragraph{Captures:} | 2969 | \paragraph{Captures:} |
| 2794 | a pattern may contain sub-patterns enclosed in parentheses, | 2970 | A pattern may contain sub-patterns enclosed in parentheses, |
| 2795 | that describe \Def{captures}. | 2971 | that describe \Def{captures}. |
| 2796 | When a match succeeds, the sub-strings of the subject string | 2972 | When a match succeeds, the sub-strings of the subject string |
| 2797 | that match captures are stored (\emph{captured}) for future use. | 2973 | that match captures are stored (\emph{captured}) for future use. |
| @@ -2802,8 +2978,9 @@ stored as the first capture (and therefore has number~1); | |||
| 2802 | the character matching \verb|.| is captured with number~2, | 2978 | the character matching \verb|.| is captured with number~2, |
| 2803 | and the part matching \verb|%s*| has number~3. | 2979 | and the part matching \verb|%s*| has number~3. |
| 2804 | 2980 | ||
| 2805 | {\em Note: A pattern cannot contain zeros (\verb|'\0'|). | 2981 | \NOTE |
| 2806 | Use \verb|'%z'| instead.} | 2982 | {\em A pattern cannot contain embedded zeros. |
| 2983 | Use \verb|%z| instead.} | ||
| 2807 | 2984 | ||
| 2808 | 2985 | ||
| 2809 | \subsection{Mathematical Functions} \label{mathlib} | 2986 | \subsection{Mathematical Functions} \label{mathlib} |
| @@ -2820,13 +2997,13 @@ The library provides the following functions: | |||
| 2820 | \Deffunc{frexp}\Deffunc{ldexp} | 2997 | \Deffunc{frexp}\Deffunc{ldexp} |
| 2821 | \Deffunc{random}\Deffunc{randomseed} | 2998 | \Deffunc{random}\Deffunc{randomseed} |
| 2822 | \begin{verbatim} | 2999 | \begin{verbatim} |
| 2823 | abs acos asin atan atan2 ceil cos deg floor log log10 | 3000 | abs acos asin atan atan2 ceil cos deg floor log log10 |
| 2824 | max min mod rad sin sqrt tan frexp ldexp | 3001 | max min mod rad sin sqrt tan frexp ldexp |
| 2825 | random randomseed | 3002 | random randomseed |
| 2826 | \end{verbatim} | 3003 | \end{verbatim} |
| 2827 | plus a global variable \IndexVerb{PI}. | 3004 | plus a global variable \IndexVerb{PI}. |
| 2828 | Most of them | 3005 | Most of them |
| 2829 | are only interfaces to the homonymous functions in the C library, | 3006 | are only interfaces to the homonymous functions in the C~library, |
| 2830 | except that, for the trigonometric functions, | 3007 | except that, for the trigonometric functions, |
| 2831 | all angles are expressed in \emph{degrees}, not radians. | 3008 | all angles are expressed in \emph{degrees}, not radians. |
| 2832 | Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert | 3009 | Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert |
| @@ -2835,11 +3012,12 @@ between radians and degrees. | |||
| 2835 | The function \verb|max| returns the maximum | 3012 | The function \verb|max| returns the maximum |
| 2836 | value of its numeric arguments. | 3013 | value of its numeric arguments. |
| 2837 | Similarly, \verb|min| computes the minimum. | 3014 | Similarly, \verb|min| computes the minimum. |
| 2838 | Both can be used with 1, 2 or more arguments. | 3015 | Both can be used with 1, 2, or more arguments. |
| 2839 | 3016 | ||
| 2840 | The functions \verb|random| and \verb|randomseed| are interfaces to | 3017 | The functions \verb|random| and \verb|randomseed| are interfaces to |
| 2841 | the simple random generator functions \verb|rand| and \verb|srand|, | 3018 | the simple random generator functions \verb|rand| and \verb|srand|, |
| 2842 | provided by ANSI C. | 3019 | provided by ANSI C. |
| 3020 | (No guarantees can be given for their statistical properties.) | ||
| 2843 | The function \verb|random|, when called without arguments, | 3021 | The function \verb|random|, when called without arguments, |
| 2844 | returns a pseudo-random real number in the range \Math{[0,1)}. | 3022 | returns a pseudo-random real number in the range \Math{[0,1)}. |
| 2845 | When called with a number \Math{n}, | 3023 | When called with a number \Math{n}, |
| @@ -2855,7 +3033,7 @@ over two \Def{file handles}, one for reading and one for writing. | |||
| 2855 | These handles are stored in two Lua global variables, | 3033 | These handles are stored in two Lua global variables, |
| 2856 | called \verb|_INPUT| and \verb|_OUTPUT|. | 3034 | called \verb|_INPUT| and \verb|_OUTPUT|. |
| 2857 | The global variables | 3035 | The global variables |
| 2858 | \verb|_STDIN|, \verb|_STDOUT| and \verb|_STDERR| | 3036 | \verb|_STDIN|, \verb|_STDOUT|, and \verb|_STDERR| |
| 2859 | are initialized with file descriptors for | 3037 | are initialized with file descriptors for |
| 2860 | \verb|stdin|, \verb|stdout| and \verb|stderr|. | 3038 | \verb|stdin|, \verb|stdout| and \verb|stderr|. |
| 2861 | Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|. | 3039 | Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|. |
| @@ -2877,7 +3055,7 @@ It returns a new file handle, | |||
| 2877 | or, in case of errors, \nil\ plus a string describing the error. | 3055 | or, in case of errors, \nil\ plus a string describing the error. |
| 2878 | This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. | 3056 | This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. |
| 2879 | 3057 | ||
| 2880 | The string mode can be any of the following: | 3058 | The \verb|mode| string can be any of the following: |
| 2881 | \begin{description} | 3059 | \begin{description} |
| 2882 | \item[``r''] read mode; | 3060 | \item[``r''] read mode; |
| 2883 | \item[``w''] write mode; | 3061 | \item[``w''] write mode; |
| @@ -2887,8 +3065,9 @@ The string mode can be any of the following: | |||
| 2887 | \item[``a+''] append update mode, previous data is preserved, | 3065 | \item[``a+''] append update mode, previous data is preserved, |
| 2888 | writing is only allowed at the end of file. | 3066 | writing is only allowed at the end of file. |
| 2889 | \end{description} | 3067 | \end{description} |
| 2890 | The string mode may also have a \verb|b| at the end, | 3068 | The \verb|mode| string may also have a \verb|b| at the end, |
| 2891 | which is needed in some systems to open the file in binary mode. | 3069 | which is needed in some systems to open the file in binary mode. |
| 3070 | This string is exactlty what is used in the standard~C function \verb|fopen|. | ||
| 2892 | 3071 | ||
| 2893 | \subsubsection*{\ff \T{closefile (handle)}}\Deffunc{closefile} | 3072 | \subsubsection*{\ff \T{closefile (handle)}}\Deffunc{closefile} |
| 2894 | 3073 | ||
| @@ -2972,7 +3151,7 @@ plus a string describing the error. | |||
| 2972 | 3151 | ||
| 2973 | Saves any written data to the given file. | 3152 | Saves any written data to the given file. |
| 2974 | If \verb|filehandle| is not specified, | 3153 | If \verb|filehandle| is not specified, |
| 2975 | flushes all open files. | 3154 | then \verb|flush| flushes all open files. |
| 2976 | If this function fails, it returns \nil, | 3155 | If this function fails, it returns \nil, |
| 2977 | plus a string describing the error. | 3156 | plus a string describing the error. |
| 2978 | 3157 | ||
| @@ -3016,7 +3195,7 @@ according to the given formats, which specify what to read. | |||
| 3016 | For each format, | 3195 | For each format, |
| 3017 | the function returns a string (or a number) with the characters read, | 3196 | the function returns a string (or a number) with the characters read, |
| 3018 | or \nil\ if it cannot read data with the specified format. | 3197 | or \nil\ if it cannot read data with the specified format. |
| 3019 | When called without patterns, | 3198 | When called without formats, |
| 3020 | it uses a default format that reads the next line | 3199 | it uses a default format that reads the next line |
| 3021 | (see below). | 3200 | (see below). |
| 3022 | 3201 | ||
| @@ -3032,6 +3211,8 @@ On end of file, it returns the empty string. | |||
| 3032 | \item[``*w''] reads the next word | 3211 | \item[``*w''] reads the next word |
| 3033 | (maximal sequence of non white-space characters), | 3212 | (maximal sequence of non white-space characters), |
| 3034 | skipping spaces if necessary, or \nil\ on end of file. | 3213 | skipping spaces if necessary, or \nil\ on end of file. |
| 3214 | \item[\emph{number}] reads a string with up to that number of characters, | ||
| 3215 | or \nil\ on end of file. | ||
| 3035 | \end{description} | 3216 | \end{description} |
| 3036 | 3217 | ||
| 3037 | \subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write} | 3218 | \subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write} |
| @@ -3049,7 +3230,7 @@ plus a string describing the error. | |||
| 3049 | 3230 | ||
| 3050 | Returns a string containing date and time | 3231 | Returns a string containing date and time |
| 3051 | formatted according to the given string \verb|format|, | 3232 | formatted according to the given string \verb|format|, |
| 3052 | following the same rules of the ANSI C function \verb|strftime|. | 3233 | following the same rules of the ANSI~C function \verb|strftime|. |
| 3053 | When called without arguments, | 3234 | When called without arguments, |
| 3054 | it returns a reasonable date and time representation that depends on | 3235 | it returns a reasonable date and time representation that depends on |
| 3055 | the host system and on the current locale. | 3236 | the host system and on the current locale. |
| @@ -3061,7 +3242,7 @@ used by the program, in seconds. | |||
| 3061 | 3242 | ||
| 3062 | \subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} | 3243 | \subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} |
| 3063 | 3244 | ||
| 3064 | Calls the C function \verb|exit|, | 3245 | Calls the C~function \verb|exit|, |
| 3065 | with an optional \verb|code|, | 3246 | with an optional \verb|code|, |
| 3066 | to terminate the program. | 3247 | to terminate the program. |
| 3067 | The default value for \verb|code| is the success code. | 3248 | The default value for \verb|code| is the success code. |
| @@ -3073,13 +3254,13 @@ or \nil\ if the variable is not defined. | |||
| 3073 | 3254 | ||
| 3074 | \subsubsection*{\ff \T{execute (command)}}\Deffunc{execute} | 3255 | \subsubsection*{\ff \T{execute (command)}}\Deffunc{execute} |
| 3075 | 3256 | ||
| 3076 | This function is equivalent to the C function \verb|system|. | 3257 | This function is equivalent to the C~function \verb|system|. |
| 3077 | It passes \verb|command| to be executed by an operating system shell. | 3258 | It passes \verb|command| to be executed by an operating system shell. |
| 3078 | It returns a status code, which is system-dependent. | 3259 | It returns a status code, which is system-dependent. |
| 3079 | 3260 | ||
| 3080 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} | 3261 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} |
| 3081 | 3262 | ||
| 3082 | This function is an interface to the ANSI C function \verb|setlocale|. | 3263 | This function is an interface to the ANSI~C function \verb|setlocale|. |
| 3083 | \verb|locale| is a string specifying a locale; | 3264 | \verb|locale| is a string specifying a locale; |
| 3084 | \verb|category| is an optional string describing which category to change: | 3265 | \verb|category| is an optional string describing which category to change: |
| 3085 | \verb|"all"|, \verb|"collate"|, \verb|"ctype"|, | 3266 | \verb|"all"|, \verb|"collate"|, \verb|"ctype"|, |
| @@ -3089,7 +3270,7 @@ The function returns the name of the new locale, | |||
| 3089 | or \nil\ if the request cannot be honored. | 3270 | or \nil\ if the request cannot be honored. |
| 3090 | 3271 | ||
| 3091 | 3272 | ||
| 3092 | \section{The Debugger Interface} \label{debugI} | 3273 | \section{The Debug Interface} \label{debugI} |
| 3093 | 3274 | ||
| 3094 | Lua has no built-in debugging facilities. | 3275 | Lua has no built-in debugging facilities. |
| 3095 | Instead, it offers a special interface, | 3276 | Instead, it offers a special interface, |
| @@ -3097,7 +3278,8 @@ by means of functions and \emph{hooks}, | |||
| 3097 | which allows the construction of different | 3278 | which allows the construction of different |
| 3098 | kinds of debuggers, profilers, and other tools | 3279 | kinds of debuggers, profilers, and other tools |
| 3099 | that need ``inside information'' from the interpreter. | 3280 | that need ``inside information'' from the interpreter. |
| 3100 | This interface is declared in the header file \verb|luadebug.h|. | 3281 | This interface is declared in the header file \verb|luadebug.h|, |
| 3282 | and has \emph{no} single-state variant. | ||
| 3101 | 3283 | ||
| 3102 | \subsection{Stack and Function Information} | 3284 | \subsection{Stack and Function Information} |
| 3103 | 3285 | ||
| @@ -3106,23 +3288,24 @@ The main function to get information about the interpreter stack is | |||
| 3106 | \begin{verbatim} | 3288 | \begin{verbatim} |
| 3107 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); | 3289 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); |
| 3108 | \end{verbatim} | 3290 | \end{verbatim} |
| 3109 | It fills parts of a structure (\verb|lua_Debug|) with | 3291 | It fills parts of a \verb|lua_Debug| structure with |
| 3110 | an identification of the \emph{activation record} | 3292 | an identification of the \emph{activation record} |
| 3111 | of the function executing at a given level. | 3293 | of the function executing at a given level. |
| 3112 | Level~0 is the current running function, | 3294 | Level~0 is the current running function, |
| 3113 | while level \Math{n+1} is the function that has called level \Math{n}. | 3295 | whereas level \Math{n+1} is the function that has called level \Math{n}. |
| 3114 | Usually, \verb|lua_getstack| returns 1; | 3296 | Usually, \verb|lua_getstack| returns 1; |
| 3115 | when called with a level greater than the stack depth, | 3297 | when called with a level greater than the stack depth, |
| 3116 | it returns 0. | 3298 | it returns 0. |
| 3117 | 3299 | ||
| 3118 | The structure \verb|lua_Debug| is used to carry different informations | 3300 | \Deffunc{lua_Debug} |
| 3119 | about an active function: \Deffunc{lua_Debug} | 3301 | The structure \verb|lua_Debug| is used to carry different pieces of information |
| 3302 | about an active function: | ||
| 3120 | \begin{verbatim} | 3303 | \begin{verbatim} |
| 3121 | struct lua_Debug { | 3304 | struct lua_Debug { |
| 3122 | const char *event; /* `call', `return' */ | 3305 | const char *event; /* "call", "return" */ |
| 3123 | const char *source; /* (S) */ | 3306 | const char *source; /* (S) */ |
| 3124 | int linedefined; /* (S) */ | 3307 | int linedefined; /* (S) */ |
| 3125 | const char *what; /* (S) `Lua' function, `C' function, Lua `main' */ | 3308 | const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ |
| 3126 | int currentline; /* (l) */ | 3309 | int currentline; /* (l) */ |
| 3127 | const char *name; /* (n) */ | 3310 | const char *name; /* (n) */ |
| 3128 | const char *namewhat; /* (n) global, tag method, local, field */ | 3311 | const char *namewhat; /* (n) global, tag method, local, field */ |
| @@ -3135,15 +3318,18 @@ struct lua_Debug { | |||
| 3135 | The \verb|lua_getstack| function fills only the private part | 3318 | The \verb|lua_getstack| function fills only the private part |
| 3136 | of this structure, for future use. | 3319 | of this structure, for future use. |
| 3137 | To fill in the other fields of \verb|lua_Debug| with useful information, | 3320 | To fill in the other fields of \verb|lua_Debug| with useful information, |
| 3138 | you call \Deffunc{lua_getinfo} | 3321 | call \Deffunc{lua_getinfo} |
| 3139 | \begin{verbatim} | 3322 | \begin{verbatim} |
| 3140 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); | 3323 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); |
| 3141 | \end{verbatim} | 3324 | \end{verbatim} |
| 3142 | Each character in string \verb|what| selects some fields to be filled, | 3325 | This function returns 0 on error |
| 3143 | as indicated by the letter in parentheses in the structure definition; | 3326 | (e.g., an invalid option in \verb|what|). |
| 3327 | Each character in the string \verb|what| | ||
| 3328 | selects some fields of \verb|ar| to be filled, | ||
| 3329 | as indicated by the letter in parentheses in the definition of \verb|lua_Debug|; | ||
| 3144 | that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|, | 3330 | that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|, |
| 3145 | and \verb|l| fills the field \verb|currentline|, etc. | 3331 | and \verb|l| fills the field \verb|currentline|, etc. |
| 3146 | Next we describe each field: | 3332 | We describe each field below: |
| 3147 | \begin{description} | 3333 | \begin{description} |
| 3148 | 3334 | ||
| 3149 | \item[source] | 3335 | \item[source] |
| @@ -3156,7 +3342,7 @@ if the function was defined in a file, | |||
| 3156 | the line number where starts the definition of the function. | 3342 | the line number where starts the definition of the function. |
| 3157 | 3343 | ||
| 3158 | \item[what] the string \verb|"Lua"| if this is a Lua function, | 3344 | \item[what] the string \verb|"Lua"| if this is a Lua function, |
| 3159 | \verb|"C"| if this is a C function, | 3345 | \verb|"C"| if this is a C~function, |
| 3160 | or \verb|"main"| if this is the main part of a chunk. | 3346 | or \verb|"main"| if this is the main part of a chunk. |
| 3161 | 3347 | ||
| 3162 | \item[currentline] | 3348 | \item[currentline] |
| @@ -3175,11 +3361,11 @@ while others may be stored only in a table field. | |||
| 3175 | The \verb|lua_getinfo| function checks whether the given | 3361 | The \verb|lua_getinfo| function checks whether the given |
| 3176 | function is a tag method or the value of a global variable. | 3362 | function is a tag method or the value of a global variable. |
| 3177 | If the given function is a tag method, | 3363 | If the given function is a tag method, |
| 3178 | \verb|name| points to the event name. | 3364 | then \verb|name| points to the event name. |
| 3179 | If the given function is the value of a global variable, | 3365 | If the given function is the value of a global variable, |
| 3180 | \verb|name| points to the variable name. | 3366 | then \verb|name| points to the variable name. |
| 3181 | If the given function is neither a tag method nor a global variable, | 3367 | If the given function is neither a tag method nor a global variable, |
| 3182 | \verb|name| is set to \verb|NULL|. | 3368 | then \verb|name| is set to \verb|NULL|. |
| 3183 | 3369 | ||
| 3184 | \item[namewhat] | 3370 | \item[namewhat] |
| 3185 | Explains the previous field. | 3371 | Explains the previous field. |
| @@ -3190,8 +3376,8 @@ if the function is a tag method, | |||
| 3190 | otherwise \verb|namewhat| is \verb|""| (the empty string). | 3376 | otherwise \verb|namewhat| is \verb|""| (the empty string). |
| 3191 | 3377 | ||
| 3192 | \item[nups] | 3378 | \item[nups] |
| 3193 | Number of upvalues of a C function. | 3379 | Number of upvalues of a C~function. |
| 3194 | If the function is not a C function, | 3380 | If the function is not a C~function, |
| 3195 | \verb|nups| is set to 0. | 3381 | \verb|nups| is set to 0. |
| 3196 | 3382 | ||
| 3197 | \item[func] | 3383 | \item[func] |
| @@ -3206,6 +3392,10 @@ int lua_setdebug (lua_State *L, int debug); | |||
| 3206 | \end{verbatim} | 3392 | \end{verbatim} |
| 3207 | This function sets the flag and returns its previous value. | 3393 | This function sets the flag and returns its previous value. |
| 3208 | This flag can also be set from Lua~\see{pragma}. | 3394 | This flag can also be set from Lua~\see{pragma}. |
| 3395 | Setting the flag using \verb|lua_setdebug| affects all chunks that are | ||
| 3396 | compiled afterwards. | ||
| 3397 | Individual functions may still control the generation of debug information | ||
| 3398 | by using \verb|$debug| or \verb|$nodebug|. | ||
| 3209 | 3399 | ||
| 3210 | \subsection{Manipulating Local Variables} | 3400 | \subsection{Manipulating Local Variables} |
| 3211 | 3401 | ||
| @@ -3235,7 +3425,7 @@ int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); | |||
| 3235 | \end{verbatim} | 3425 | \end{verbatim} |
| 3236 | The parameter \verb|ar| must be a valid activation record, | 3426 | The parameter \verb|ar| must be a valid activation record, |
| 3237 | filled by a previous call to \verb|lua_getstack| or | 3427 | filled by a previous call to \verb|lua_getstack| or |
| 3238 | given as argument to a hook (see next section). | 3428 | given as argument to a hook \see{sub-hooks}. |
| 3239 | To use \verb|lua_getlocal|, | 3429 | To use \verb|lua_getlocal|, |
| 3240 | you fill the \verb|index| field of \verb|v| with the index | 3430 | you fill the \verb|index| field of \verb|v| with the index |
| 3241 | of a local variable; then the function fills the fields | 3431 | of a local variable; then the function fills the fields |
| @@ -3256,7 +3446,7 @@ int listvars (lua_State *L, int level) { | |||
| 3256 | int i; | 3446 | int i; |
| 3257 | if (lua_getstack(L, level, &ar) == 0) | 3447 | if (lua_getstack(L, level, &ar) == 0) |
| 3258 | return 0; /* failure: no such level on the stack */ | 3448 | return 0; /* failure: no such level on the stack */ |
| 3259 | for (i=1; ;i++) { | 3449 | for (i=1; ; i++) { |
| 3260 | lua_Localvar v; | 3450 | lua_Localvar v; |
| 3261 | v.index = i; | 3451 | v.index = i; |
| 3262 | if (lua_getlocal(L, &ar, &v) == 0) | 3452 | if (lua_getlocal(L, &ar, &v) == 0) |
| @@ -3267,7 +3457,7 @@ int listvars (lua_State *L, int level) { | |||
| 3267 | \end{verbatim} | 3457 | \end{verbatim} |
| 3268 | 3458 | ||
| 3269 | 3459 | ||
| 3270 | \subsection{Hooks} | 3460 | \subsection{Hooks}\label{sub-hooks} |
| 3271 | 3461 | ||
| 3272 | The Lua interpreter offers two hooks for debugging purposes: | 3462 | The Lua interpreter offers two hooks for debugging purposes: |
| 3273 | a \emph{call} hook and a \emph{line} hook. | 3463 | a \emph{call} hook and a \emph{line} hook. |
| @@ -3297,8 +3487,9 @@ local variables. | |||
| 3297 | 3487 | ||
| 3298 | The line hook is called every time the interpreter changes | 3488 | The line hook is called every time the interpreter changes |
| 3299 | the line of code it is executing. | 3489 | the line of code it is executing. |
| 3300 | The \verb|currentline| field of \verb|ar| has the line number. | 3490 | The \verb|event| field of \verb|ar| has the string \verb|"line"|, |
| 3301 | Again, you can use this \verb|ar| in other calls to the API. | 3491 | and the \verb|currentline| field has the line number. |
| 3492 | Again, you can use this \verb|ar| in other calls to the debug API. | ||
| 3302 | This hook is called only if the active function | 3493 | This hook is called only if the active function |
| 3303 | has been compiled with debug information~\see{pragma}. | 3494 | has been compiled with debug information~\see{pragma}. |
| 3304 | 3495 | ||
| @@ -3313,10 +3504,10 @@ called by the hook, because those errors are protected; | |||
| 3313 | the control returns to the hook anyway.) | 3504 | the control returns to the hook anyway.) |
| 3314 | 3505 | ||
| 3315 | 3506 | ||
| 3316 | \subsection{The Reflexive Debugger Interface} | 3507 | \subsection{The Reflexive Debug Interface} |
| 3317 | 3508 | ||
| 3318 | The library \verb|ldblib| provides | 3509 | The library \verb|ldblib| provides |
| 3319 | the functionality of the debugger interface to Lua programs. | 3510 | the functionality of the debug interface to Lua programs. |
| 3320 | If you want to use this library, | 3511 | If you want to use this library, |
| 3321 | your host application must open it, | 3512 | your host application must open it, |
| 3322 | by calling \verb|lua_dblibopen|. | 3513 | by calling \verb|lua_dblibopen|. |
| @@ -3332,9 +3523,9 @@ As a general rule, if your program does not need this library, | |||
| 3332 | do not open it. | 3523 | do not open it. |
| 3333 | 3524 | ||
| 3334 | 3525 | ||
| 3335 | \subsubsection*{\ff \T{getstack (level, what)}}\Deffunc{getstack} | 3526 | \subsubsection*{\ff \T{getstack (level, [what])}}\Deffunc{getstack} |
| 3336 | 3527 | ||
| 3337 | This function returns a table with informations about the function | 3528 | This function returns a table with information about the function |
| 3338 | running at level \verb|level| of the stack. | 3529 | running at level \verb|level| of the stack. |
| 3339 | Level 0 is the current function (\verb|getstack| itself); | 3530 | Level 0 is the current function (\verb|getstack| itself); |
| 3340 | level 1 is the function that called \verb|getstack|. | 3531 | level 1 is the function that called \verb|getstack|. |
| @@ -3342,9 +3533,11 @@ If \verb|level| is larger than the number of active functions, | |||
| 3342 | the function returns \nil. | 3533 | the function returns \nil. |
| 3343 | The table contains all the fields returned by \verb|lua_getinfo|, | 3534 | The table contains all the fields returned by \verb|lua_getinfo|, |
| 3344 | with the string \verb|what| describing what to get. | 3535 | with the string \verb|what| describing what to get. |
| 3536 | The default for \rerb|what| is to get all information available. | ||
| 3345 | 3537 | ||
| 3346 | For instance, the expression \verb|getstack(1, 'n').name| returns | 3538 | For instance, the expression \verb|getstack(1,"n").name| returns |
| 3347 | the name of the current function. | 3539 | the name of the current function, |
| 3540 | if a reasonable name can be found. | ||
| 3348 | 3541 | ||
| 3349 | 3542 | ||
| 3350 | \subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal} | 3543 | \subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal} |
| @@ -3402,11 +3595,13 @@ the language is frequently used as a stand-alone interpreter. | |||
| 3402 | An implementation of such an interpreter, | 3595 | An implementation of such an interpreter, |
| 3403 | called simply \verb|lua|, | 3596 | called simply \verb|lua|, |
| 3404 | is provided with the standard distribution. | 3597 | is provided with the standard distribution. |
| 3598 | |||
| 3405 | This program can be called with any sequence of the following arguments: | 3599 | This program can be called with any sequence of the following arguments: |
| 3406 | \begin{description} | 3600 | \begin{description} |
| 3407 | \item[\T{-}] executes \verb|stdin| as a file; | 3601 | \item[\T{-}] executes \verb|stdin| as a file; |
| 3602 | \item[\T{-c}] calls \verb|lua_close| after running all arguments; | ||
| 3408 | \item[\T{-d}] turns on debug information; | 3603 | \item[\T{-d}] turns on debug information; |
| 3409 | \item[\T{-e stat}] executes string \verb|stat|; | 3604 | \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; |
| 3410 | \item[\T{-f filename}] executes file \verb|filename| with the | 3605 | \item[\T{-f filename}] executes file \verb|filename| with the |
| 3411 | remaining arguments in table \verb|arg|; | 3606 | remaining arguments in table \verb|arg|; |
| 3412 | \item[\T{-i}] enters interactive mode with prompt; | 3607 | \item[\T{-i}] enters interactive mode with prompt; |
| @@ -3424,7 +3619,7 @@ For instance, an invocation like | |||
| 3424 | \begin{verbatim} | 3619 | \begin{verbatim} |
| 3425 | $ lua -i a=test prog.lua | 3620 | $ lua -i a=test prog.lua |
| 3426 | \end{verbatim} | 3621 | \end{verbatim} |
| 3427 | will first interact with the user until an \verb|EOF|, | 3622 | will first interact with the user until an \verb|EOF| in \verb|stdin|, |
| 3428 | then will set \verb|a| to \verb|"test"|, | 3623 | then will set \verb|a| to \verb|"test"|, |
| 3429 | and finally will run the file \verb|prog.lua|. | 3624 | and finally will run the file \verb|prog.lua|. |
| 3430 | 3625 | ||
| @@ -3443,19 +3638,21 @@ then creates a table \T{arg}, | |||
| 3443 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} | 3638 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} |
| 3444 | \end{verbatim} | 3639 | \end{verbatim} |
| 3445 | and then runs the file \T{b.lua}. | 3640 | and then runs the file \T{b.lua}. |
| 3641 | The stand-alone interpreter also provides a \verb|getarg| function that | ||
| 3642 | can be used to access \emph{all} command line arguments. | ||
| 3446 | 3643 | ||
| 3447 | In interactive mode, | 3644 | In interactive mode, |
| 3448 | a multi-line statement can be written finishing intermediate | 3645 | a multi-line statement can be written finishing intermediate |
| 3449 | lines with a backslash (\verb|\|). | 3646 | lines with a backslash (\verb|\|). |
| 3450 | If the global variable \verb|_PROMPT| is defined as a string, | 3647 | If the global variable \verb|_PROMPT| is defined as a string, |
| 3451 | its value is used as the prompt. \Index{_PROMPT} | 3648 | its value is used as the prompt. \index{_PROMPT} |
| 3452 | Therefore, the prompt can be changed like below: | 3649 | Therefore, the prompt can be changed like below: |
| 3453 | \begin{verbatim} | 3650 | \begin{verbatim} |
| 3454 | $ lua _PROMPT='myprompt> ' -i | 3651 | $ lua _PROMPT='myprompt> ' -i |
| 3455 | \end{verbatim} | 3652 | \end{verbatim} |
| 3456 | 3653 | ||
| 3457 | In Unix systems, Lua scripts can be made into executable programs | 3654 | In Unix systems, Lua scripts can be made into executable programs |
| 3458 | by using the \verb|#!| form, | 3655 | by using \verb|chmod +x| and the~\verb|#!| form, |
| 3459 | as in \verb|#!/usr/local/bin/lua|, | 3656 | as in \verb|#!/usr/local/bin/lua|, |
| 3460 | or \verb|#!/usr/local/bin/lua -f| to get other arguments. | 3657 | or \verb|#!/usr/local/bin/lua -f| to get other arguments. |
| 3461 | 3658 | ||
| @@ -3470,7 +3667,6 @@ who found the name of the game. | |||
| 3470 | Lua means \emph{moon} in Portuguese. | 3667 | Lua means \emph{moon} in Portuguese. |
| 3471 | 3668 | ||
| 3472 | 3669 | ||
| 3473 | |||
| 3474 | \appendix | 3670 | \appendix |
| 3475 | 3671 | ||
| 3476 | \section*{Incompatibilities with Previous Versions} | 3672 | \section*{Incompatibilities with Previous Versions} |
| @@ -3482,12 +3678,154 @@ Here is a list of all these incompatibilities. | |||
| 3482 | 3678 | ||
| 3483 | \subsection*{Incompatibilities with \Index{version 3.2}} | 3679 | \subsection*{Incompatibilities with \Index{version 3.2}} |
| 3484 | \begin{itemize} | 3680 | \begin{itemize} |
| 3485 | \item | ||
| 3486 | 3681 | ||
| 3682 | \item | ||
| 3683 | General read patterns are now deprecated. | ||
| 3684 | \item | ||
| 3685 | Garbage-collection tag methods for tables is now deprecated. | ||
| 3686 | \item | ||
| 3687 | \verb|setglobal|, \verb|rawsetglobal|, and \verb|sort| no longer return a value; | ||
| 3688 | \verb|type| no longer return a second value. | ||
| 3689 | \item | ||
| 3690 | In nested function calls like \verb|f(g(x))| | ||
| 3691 | \emph{all} return values from \verb|g| are passed as arguments to \verb|f|. | ||
| 3692 | (This only happens when \verb|g| is the last | ||
| 3693 | [or the only] argument to \verb|f|.) | ||
| 3694 | \item | ||
| 3695 | There is now only one tag method for order operators. | ||
| 3696 | \item | ||
| 3697 | The debug API has been completely rewritten. | ||
| 3698 | \item | ||
| 3699 | The pre-compiler may use the fact that some operators are associative, | ||
| 3700 | for optimizations. | ||
| 3701 | This may cause problems if these operators | ||
| 3702 | have non-associative tag methods. | ||
| 3703 | \item | ||
| 3704 | All functions from the old API are now macros. | ||
| 3705 | \item | ||
| 3706 | A \verb|const| qualifier has been added to \verb|char *| | ||
| 3707 | in all API functions that handle C~strings. | ||
| 3708 | \item | ||
| 3709 | \verb|luaL_openlib| no longer automatically calls \verb|lua_open|. | ||
| 3710 | So, | ||
| 3711 | you must now explicitly call \verb|lua_open| before opening | ||
| 3712 | the standard libraries. | ||
| 3713 | \item | ||
| 3714 | \verb|lua_type| now returns a string describing the type, | ||
| 3715 | and is no longer a synonym for \verb|lua_tag|. | ||
| 3487 | \item Old pre-compiled code is obsolete, and must be re-compiled. | 3716 | \item Old pre-compiled code is obsolete, and must be re-compiled. |
| 3488 | 3717 | ||
| 3489 | \end{itemize} | 3718 | \end{itemize} |
| 3490 | 3719 | ||
| 3720 | %{=============================================================== | ||
| 3721 | \section*{The complete syntax of Lua} | ||
| 3722 | |||
| 3723 | \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} | ||
| 3724 | |||
| 3725 | \renewcommand{\OrNL}{\\ & \Or & } | ||
| 3726 | |||
| 3727 | \begin{Produc} | ||
| 3728 | |||
| 3729 | \produc{chunk}{\rep{stat} \opt{ret}} | ||
| 3730 | |||
| 3731 | \produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}} | ||
| 3732 | |||
| 3733 | \produc{label}{\ter{$\vert$} name \ter{$\vert$}} | ||
| 3734 | |||
| 3735 | \produc{stat}{% | ||
| 3736 | varlist1 \ter{=} explist1 | ||
| 3737 | \OrNL functioncall | ||
| 3738 | \OrNL \rwd{do} block \rwd{end} | ||
| 3739 | \OrNL \rwd{while} exp1 \rwd{do} block \rwd{end} | ||
| 3740 | \OrNL \rwd{repeat} block \rwd{until} exp1 | ||
| 3741 | \OrNL \rwd{if} exp1 \rwd{then} block | ||
| 3742 | \rep{\rwd{elseif} exp1 \rwd{then} block} | ||
| 3743 | \opt{\rwd{else} block} \rwd{end} | ||
| 3744 | \OrNL \rwd{return} \opt{explist1} | ||
| 3745 | \OrNL \rwd{break} \opt{name} | ||
| 3746 | \OrNL \rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} | ||
| 3747 | \rwd{do} block \rwd{end} | ||
| 3748 | \OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} | ||
| 3749 | \OrNL \rwd{local} declist \opt{init} | ||
| 3750 | } | ||
| 3751 | |||
| 3752 | \produc{var}{% | ||
| 3753 | name | ||
| 3754 | \OrNL simpleexp \ter{[} exp1 \ter{]} | ||
| 3755 | \OrNL simpleexp \ter{.} name | ||
| 3756 | } | ||
| 3757 | |||
| 3758 | \produc{varlist1}{var \rep{\ter{,} var}} | ||
| 3759 | |||
| 3760 | \produc{declist}{name \rep{\ter{,} name}} | ||
| 3761 | |||
| 3762 | \produc{init}{\ter{=} explist1} | ||
| 3763 | |||
| 3764 | \produc{exp}{% | ||
| 3765 | \rwd{nil} | ||
| 3766 | \Or number | ||
| 3767 | \Or literal | ||
| 3768 | \Or function | ||
| 3769 | \Or simpleexp | ||
| 3770 | \Or \ter{(} exp \ter{)} | ||
| 3771 | } | ||
| 3772 | |||
| 3773 | \produc{exp1}{exp} | ||
| 3774 | |||
| 3775 | \produc{explist1}{\rep{exp1 \ter{,}} exp} | ||
| 3776 | |||
| 3777 | \produc{simpleexp}{% | ||
| 3778 | var | ||
| 3779 | \Or upvalue | ||
| 3780 | \Or functioncall | ||
| 3781 | \Or tableconstructor | ||
| 3782 | } | ||
| 3783 | |||
| 3784 | \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} | ||
| 3785 | \produc{fieldlist}{% | ||
| 3786 | lfieldlist | ||
| 3787 | \Or ffieldlist | ||
| 3788 | \Or lfieldlist \ter{;} ffieldlist | ||
| 3789 | \Or ffieldlist \ter{;} lfieldlist | ||
| 3790 | } | ||
| 3791 | \produc{lfieldlist}{\opt{lfieldlist1}} | ||
| 3792 | \produc{ffieldlist}{\opt{ffieldlist1}} | ||
| 3793 | \produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}} | ||
| 3794 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} | ||
| 3795 | \produc{ffield}{% | ||
| 3796 | \ter{[} exp \ter{]} \ter{=} exp | ||
| 3797 | \Or name \ter{=} exp | ||
| 3798 | } | ||
| 3799 | |||
| 3800 | \produc{functioncall}{% | ||
| 3801 | simpleexp args | ||
| 3802 | \Or simpleexp \ter{:} name args | ||
| 3803 | } | ||
| 3804 | |||
| 3805 | \produc{args}{% | ||
| 3806 | \ter{(} \opt{explist1} \ter{)} | ||
| 3807 | \Or tableconstructor | ||
| 3808 | \Or \ter{literal} | ||
| 3809 | } | ||
| 3810 | |||
| 3811 | \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}} | ||
| 3812 | |||
| 3813 | \produc{funcname}{% | ||
| 3814 | name | ||
| 3815 | \OrNL name \ter{.} name | ||
| 3816 | \OrNL name \ter{:} name | ||
| 3817 | } | ||
| 3818 | |||
| 3819 | \produc{parlist1}{% | ||
| 3820 | \ter{\ldots} | ||
| 3821 | \Or name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}} | ||
| 3822 | } | ||
| 3823 | |||
| 3824 | \produc{upvalue}{\ter{\%} name} | ||
| 3825 | |||
| 3826 | \end{Produc} | ||
| 3827 | %}=============================================================== | ||
| 3828 | |||
| 3491 | % restore underscore to usual meaning | 3829 | % restore underscore to usual meaning |
| 3492 | \catcode`\_=8 | 3830 | \catcode`\_=8 |
| 3493 | 3831 | ||
| @@ -3498,5 +3836,3 @@ Here is a list of all these incompatibilities. | |||
| 3498 | 3836 | ||
| 3499 | 3837 | ||
| 3500 | \end{document} | 3838 | \end{document} |
| 3501 | |||
| 3502 | |||
