diff options
| author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2003-01-24 14:38:18 -0200 |
|---|---|---|
| committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2003-01-24 14:38:18 -0200 |
| commit | 83f0d6ef1ac9ddd2e9771e721aab2af8117a18a1 (patch) | |
| tree | 544aa77c0a59c66cf3e5f42e0192a81979850137 | |
| parent | 3088ebd95b7c509ff1a049ef4a10a1c016883490 (diff) | |
| download | lua-83f0d6ef1ac9ddd2e9771e721aab2af8117a18a1.tar.gz lua-83f0d6ef1ac9ddd2e9771e721aab2af8117a18a1.tar.bz2 lua-83f0d6ef1ac9ddd2e9771e721aab2af8117a18a1.zip | |
DEPRECATED (new manual uses an independent format instead of LaTeX)
| -rw-r--r-- | manual.tex | 4539 |
1 files changed, 0 insertions, 4539 deletions
diff --git a/manual.tex b/manual.tex deleted file mode 100644 index 35984019..00000000 --- a/manual.tex +++ /dev/null | |||
| @@ -1,4539 +0,0 @@ | |||
| 1 | % $Id: manual.tex,v 2.1 2003/01/22 16:29:38 roberto Exp roberto $ | ||
| 2 | %{[( | ||
| 3 | |||
| 4 | \documentclass[11pt,twoside]{article} | ||
| 5 | \usepackage{fullpage} | ||
| 6 | \usepackage{iso} | ||
| 7 | \usepackage{graphicx} | ||
| 8 | |||
| 9 | |||
| 10 | |||
| 11 | % Right arrow (internal use) | ||
| 12 | \newcommand{\ra}{\(\rightarrow\)\ } | ||
| 13 | |||
| 14 | % Terminal Simbols | ||
| 15 | \newcommand{\ter}[1]{{\rm`{\tt#1}'}} | ||
| 16 | %reserved words | ||
| 17 | \newcommand{\rwd}[1]{{\bf\lowercase{#1}}} | ||
| 18 | % empty production | ||
| 19 | \newcommand{\emptyprod}{$\epsilon$ } | ||
| 20 | |||
| 21 | % repetitions and optionals | ||
| 22 | \newcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}} | ||
| 23 | \newcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}} | ||
| 24 | \newcommand{\oneormore}[1]{{\rm\{}#1{\/\rm\}$^+$}} | ||
| 25 | |||
| 26 | \newcommand{\prg}[1]{{\it #1\/}} | ||
| 27 | |||
| 28 | %productions: \produc{non-terminal}{rule} | ||
| 29 | \newcommand{\produc}[2]{#1 & \ra & #2\index{grammar!#1}\\} | ||
| 30 | |||
| 31 | %new line inside a production | ||
| 32 | \newcommand{\NL}{\\ & &} | ||
| 33 | %new line indented | ||
| 34 | \newcommand{\NLI}{\NL\hspace{2ex}} | ||
| 35 | |||
| 36 | % 'or' | ||
| 37 | \newcommand{\Or}{$|$ } | ||
| 38 | |||
| 39 | % 'or' in a new line | ||
| 40 | \newcommand{\OrNL}{\\ & \Or & } | ||
| 41 | |||
| 42 | %Environment for productions | ||
| 43 | \newenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{5ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} | ||
| 44 | |||
| 45 | |||
| 46 | %\newcommand{\See}[1]{Section~\ref{#1}} | ||
| 47 | \newcommand{\See}[1]{\S\ref{#1}} | ||
| 48 | %\newcommand{\see}[1]{(see~\See{#1} on page \pageref{#1})} | ||
| 49 | \newcommand{\see}[1]{(see~\See{#1})} | ||
| 50 | \newcommand{\seepage}[1]{(see page~\pageref{#1})} | ||
| 51 | \newcommand{\M}[1]{{\rm\emph{#1}}} | ||
| 52 | \newcommand{\T}[1]{{\tt #1}} | ||
| 53 | \newcommand{\Math}[1]{$#1$} | ||
| 54 | \newcommand{\nil}{{\bf nil}} | ||
| 55 | \newcommand{\False}{{\bf false}} | ||
| 56 | \newcommand{\True}{{\bf true}} | ||
| 57 | %\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} | ||
| 58 | \def\tecgraf{{\sf Tecgraf}} | ||
| 59 | |||
| 60 | \newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} | ||
| 61 | \newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} | ||
| 62 | \newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}} | ||
| 63 | \newcommand{\IndexTM}[1]{\index{#1 event@{\Q{#1} event}}\index{metamethod!#1}} | ||
| 64 | \newcommand{\Def}[1]{\emph{#1}\index{#1}} | ||
| 65 | \newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}} | ||
| 66 | \newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}} | ||
| 67 | \newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}} | ||
| 68 | \newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}} | ||
| 69 | \newcommand{\IndexKW}[1]{\index{keywords!#1@{\tt #1}}} | ||
| 70 | |||
| 71 | \newcommand{\Q}[1]{``#1''} | ||
| 72 | \newcommand{\Em}{---} | ||
| 73 | \newcommand{\En}{--} | ||
| 74 | \newcommand{\C}[1]{} | ||
| 75 | |||
| 76 | \newcommand{\ff}{$\bullet$\ } | ||
| 77 | |||
| 78 | \newcommand{\Version}{5.0 (beta)} | ||
| 79 | |||
| 80 | \newcommand{\Nter}[1]{{\tt#1}} | ||
| 81 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } | ||
| 82 | |||
| 83 | \newcommand{\At}{{\tt @}} %{\verb|@|} | ||
| 84 | \newcommand{\Nb}{~} | ||
| 85 | |||
| 86 | \makeindex | ||
| 87 | |||
| 88 | \begin{document} | ||
| 89 | |||
| 90 | %{=============================================================== | ||
| 91 | \thispagestyle{empty} | ||
| 92 | \pagestyle{empty} | ||
| 93 | |||
| 94 | { | ||
| 95 | \parindent=0pt | ||
| 96 | \vglue1.5in | ||
| 97 | {\LARGE\bf | ||
| 98 | The Lua Programming Language} | ||
| 99 | \hfill | ||
| 100 | \vskip4pt \hrule height 4pt width \hsize \vskip4pt | ||
| 101 | \hfill | ||
| 102 | Reference Manual for Lua version \Version | ||
| 103 | \\ | ||
| 104 | \null | ||
| 105 | \hfill | ||
| 106 | Last revised on \today | ||
| 107 | \\ | ||
| 108 | \vfill | ||
| 109 | \centering | ||
| 110 | \includegraphics[width=0.7\textwidth]{nolabel.ps} | ||
| 111 | \vfill | ||
| 112 | \vskip4pt \hrule height 2pt width \hsize | ||
| 113 | } | ||
| 114 | |||
| 115 | \newpage | ||
| 116 | \begin{quotation} | ||
| 117 | \parskip=10pt | ||
| 118 | \parindent=0pt | ||
| 119 | \footnotesize | ||
| 120 | \null\vfill | ||
| 121 | |||
| 122 | \noindent | ||
| 123 | Copyright \copyright\ 2002 Tecgraf, PUC-Rio. All rights reserved. | ||
| 124 | |||
| 125 | Permission is hereby granted, free of charge, | ||
| 126 | to any person obtaining a copy of this software | ||
| 127 | and associated documentation files (the "Software"), | ||
| 128 | to deal in the Software without restriction, | ||
| 129 | including without limitation the rights to use, copy, modify, | ||
| 130 | merge, publish, distribute, sublicense, | ||
| 131 | and/or sell copies of the Software, | ||
| 132 | and to permit persons to whom the Software is furnished to do so, | ||
| 133 | subject to the following conditions: | ||
| 134 | |||
| 135 | The above copyright notice and this permission notice shall be | ||
| 136 | included in all copies or substantial portions of the Software. | ||
| 137 | |||
| 138 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| 139 | EXPRESS OR IMPLIED, | ||
| 140 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 141 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
| 142 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE | ||
| 143 | FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| 144 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
| 145 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE | ||
| 146 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
| 147 | |||
| 148 | |||
| 149 | Copies of this manual can be obtained at | ||
| 150 | Lua's official web site, | ||
| 151 | \verb|www.lua.org|. | ||
| 152 | |||
| 153 | \bigskip | ||
| 154 | The Lua logo was designed by A. Nakonechny. | ||
| 155 | Copyright \copyright\ 1998. All rights reserved. | ||
| 156 | \end{quotation} | ||
| 157 | %}=============================================================== | ||
| 158 | \newpage | ||
| 159 | |||
| 160 | \title{\Large\bf Reference Manual of the Programming Language Lua \Version} | ||
| 161 | |||
| 162 | \author{% | ||
| 163 | Roberto Ierusalimschy\qquad | ||
| 164 | Luiz Henrique de Figueiredo\qquad | ||
| 165 | Waldemar Celes | ||
| 166 | \vspace{1.0ex}\\ | ||
| 167 | \smallskip | ||
| 168 | \small\tt lua@tecgraf.puc-rio.br | ||
| 169 | \vspace{2.0ex}\\ | ||
| 170 | %MCC 08/95 --- | ||
| 171 | \tecgraf\ --- Computer Science Department --- PUC-Rio | ||
| 172 | } | ||
| 173 | |||
| 174 | %\date{{\small \tt\$Date: 2003/01/22 16:29:38 $ $}} | ||
| 175 | |||
| 176 | \maketitle | ||
| 177 | |||
| 178 | \pagestyle{plain} | ||
| 179 | \pagenumbering{roman} | ||
| 180 | |||
| 181 | \begin{abstract} | ||
| 182 | \noindent | ||
| 183 | Lua is a powerful, light-weight programming language | ||
| 184 | designed for extending applications. | ||
| 185 | Lua is also frequently used as a general-purpose, stand-alone language. | ||
| 186 | Lua combines simple procedural syntax | ||
| 187 | (similar to Pascal) | ||
| 188 | with | ||
| 189 | powerful data description constructs | ||
| 190 | based on associative arrays and extensible semantics. | ||
| 191 | Lua is | ||
| 192 | dynamically typed, | ||
| 193 | interpreted from opcodes, | ||
| 194 | and has automatic memory management with garbage collection, | ||
| 195 | making it ideal for | ||
| 196 | configuration, | ||
| 197 | scripting, | ||
| 198 | and | ||
| 199 | rapid prototyping. | ||
| 200 | |||
| 201 | This document describes version \Version{} of the Lua programming language | ||
| 202 | and the Application Program Interface (API) | ||
| 203 | that allows interaction between Lua programs and their host C~programs. | ||
| 204 | \end{abstract} | ||
| 205 | |||
| 206 | \def\abstractname{Resumo} | ||
| 207 | \begin{abstract} | ||
| 208 | \noindent | ||
| 209 | Lua é uma linguagem de programação | ||
| 210 | poderosa e leve, | ||
| 211 | projetada para estender aplicações. | ||
| 212 | Lua também é frequentemente usada como uma linguagem de propósito geral. | ||
| 213 | Lua combina programação procedural | ||
| 214 | (com sintaxe semelhante à de Pascal) | ||
| 215 | com | ||
| 216 | poderosas construções para descrição de dados, | ||
| 217 | baseadas em tabelas associativas e semântica extensível. | ||
| 218 | Lua é | ||
| 219 | tipada dinamicamente, | ||
| 220 | interpretada a partir de \emph{opcodes}, | ||
| 221 | e tem gerenciamento automático de memória com coleta de lixo. | ||
| 222 | Essas características fazem de Lua uma linguagem ideal para | ||
| 223 | configuração, | ||
| 224 | automação (\emph{scripting}) | ||
| 225 | e prototipagem rápida. | ||
| 226 | |||
| 227 | Este documento descreve a versão \Version{} da linguagem de | ||
| 228 | programação Lua e a Interface de Programação (API) que permite | ||
| 229 | a interação entre programas Lua e programas C~hospedeiros. | ||
| 230 | \end{abstract} | ||
| 231 | |||
| 232 | \newpage | ||
| 233 | \null | ||
| 234 | \newpage | ||
| 235 | \tableofcontents | ||
| 236 | |||
| 237 | \newpage | ||
| 238 | \setcounter{page}{1} | ||
| 239 | \pagestyle{plain} | ||
| 240 | \pagenumbering{arabic} | ||
| 241 | |||
| 242 | \catcode`\_=12 | ||
| 243 | \catcode`\$=12 | ||
| 244 | \catcode`\#=12 | ||
| 245 | \catcode`\%=12 | ||
| 246 | \catcode`\^=12 | ||
| 247 | \catcode`\~=12 | ||
| 248 | \catcode`\&=12 | ||
| 249 | |||
| 250 | |||
| 251 | |||
| 252 | \C{-------------------------------------------------------------------------} | ||
| 253 | \section{Introduction} | ||
| 254 | |||
| 255 | Lua is an extension programming language designed to support | ||
| 256 | general procedural programming with data description | ||
| 257 | facilities. | ||
| 258 | Lua is intended to be used as a powerful, light-weight | ||
| 259 | configuration language for any program that needs one. | ||
| 260 | Lua is implemented as a library, written in C. | ||
| 261 | |||
| 262 | Being an extension language, Lua has no notion of a \Q{main} program: | ||
| 263 | it only works \emph{embedded} in a host client, | ||
| 264 | called the \emph{embedding program} or simply the \emph{host}. | ||
| 265 | This host program can invoke functions to execute a piece of Lua code, | ||
| 266 | can write and read Lua variables, | ||
| 267 | and can register C\Nb{}functions to be called by Lua code. | ||
| 268 | Through the use of C\Nb{}functions, Lua can be augmented to cope with | ||
| 269 | a wide range of different domains, | ||
| 270 | thus creating customized programming languages sharing a syntactical framework. | ||
| 271 | |||
| 272 | Lua is free software, | ||
| 273 | and is provided as usual with no guarantees, | ||
| 274 | as stated in its copyright notice. | ||
| 275 | The implementation described in this manual is available | ||
| 276 | at Lua's official web site, \verb|www.lua.org|. | ||
| 277 | |||
| 278 | Like any other reference manual, | ||
| 279 | this document is dry in places. | ||
| 280 | For a discussion of the decisions behind the design of Lua, | ||
| 281 | see the papers below, | ||
| 282 | which are available at Lua's web site. | ||
| 283 | \begin{itemize} | ||
| 284 | \item | ||
| 285 | R.\Nb{}Ierusalimschy, L.\Nb{}H.\Nb{}de Figueiredo, and W.\Nb{}Celes. | ||
| 286 | Lua\Em{}an extensible extension language. | ||
| 287 | \emph{Software: Practice & Experience} {\bf 26} #6 (1996) 635\En{}652. | ||
| 288 | \item | ||
| 289 | L.\Nb{}H.\Nb{}de Figueiredo, R.\Nb{}Ierusalimschy, and W.\Nb{}Celes. | ||
| 290 | The design and implementation of a language for extending applications. | ||
| 291 | \emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273\En{}283. | ||
| 292 | \item | ||
| 293 | L.\Nb{}H.\Nb{}de Figueiredo, R.\Nb{}Ierusalimschy, and W.\Nb{}Celes. | ||
| 294 | Lua: an extensible embedded language. | ||
| 295 | \emph{Dr. Dobb's Journal} {\bf 21} #12 (Dec 1996) 26\En{}33. | ||
| 296 | \item | ||
| 297 | R.\Nb{}Ierusalimschy, L.\Nb{}H.\Nb{}de Figueiredo, and W.\Nb{}Celes. | ||
| 298 | The evolution of an extension language: a history of Lua, | ||
| 299 | \emph{Proceedings of V Brazilian Symposium on Programming Languages} (2001) B-14\En{}B-28. | ||
| 300 | \end{itemize} | ||
| 301 | |||
| 302 | Lua means \Q{moon} in Portuguese. | ||
| 303 | |||
| 304 | \C{-------------------------------------------------------------------------} | ||
| 305 | \section{Lua Concepts}\label{concepts} | ||
| 306 | |||
| 307 | This section describes the main concepts of Lua as a language. | ||
| 308 | The syntax and semantics of Lua are described in \See{language}. | ||
| 309 | The discussion below is not purely conceptual; | ||
| 310 | it includes references to the C\Nb{}API \see{API}, | ||
| 311 | because Lua is designed to be embedded in host programs. | ||
| 312 | It also includes references to the standard libraries \see{libraries}. | ||
| 313 | |||
| 314 | |||
| 315 | \subsection{Environment and Chunks} | ||
| 316 | |||
| 317 | All statements in Lua are executed in a \Def{global environment}. | ||
| 318 | This environment is initialized with a call from the embedding program to | ||
| 319 | \verb|lua_open| and | ||
| 320 | persists until a call to \verb|lua_close| | ||
| 321 | or the end of the embedding program. | ||
| 322 | The host program can create multiple independent global | ||
| 323 | environments, and freely switch among them \see{mangstate}. | ||
| 324 | |||
| 325 | The unit of execution of Lua is called a \Def{chunk}. | ||
| 326 | A chunk is simply a sequence of statements. | ||
| 327 | Statements are described in \See{stats}. | ||
| 328 | |||
| 329 | A chunk may be stored in a file or in a string inside the host program. | ||
| 330 | When a chunk is executed, first it is pre-compiled into opcodes for | ||
| 331 | a virtual machine, | ||
| 332 | and then the compiled statements are executed | ||
| 333 | by an interpreter for the virtual machine. | ||
| 334 | All modifications that a chunk makes to the global environment persist | ||
| 335 | after the chunk ends. | ||
| 336 | |||
| 337 | Chunks may also be pre-compiled into binary form and stored in files; | ||
| 338 | see program \IndexVerb{luac} for details. | ||
| 339 | Programs in source and compiled forms are interchangeable; | ||
| 340 | Lua automatically detects the file type and acts accordingly. | ||
| 341 | \index{pre-compilation} | ||
| 342 | |||
| 343 | |||
| 344 | \subsection{Table of Globals} \label{global-table} | ||
| 345 | |||
| 346 | ???? | ||
| 347 | |||
| 348 | \subsection{\Index{Values and Types}} \label{TypesSec} | ||
| 349 | |||
| 350 | Lua is a \emph{dynamically typed language}. | ||
| 351 | That means that | ||
| 352 | variables do not have types; only values do. | ||
| 353 | There are no type definitions in the language. | ||
| 354 | All values carry their own type. | ||
| 355 | |||
| 356 | There are eight \Index{basic types} in Lua: | ||
| 357 | \Def{nil}, \Def{boolean}, \Def{number}, | ||
| 358 | \Def{string}, \Def{function}, \Def{userdata}, \Def{thread}, and \Def{table}. | ||
| 359 | \emph{Nil} is the type of the value \nil{}, | ||
| 360 | whose main property is to be different from any other value; | ||
| 361 | usually it represents the absence of a useful value. | ||
| 362 | \emph{Boolean} is the type of the values \False{} and \True{}. | ||
| 363 | In Lua, both \nil{} and \False{} make a condition false, | ||
| 364 | and any other value makes it true. | ||
| 365 | \emph{Number} represents real (double-precision floating-point) numbers. | ||
| 366 | (It is not difficult to build Lua interpreters that use other | ||
| 367 | internal representations for numbers, | ||
| 368 | such as single-precision float or long integers.) | ||
| 369 | \emph{String} represents arrays of characters. | ||
| 370 | \index{eight-bit clean} | ||
| 371 | Lua is 8-bit clean, | ||
| 372 | so strings may contain any 8-bit character, | ||
| 373 | including embedded zeros (\verb|'\0'|) \see{lexical}. | ||
| 374 | |||
| 375 | Functions are \emph{first-class values} in Lua. | ||
| 376 | That means that functions can be stored in variables, | ||
| 377 | passed as arguments to other functions, and returned as results. | ||
| 378 | Lua can call (and manipulate) functions written in Lua and | ||
| 379 | functions written in C | ||
| 380 | \see{functioncall}. | ||
| 381 | |||
| 382 | The type \emph{userdata} is provided to allow arbitrary C data to | ||
| 383 | be stored in Lua variables. | ||
| 384 | This type corresponds to a block of raw memory | ||
| 385 | and has no pre-defined operations in Lua, | ||
| 386 | except assignment and identity test. | ||
| 387 | However, by using \emph{metatables}, | ||
| 388 | the programmer can define operations for userdata values | ||
| 389 | \see{metatable}. | ||
| 390 | Userdata values cannot be created or modified in Lua, | ||
| 391 | only through the C\Nb{}API. | ||
| 392 | This guarantees the integrity of data owned by the host program. | ||
| 393 | |||
| 394 | The type \Def{thread} represents independent threads of execution, | ||
| 395 | and it is used to implement coroutines. | ||
| 396 | (This is an experimental area; it needs more documentation, | ||
| 397 | and is subject to changes in the future.) | ||
| 398 | |||
| 399 | The type \emph{table} implements \Index{associative arrays}, | ||
| 400 | that is, \Index{arrays} that can be indexed not only with numbers, | ||
| 401 | but with any value (except \nil{}). | ||
| 402 | Moreover, | ||
| 403 | tables can be \emph{heterogeneous}, | ||
| 404 | that is, they can contain values of all types (except \nil{}). | ||
| 405 | Tables are the sole data structuring mechanism in Lua; | ||
| 406 | they may be used to represent not only ordinary arrays, | ||
| 407 | but also symbol tables, sets, records, graphs, trees, etc. | ||
| 408 | To represent \Index{records}, Lua uses the field name as an index. | ||
| 409 | The language supports this representation by | ||
| 410 | providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. | ||
| 411 | There are several convenient ways to create tables in Lua | ||
| 412 | \see{tableconstructor}. | ||
| 413 | |||
| 414 | Like indices, the value of a table field can be of any type. | ||
| 415 | In particular, | ||
| 416 | because functions are first class values, | ||
| 417 | table fields may contain functions. | ||
| 418 | Thus tables may also carry \emph{methods} \see{func-def}. | ||
| 419 | |||
| 420 | Tables, functions, and userdata values are \emph{objects}: | ||
| 421 | variables do not actually \emph{contain} these values, | ||
| 422 | only \emph{references} to them. | ||
| 423 | Assignment, parameter passing, and function returns | ||
| 424 | always manipulate references to these values, | ||
| 425 | and do not imply any kind of copy. | ||
| 426 | |||
| 427 | The library function \verb|type| returns a string describing the type | ||
| 428 | of a given value \see{pdf-type}. | ||
| 429 | |||
| 430 | |||
| 431 | \subsubsection{Metatables} | ||
| 432 | |||
| 433 | Each table and userdata object in Lua may have a \Index{metatable}. | ||
| 434 | |||
| 435 | You can change several aspects of the behavior | ||
| 436 | of an object by setting specific fields in its metatable. | ||
| 437 | For instance, when an object is the operand of an addition, | ||
| 438 | Lua checks for a function in the field \verb|"__add"| in its metatable. | ||
| 439 | If it finds one, | ||
| 440 | Lua calls that function to perform the addition. | ||
| 441 | |||
| 442 | We call the keys in a metatable \Index{events}, | ||
| 443 | and the values \Index{metamethods}. | ||
| 444 | In the previous example, \verb|"add"| is the event, | ||
| 445 | and the function is the metamethod that performs the addition. | ||
| 446 | |||
| 447 | A metatable controls how an object behaves in arithmetic operations, | ||
| 448 | order comparisons, concatenation, and indexing. | ||
| 449 | A metatable can also define a function to be called when a userdata | ||
| 450 | is garbage collected. | ||
| 451 | \See{metatable} gives a detailed description of which events you | ||
| 452 | can control with metatables. | ||
| 453 | |||
| 454 | You can query and change the metatable of an object | ||
| 455 | through the \verb|setmetatable| and \verb|getmetatable| | ||
| 456 | functions \see{pdf-getmetatable}. | ||
| 457 | |||
| 458 | |||
| 459 | |||
| 460 | \subsection{Coercion} \label{coercion} | ||
| 461 | |||
| 462 | Lua provides automatic conversion between | ||
| 463 | string and number values at run time. | ||
| 464 | Any arithmetic operation applied to a string tries to convert | ||
| 465 | that string to a number, following the usual rules. | ||
| 466 | Conversely, whenever a number is used where a string is expected, | ||
| 467 | the number is converted to a string, in a reasonable format. | ||
| 468 | The format is chosen so that | ||
| 469 | a conversion from number to string then back to number | ||
| 470 | reproduces the original number \emph{exactly}. | ||
| 471 | For complete control of how numbers are converted to strings, | ||
| 472 | use the \verb|format| function \see{format}. | ||
| 473 | |||
| 474 | |||
| 475 | \subsection{Variables} | ||
| 476 | |||
| 477 | There are two kinds of variables in Lua: | ||
| 478 | global variables | ||
| 479 | and local variables. | ||
| 480 | Variables are assumed to be global unless explicitly declared local | ||
| 481 | \see{localvar}. | ||
| 482 | Before the first assignment to a variable, its value is \nil{}. | ||
| 483 | |||
| 484 | All global variables live as fields in ordinary Lua tables. | ||
| 485 | Usually, globals live in a table called \Index{table of globals}. | ||
| 486 | However, a function can individually change its global table, | ||
| 487 | so that all global variables in that function will refer to that table. | ||
| 488 | This mechanism allows the creation of \Index{namespaces} and other | ||
| 489 | modularization facilities. | ||
| 490 | |||
| 491 | \Index{Local variables} are lexically scoped. | ||
| 492 | Therefore, local variables can be freely accessed by functions | ||
| 493 | defined inside their scope \see{visibility}. | ||
| 494 | |||
| 495 | |||
| 496 | \subsection{Garbage Collection}\label{GC} | ||
| 497 | |||
| 498 | Lua does automatic memory management. | ||
| 499 | That means that | ||
| 500 | you do not have to worry about allocating memory for new objects | ||
| 501 | and freeing it when the objects are no longer needed. | ||
| 502 | Lua manages memory automatically by running | ||
| 503 | a \Index{garbage collector} from time to time | ||
| 504 | and | ||
| 505 | collecting all dead objects | ||
| 506 | (all objects that are no longer accessible from Lua). | ||
| 507 | All objects in Lua are subject to automatic management: | ||
| 508 | tables, userdata, functions, and strings. | ||
| 509 | |||
| 510 | Using the C\Nb{}API, | ||
| 511 | you can set garbage-collector metamethods for userdata \see{metatable}. | ||
| 512 | When it is about to free a userdata, | ||
| 513 | Lua calls the metamethod associated with event \verb|gc| in the | ||
| 514 | userdata's metatable. | ||
| 515 | Using such facility, you can coordinate Lua's garbage collection | ||
| 516 | with external resource management | ||
| 517 | (such as closing files, network or database connections, | ||
| 518 | or freeing your own memory). | ||
| 519 | |||
| 520 | Lua uses two numbers to control its garbage-collection cycles. | ||
| 521 | One number counts how many bytes of dynamic memory Lua is using, | ||
| 522 | and the other is a threshold. | ||
| 523 | When the number of bytes crosses the threshold, | ||
| 524 | Lua runs the garbage collector, | ||
| 525 | which reclaims the memory of all dead objects. | ||
| 526 | The byte counter is adjusted, | ||
| 527 | and then the threshold is reset to twice the new value of the byte counter. | ||
| 528 | |||
| 529 | Through the C\Nb{}API, you can query those numbers, | ||
| 530 | and change the threshold \see{GC-API}. | ||
| 531 | Setting the threshold to zero actually forces an immediate | ||
| 532 | garbage-collection cycle, | ||
| 533 | while setting it to a huge number effectively stops the garbage collector. | ||
| 534 | Using Lua code you have a more limited control over garbage-collection cycles, | ||
| 535 | through the functions \verb|gcinfo| and \verb|collectgarbage| | ||
| 536 | \see{predefined}. | ||
| 537 | |||
| 538 | |||
| 539 | \subsubsection{Weak Tables}\label{weak-table} | ||
| 540 | |||
| 541 | A \IndexEmph{weak table} is a table whose elements are | ||
| 542 | \IndexEmph{weak references}. | ||
| 543 | A weak reference is ignored by the garbage collector. | ||
| 544 | In other words, | ||
| 545 | if the only references to an object are weak references, | ||
| 546 | then the garbage collector will collect that object. | ||
| 547 | |||
| 548 | A weak table can have weak keys, weak values, or both. | ||
| 549 | A table with weak keys allows the collection of its keys, | ||
| 550 | but prevents the collection of its values. | ||
| 551 | A table with both weak keys and weak values allows the collection of | ||
| 552 | both keys and values. | ||
| 553 | In any case, if either the key or the value is collected, | ||
| 554 | the whole pair is removed from the table. | ||
| 555 | The weakness of a table is controlled by the value of the | ||
| 556 | \verb|__mode| field of its metatable. | ||
| 557 | If the \verb|__mode| field is a string containing the character \verb|k|, | ||
| 558 | the keys in the table are weak. | ||
| 559 | If \verb|__mode| contains \verb|v|, | ||
| 560 | the values in the table are weak. | ||
| 561 | |||
| 562 | |||
| 563 | \C{-------------------------------------------------------------------------} | ||
| 564 | \section{The Language}\label{language} | ||
| 565 | |||
| 566 | This section describes the lexis, the syntax, and the semantics of Lua. | ||
| 567 | In other words, | ||
| 568 | this section describes | ||
| 569 | which tokens are valid, | ||
| 570 | how they can be combined, | ||
| 571 | and what their combinations mean. | ||
| 572 | |||
| 573 | \subsection{Lexical Conventions} \label{lexical} | ||
| 574 | |||
| 575 | \IndexEmph{Identifiers} in Lua can be any string of letters, | ||
| 576 | digits, and underscores, | ||
| 577 | not beginning with a digit. | ||
| 578 | This coincides with the definition of identifiers in most languages. | ||
| 579 | (The definition of letter depends on the current locale: | ||
| 580 | any character considered alphabetic by the current locale | ||
| 581 | can be used in an identifier.) | ||
| 582 | |||
| 583 | The following \IndexEmph{keywords} are reserved, | ||
| 584 | and cannot be used as identifiers: | ||
| 585 | \index{reserved words} | ||
| 586 | \begin{verbatim} | ||
| 587 | and break do else elseif | ||
| 588 | end false for function if | ||
| 589 | in local nil not or | ||
| 590 | repeat return then true until | ||
| 591 | while | ||
| 592 | \end{verbatim} | ||
| 593 | |||
| 594 | Lua is a case-sensitive language: | ||
| 595 | \T{and} is a reserved word, but \T{And} and \T{AND} | ||
| 596 | are two different, valid identifiers. | ||
| 597 | As a convention, identifiers starting with an underscore followed by | ||
| 598 | uppercase letters (such as \verb|_VERSION|) | ||
| 599 | are reserved for internal variables used by Lua. | ||
| 600 | |||
| 601 | The following strings denote other \Index{tokens}: | ||
| 602 | \begin{verbatim} | ||
| 603 | + - * / ^ = | ||
| 604 | ~= <= >= < > == | ||
| 605 | ( ) { } [ ] | ||
| 606 | ; : , . .. ... | ||
| 607 | \end{verbatim} | ||
| 608 | |||
| 609 | \IndexEmph{Literal strings} | ||
| 610 | can be delimited by matching single or double quotes, | ||
| 611 | and can contain the C-like escape sequences | ||
| 612 | `\verb|\a|' (bell), | ||
| 613 | `\verb|\b|' (backspace), | ||
| 614 | `\verb|\f|' (form feed), | ||
| 615 | `\verb|\n|' (newline), | ||
| 616 | `\verb|\r|' (carriage return), | ||
| 617 | `\verb|\t|' (horizontal tab), | ||
| 618 | `\verb|\v|' (vertical tab), | ||
| 619 | `\verb|\\|' (backslash), | ||
| 620 | `\verb|\"|' (quotation mark), | ||
| 621 | `\verb|\'|' (apostrophe), | ||
| 622 | `\verb|\[|' (left square bracket), | ||
| 623 | `\verb|\]|' (right square bracket), | ||
| 624 | and `\verb|\|\emph{newline}' (that is, a backslash followed by a real newline, | ||
| 625 | which results in a newline in the string). | ||
| 626 | A character in a string may also be specified by its numerical value | ||
| 627 | using the escape sequence `\verb|\|\emph{ddd}', | ||
| 628 | where \emph{ddd} is a sequence of up to three \emph{decimal} digits. | ||
| 629 | Strings in Lua may contain any 8-bit value, including embedded zeros, | ||
| 630 | which can be specified as `\verb|\0|'. | ||
| 631 | |||
| 632 | Literal strings can also be delimited by matching | ||
| 633 | \verb|[[| \Math{\ldots} \verb|]]|. | ||
| 634 | Literals in this bracketed form may run for several lines, | ||
| 635 | may contain nested \verb|[[| \Math{\ldots} \verb|]]| pairs, | ||
| 636 | and do not interpret escape sequences. | ||
| 637 | For convenience, | ||
| 638 | when the opening \verb|[[| is immediately followed by a newline, | ||
| 639 | the newline is not included in the string. \C{ ]]} | ||
| 640 | That form is specially convenient for | ||
| 641 | writing strings that contain program pieces or | ||
| 642 | other quoted strings. | ||
| 643 | As an example, in a system using ASCII | ||
| 644 | (in which `\verb|a|' is coded as\Nb{}97, | ||
| 645 | newline is coded as\Nb{}10, and `\verb|1|' is coded as\Nb{}49), | ||
| 646 | the four literals below denote the same string: | ||
| 647 | \begin{verbatim} | ||
| 648 | (1) "alo\n123\"" | ||
| 649 | (2) '\97lo\10\04923"' | ||
| 650 | (3) [[alo | ||
| 651 | 123"]] | ||
| 652 | (4) [[ | ||
| 653 | alo | ||
| 654 | 123"]] | ||
| 655 | \end{verbatim} | ||
| 656 | |||
| 657 | \IndexEmph{Numerical constants} may be written with an optional decimal part | ||
| 658 | and an optional decimal exponent. | ||
| 659 | Examples of valid numerical constants are | ||
| 660 | \begin{verbatim} | ||
| 661 | 3 3.0 3.1416 314.16e-2 0.31416E1 | ||
| 662 | \end{verbatim} | ||
| 663 | |||
| 664 | \IndexEmph{Comments} start anywhere outside a string with a | ||
| 665 | double hyphen (\verb|--|); | ||
| 666 | If the text after \verb|--| is different from \verb|[[|, | ||
| 667 | the comment is a short comment, | ||
| 668 | that runs until the end of the line. | ||
| 669 | Otherwise, it is a long comment, | ||
| 670 | that runs until the corresponding \verb|]]|. | ||
| 671 | Long comments may run for several lines, | ||
| 672 | and may contain nested \verb|[[| \Math{\ldots} \verb|]]| pairs. | ||
| 673 | For convenience, | ||
| 674 | the first line of a chunk is skipped if it starts with \verb|#|. | ||
| 675 | This facility allows the use of Lua as a script interpreter | ||
| 676 | in Unix systems \see{lua-sa}. | ||
| 677 | |||
| 678 | |||
| 679 | \subsection{Variables}\label{variables} | ||
| 680 | |||
| 681 | Variables are places that store values. | ||
| 682 | \C{In Lua, variables are given by simple identifiers or by table fields.} | ||
| 683 | |||
| 684 | A single name can denote a global variable, a local variable, | ||
| 685 | or a formal parameter in a function | ||
| 686 | (formal parameters are just local variables): | ||
| 687 | \begin{Produc} | ||
| 688 | \produc{var}{\Nter{Name}} | ||
| 689 | \end{Produc} | ||
| 690 | Square brackets are used to index a table: | ||
| 691 | \begin{Produc} | ||
| 692 | \produc{var}{prefixexp \ter{[} exp \ter{]}} | ||
| 693 | \end{Produc} | ||
| 694 | The first expression should result in a table value, | ||
| 695 | and the second expression identifies a specific entry inside that table. | ||
| 696 | |||
| 697 | The syntax \verb|var.NAME| is just syntactic sugar for | ||
| 698 | \verb|var["NAME"]|: | ||
| 699 | \begin{Produc} | ||
| 700 | \produc{var}{prefixexp \ter{.} \Nter{Name}} | ||
| 701 | \end{Produc} | ||
| 702 | |||
| 703 | The expression denoting the table to be indexed has a restricted syntax; | ||
| 704 | see \See{expressions} for details. | ||
| 705 | |||
| 706 | The meaning of assignments and evaluations of global and | ||
| 707 | indexed variables can be changed via metatables. | ||
| 708 | An assignment to a global variable \verb|x = val| | ||
| 709 | is equivalent to the assignment | ||
| 710 | \verb|_glob.x = val|, | ||
| 711 | where \verb|_glob| is the table of globals of the running function | ||
| 712 | (see \See{global-table} for a discussion about the table of globals). | ||
| 713 | An assignment to an indexed variable \verb|t[i] = val| is equivalent to | ||
| 714 | \verb|settable_event(t,i,val)|. | ||
| 715 | An access to a global variable \verb|x| | ||
| 716 | is equivalent to \verb|_glob.x| | ||
| 717 | (again, see \See{global-table} for a discussion about \verb|_glob|). | ||
| 718 | An access to an indexed variable \verb|t[i]| is equivalent to | ||
| 719 | a call \verb|gettable_event(t,i)|. | ||
| 720 | See \See{metatable} for a complete description of the | ||
| 721 | \verb|settable_event| and \verb|gettable_event| functions. | ||
| 722 | (These functions are not defined or callable in Lua. | ||
| 723 | We use them here only for explanatory purposes.) | ||
| 724 | |||
| 725 | |||
| 726 | \subsection{Statements}\label{stats} | ||
| 727 | |||
| 728 | Lua supports an almost conventional set of \Index{statements}, | ||
| 729 | similar to those in Pascal or C. | ||
| 730 | The conventional commands include | ||
| 731 | assignment, control structures, and procedure calls. | ||
| 732 | Non-conventional commands include table constructors | ||
| 733 | and variable declarations. | ||
| 734 | |||
| 735 | \subsubsection{Chunks}\label{chunks} | ||
| 736 | The unit of execution of Lua is called a \Def{chunk}. | ||
| 737 | A chunk is simply a sequence of statements, | ||
| 738 | which are executed sequentially. | ||
| 739 | Each statement can be optionally followed by a semicolon: | ||
| 740 | \begin{Produc} | ||
| 741 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | ||
| 742 | \end{Produc} | ||
| 743 | |||
| 744 | \subsubsection{Blocks} | ||
| 745 | A \Index{block} is a list of statements; | ||
| 746 | syntactically, a block is equal to a chunk: | ||
| 747 | \begin{Produc} | ||
| 748 | \produc{block}{chunk} | ||
| 749 | \end{Produc} | ||
| 750 | |||
| 751 | A block may be explicitly delimited to produce a single statement: | ||
| 752 | \begin{Produc} | ||
| 753 | \produc{stat}{\rwd{do} block \rwd{end}} | ||
| 754 | \end{Produc} | ||
| 755 | \IndexKW{do} | ||
| 756 | Explicit blocks are useful | ||
| 757 | to control the scope of variable declarations. | ||
| 758 | Explicit blocks are also sometimes used to | ||
| 759 | add a \rwd{return} or \rwd{break} statement in the middle | ||
| 760 | of another block \see{control}. | ||
| 761 | |||
| 762 | \subsubsection{\Index{Assignment}} \label{assignment} | ||
| 763 | Lua allows \Index{multiple assignment}. | ||
| 764 | Therefore, the syntax for assignment | ||
| 765 | defines a list of variables on the left side | ||
| 766 | and a list of expressions on the right side. | ||
| 767 | The elements in both lists are separated by commas: | ||
| 768 | \begin{Produc} | ||
| 769 | \produc{stat}{varlist1 \ter{=} explist1} | ||
| 770 | \produc{varlist1}{var \rep{\ter{,} var}} | ||
| 771 | \produc{explist1}{exp \rep{\ter{,} exp}} | ||
| 772 | \end{Produc} | ||
| 773 | Expressions are discussed in \See{expressions}. | ||
| 774 | |||
| 775 | Before the assignment, | ||
| 776 | the list of values is \emph{adjusted} to the length of | ||
| 777 | the list of variables.\index{adjustment} | ||
| 778 | If there are more values than needed, | ||
| 779 | the excess values are thrown away. | ||
| 780 | If there are fewer values than needed, | ||
| 781 | the list is extended with as many \nil{}'s as needed. | ||
| 782 | If the list of expressions ends with a function call, | ||
| 783 | then all values returned by that function call enter in the list of values, | ||
| 784 | before the adjustment | ||
| 785 | (except when the call is enclosed in parentheses; see \See{expressions}). | ||
| 786 | |||
| 787 | The assignment statement first evaluates all its expressions, | ||
| 788 | and only then are the assignments performed. | ||
| 789 | Thus the code | ||
| 790 | \begin{verbatim} | ||
| 791 | i = 3 | ||
| 792 | i, a[i] = i+1, 20 | ||
| 793 | \end{verbatim} | ||
| 794 | sets \verb|a[3]| to 20, without affecting \verb|a[4]| | ||
| 795 | because the \verb|i| in \verb|a[i]| is evaluated | ||
| 796 | before it is assigned 4. | ||
| 797 | Similarly, the line | ||
| 798 | \begin{verbatim} | ||
| 799 | x, y = y, x | ||
| 800 | \end{verbatim} | ||
| 801 | exchanges the values of \verb|x| and \verb|y|. | ||
| 802 | |||
| 803 | \subsubsection{Control Structures}\label{control} | ||
| 804 | The control structures | ||
| 805 | \rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and | ||
| 806 | familiar syntax: | ||
| 807 | \index{while-do statement}\IndexKW{while} | ||
| 808 | \index{repeat-until statement}\IndexKW{repeat}\IndexKW{until} | ||
| 809 | \index{if-then-else statement}\IndexKW{if}\IndexKW{else}\IndexKW{elseif} | ||
| 810 | \begin{Produc} | ||
| 811 | \produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}} | ||
| 812 | \produc{stat}{\rwd{repeat} block \rwd{until} exp} | ||
| 813 | \produc{stat}{\rwd{if} exp \rwd{then} block | ||
| 814 | \rep{\rwd{elseif} exp \rwd{then} block} | ||
| 815 | \opt{\rwd{else} block} \rwd{end}} | ||
| 816 | \end{Produc} | ||
| 817 | Lua also has a \rwd{for} statement, in two flavors \see{for}. | ||
| 818 | |||
| 819 | The \Index{condition expression} \M{exp} of a | ||
| 820 | control structure may return any value. | ||
| 821 | Both \False{} and \nil{} are considered false. | ||
| 822 | All values different from \nil{} and \False{} are considered true | ||
| 823 | (in particular, the number 0 and the empty string are also true). | ||
| 824 | |||
| 825 | The \rwd{return} statement is used to return values | ||
| 826 | from a function or from a chunk.\IndexKW{return} | ||
| 827 | \label{return} | ||
| 828 | \index{return statement} | ||
| 829 | Functions and chunks may return more than one value, | ||
| 830 | so the syntax for the \rwd{return} statement is | ||
| 831 | \begin{Produc} | ||
| 832 | \produc{stat}{\rwd{return} \opt{explist1}} | ||
| 833 | \end{Produc} | ||
| 834 | |||
| 835 | The \rwd{break} statement can be used to terminate the execution of a | ||
| 836 | \rwd{while}, \rwd{repeat}, or \rwd{for} loop, | ||
| 837 | and to skip to the next statement after the loop:\IndexKW{break} | ||
| 838 | \index{break statement} | ||
| 839 | \begin{Produc} | ||
| 840 | \produc{stat}{\rwd{break}} | ||
| 841 | \end{Produc} | ||
| 842 | A \rwd{break} ends the innermost enclosing loop. | ||
| 843 | |||
| 844 | \NOTE | ||
| 845 | For syntactic reasons, \rwd{return} and \rwd{break} | ||
| 846 | statements can only be written as the \emph{last} statement of a block. | ||
| 847 | If it is really necessary to \rwd{return} or \rwd{break} in the | ||
| 848 | middle of a block, | ||
| 849 | then an explicit inner block can used, | ||
| 850 | as in the idioms | ||
| 851 | `\verb|do return end|' and | ||
| 852 | `\verb|do break end|', | ||
| 853 | because now \rwd{return} and \rwd{break} are the last statements in | ||
| 854 | their (inner) blocks. | ||
| 855 | In practice, | ||
| 856 | those idioms are only used during debugging. | ||
| 857 | (For instance, a line `\verb|do return end|' can be added at the | ||
| 858 | beginning of a chunk for syntax checking only.) | ||
| 859 | |||
| 860 | \subsubsection{For Statement} \label{for}\index{for statement} | ||
| 861 | |||
| 862 | The \rwd{for} statement has two forms, | ||
| 863 | one numeric and one generic. | ||
| 864 | \IndexKW{for}\IndexKW{in} | ||
| 865 | |||
| 866 | The numeric \rwd{for} loop repeats a block of code while a | ||
| 867 | control variable runs through an arithmetic progression. | ||
| 868 | It has the following syntax: | ||
| 869 | \begin{Produc} | ||
| 870 | \produc{stat}{\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp} | ||
| 871 | \rwd{do} block \rwd{end}} | ||
| 872 | \end{Produc} | ||
| 873 | The \emph{block} is repeated for \emph{name} starting at the value of | ||
| 874 | the first \emph{exp}, until it passes the second \emph{exp} by steps of the | ||
| 875 | third \emph{exp}. | ||
| 876 | More precisely, a \rwd{for} statement like | ||
| 877 | \begin{verbatim} | ||
| 878 | for var = e1, e2, e3 do block end | ||
| 879 | \end{verbatim} | ||
| 880 | is equivalent to the code: | ||
| 881 | \begin{verbatim} | ||
| 882 | do | ||
| 883 | local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) | ||
| 884 | if not (var and _limit and _step) then error() end | ||
| 885 | while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do | ||
| 886 | block | ||
| 887 | var = var+_step | ||
| 888 | end | ||
| 889 | end | ||
| 890 | \end{verbatim} | ||
| 891 | Note the following: | ||
| 892 | \begin{itemize}\itemsep=0pt | ||
| 893 | \item Both the limit and the step are evaluated only once, | ||
| 894 | before the loop starts. | ||
| 895 | \item \verb|_limit| and \verb|_step| are invisible variables. | ||
| 896 | The names are here for explanatory purposes only. | ||
| 897 | \item The behavior is \emph{undefined} if you assign to \verb|var| inside | ||
| 898 | the block. | ||
| 899 | \item If the third expression (the step) is absent, then a step of\Nb{}1 is used. | ||
| 900 | \item You can use \rwd{break} to exit a \rwd{for} loop. | ||
| 901 | \item The loop variable \verb|var| is local to the statement; | ||
| 902 | you cannot use its value after the \rwd{for} ends or is broken. | ||
| 903 | If you need the value of the loop variable \verb|var|, | ||
| 904 | then assign it to another variable before breaking or exiting the loop. | ||
| 905 | \end{itemize} | ||
| 906 | |||
| 907 | The generic \rwd{for} statement works over functions, | ||
| 908 | called \Index{generators}. | ||
| 909 | It calls its generator to produce a new value for each iteration, | ||
| 910 | stopping when the new value is \nil{}. | ||
| 911 | It has the following syntax: | ||
| 912 | \begin{Produc} | ||
| 913 | \produc{stat}{\rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 | ||
| 914 | \rwd{do} block \rwd{end}} | ||
| 915 | \end{Produc} | ||
| 916 | A \rwd{for} statement like | ||
| 917 | \begin{verbatim} | ||
| 918 | for var_1, ..., var_n in explist do block end | ||
| 919 | \end{verbatim} | ||
| 920 | is equivalent to the code: | ||
| 921 | \begin{verbatim} | ||
| 922 | do | ||
| 923 | local _f, _s, var_1, ..., var_n = explist | ||
| 924 | while true do | ||
| 925 | var_1, ..., var_n = _f(_s, var_1) | ||
| 926 | if var_1 == nil then break end | ||
| 927 | block | ||
| 928 | end | ||
| 929 | end | ||
| 930 | \end{verbatim} | ||
| 931 | Note the following: | ||
| 932 | \begin{itemize}\itemsep=0pt | ||
| 933 | \item \verb|explist| is evaluated only once. | ||
| 934 | Its results are a \Q{generator} function, | ||
| 935 | a \Q{state}, and an initial value for the first \Q{iterator variable}. | ||
| 936 | \item \verb|_f| and \verb|_s| are invisible variables. | ||
| 937 | The names are here for explanatory purposes only. | ||
| 938 | \item The behavior is \emph{undefined} if you assign to any | ||
| 939 | \verb|var_i| inside the block. | ||
| 940 | \item You can use \rwd{break} to exit a \rwd{for} loop. | ||
| 941 | \item The loop variables \verb|var_i| are local to the statement; | ||
| 942 | you cannot use their values after the \rwd{for} ends. | ||
| 943 | If you need these values, | ||
| 944 | then assign them to other variables before breaking or exiting the loop. | ||
| 945 | \end{itemize} | ||
| 946 | |||
| 947 | |||
| 948 | \subsubsection{Function Calls as Statements} \label{funcstat} | ||
| 949 | Because of possible side-effects, | ||
| 950 | function calls can be executed as statements: | ||
| 951 | \begin{Produc} | ||
| 952 | \produc{stat}{functioncall} | ||
| 953 | \end{Produc} | ||
| 954 | In this case, all returned values are thrown away. | ||
| 955 | Function calls are explained in \See{functioncall}. | ||
| 956 | |||
| 957 | \subsubsection{Local Declarations} \label{localvar} | ||
| 958 | \Index{Local variables} may be declared anywhere inside a block. | ||
| 959 | The declaration may include an initial assignment:\IndexKW{local} | ||
| 960 | \begin{Produc} | ||
| 961 | \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} | ||
| 962 | \produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}} | ||
| 963 | \end{Produc} | ||
| 964 | If present, an initial assignment has the same semantics | ||
| 965 | of a multiple assignment \see{assignment}. | ||
| 966 | Otherwise, all variables are initialized with \nil{}. | ||
| 967 | |||
| 968 | A chunk is also a block \see{chunks}, | ||
| 969 | so local variables can be declared outside any explicit block. | ||
| 970 | Such local variables die when the chunk ends. | ||
| 971 | |||
| 972 | Visibility rules for local variables are explained in \See{visibility}. | ||
| 973 | |||
| 974 | |||
| 975 | \subsection{\Index{Expressions}}\label{expressions} | ||
| 976 | |||
| 977 | \C{\subsubsection{\Index{Basic Expressions}}} | ||
| 978 | The basic expressions in Lua are the following: | ||
| 979 | \begin{Produc} | ||
| 980 | \produc{exp}{prefixexp} | ||
| 981 | \produc{exp}{\rwd{nil} \Or \rwd{false} \Or \rwd{true}} | ||
| 982 | \produc{exp}{Number} | ||
| 983 | \produc{exp}{Literal} | ||
| 984 | \produc{exp}{function} | ||
| 985 | \produc{exp}{tableconstructor} | ||
| 986 | \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}} | ||
| 987 | \end{Produc} | ||
| 988 | \IndexKW{nil}\IndexKW{false}\IndexKW{true} | ||
| 989 | |||
| 990 | An expression enclosed in parentheses always results in only one value. | ||
| 991 | Thus, | ||
| 992 | \verb|(f(x,y,z))| is always a single value, | ||
| 993 | even if \verb|f| returns several values. | ||
| 994 | (The value of \verb|(f(x,y,z))| is the first value returned by \verb|f| | ||
| 995 | or \nil{} if \verb|f| does not return any values.) | ||
| 996 | |||
| 997 | \emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; | ||
| 998 | variables are explained in \See{variables}; | ||
| 999 | function definitions are explained in \See{func-def}; | ||
| 1000 | function calls are explained in \See{functioncall}; | ||
| 1001 | table constructors are explained in \See{tableconstructor}. | ||
| 1002 | |||
| 1003 | Expressions can also be built with arithmetic operators, relational operators, | ||
| 1004 | and logical operators, all of which are explained below. | ||
| 1005 | |||
| 1006 | \subsubsection{Arithmetic Operators} | ||
| 1007 | Lua supports the usual \Index{arithmetic operators}: | ||
| 1008 | the binary \verb|+| (addition), | ||
| 1009 | \verb|-| (subtraction), \verb|*| (multiplication), | ||
| 1010 | \verb|/| (division), and \verb|^| (exponentiation); | ||
| 1011 | and unary \verb|-| (negation). | ||
| 1012 | If the operands are numbers, or strings that can be converted to | ||
| 1013 | numbers \see{coercion}, | ||
| 1014 | then all operations except exponentiation have the usual meaning, | ||
| 1015 | while exponentiation calls a global function \verb|pow|; ?? | ||
| 1016 | otherwise, an appropriate metamethod is called \see{metatable}. | ||
| 1017 | The standard mathematical library defines function \verb|pow|, | ||
| 1018 | giving the expected meaning to \Index{exponentiation} | ||
| 1019 | \see{mathlib}. | ||
| 1020 | |||
| 1021 | \subsubsection{Relational Operators}\label{rel-ops} | ||
| 1022 | The \Index{relational operators} in Lua are | ||
| 1023 | \begin{verbatim} | ||
| 1024 | == ~= < > <= >= | ||
| 1025 | \end{verbatim} | ||
| 1026 | These operators always result in \False{} or \True{}. | ||
| 1027 | |||
| 1028 | Equality (\verb|==|) first compares the type of its operands. | ||
| 1029 | If the types are different, then the result is \False{}. | ||
| 1030 | Otherwise, the values of the operands are compared. | ||
| 1031 | Numbers and strings are compared in the usual way. | ||
| 1032 | Tables, userdata, and functions are compared \emph{by reference}, | ||
| 1033 | that is, | ||
| 1034 | two tables are considered equal only if they are the \emph{same} table. | ||
| 1035 | |||
| 1036 | \C{TODO eq metamethod} | ||
| 1037 | |||
| 1038 | Every time you create a new table (or userdata, or function), | ||
| 1039 | this new value is different from any previously existing value. | ||
| 1040 | |||
| 1041 | \NOTE | ||
| 1042 | The conversion rules of \See{coercion} | ||
| 1043 | \emph{do not} apply to equality comparisons. | ||
| 1044 | Thus, \verb|"0"==0| evaluates to \emph{false}, | ||
| 1045 | and \verb|t[0]| and \verb|t["0"]| denote different | ||
| 1046 | entries in a table. | ||
| 1047 | \medskip | ||
| 1048 | |||
| 1049 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). | ||
| 1050 | |||
| 1051 | The order operators work as follows. | ||
| 1052 | If both arguments are numbers, then they are compared as such. | ||
| 1053 | Otherwise, if both arguments are strings, | ||
| 1054 | then their values are compared according to the current locale. | ||
| 1055 | Otherwise, the \Q{lt} or the \Q{le} metamethod is called \see{metatable}. | ||
| 1056 | |||
| 1057 | |||
| 1058 | \subsubsection{Logical Operators} | ||
| 1059 | The \Index{logical operators} in Lua are | ||
| 1060 | \index{and}\index{or}\index{not} | ||
| 1061 | \begin{verbatim} | ||
| 1062 | and or not | ||
| 1063 | \end{verbatim} | ||
| 1064 | Like the control structures \see{control}, | ||
| 1065 | all logical operators consider both \False{} and \nil{} as false | ||
| 1066 | and anything else as true. | ||
| 1067 | \IndexKW{and}\IndexKW{or}\IndexKW{not} | ||
| 1068 | |||
| 1069 | The operator \rwd{not} always return \False{} or \True{}. | ||
| 1070 | |||
| 1071 | The conjunction operator \rwd{and} returns its first argument | ||
| 1072 | if its value is \False{} or \nil{}; | ||
| 1073 | otherwise, \rwd{and} returns its second argument. | ||
| 1074 | The disjunction operator \rwd{or} returns its first argument | ||
| 1075 | if it is different from \nil{} and \False{}; | ||
| 1076 | otherwise, \rwd{or} returns its second argument. | ||
| 1077 | Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation}, | ||
| 1078 | that is, | ||
| 1079 | the second operand is evaluated only if necessary. | ||
| 1080 | For example, | ||
| 1081 | \begin{verbatim} | ||
| 1082 | 10 or error() -> 10 | ||
| 1083 | nil or "a" -> "a" | ||
| 1084 | nil and 10 -> nil | ||
| 1085 | false and error() -> false | ||
| 1086 | false and nil -> false | ||
| 1087 | false or nil -> nil | ||
| 1088 | 10 and 20 -> 20 | ||
| 1089 | \end{verbatim} | ||
| 1090 | |||
| 1091 | \subsubsection{Concatenation} \label{concat} | ||
| 1092 | The string \Index{concatenation} operator in Lua is | ||
| 1093 | denoted by two dots (`\verb|..|'). | ||
| 1094 | If both operands are strings or numbers, then they are converted to | ||
| 1095 | strings according to the rules mentioned in \See{coercion}. | ||
| 1096 | Otherwise, the \Q{concat} metamethod is called \see{metatable}. | ||
| 1097 | |||
| 1098 | \subsubsection{Precedence} | ||
| 1099 | \Index{Operator precedence} in Lua follows the table below, | ||
| 1100 | from lower to higher priority: | ||
| 1101 | \begin{verbatim} | ||
| 1102 | or | ||
| 1103 | and | ||
| 1104 | < > <= >= ~= == | ||
| 1105 | .. | ||
| 1106 | + - | ||
| 1107 | * / | ||
| 1108 | not - (unary) | ||
| 1109 | ^ | ||
| 1110 | \end{verbatim} | ||
| 1111 | The \verb|..| (concatenation) and \verb|^| (exponentiation) | ||
| 1112 | operators are right associative. | ||
| 1113 | All other binary operators are left associative. | ||
| 1114 | |||
| 1115 | \subsubsection{Table Constructors} \label{tableconstructor} | ||
| 1116 | Table \Index{constructors} are expressions that create tables; | ||
| 1117 | every time a constructor is evaluated, a new table is created. | ||
| 1118 | Constructors can be used to create empty tables, | ||
| 1119 | or to create a table and initialize some of its fields. | ||
| 1120 | The general syntax for constructors is | ||
| 1121 | \begin{Produc} | ||
| 1122 | \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}} | ||
| 1123 | \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}} | ||
| 1124 | \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or | ||
| 1125 | \Nter{Name} \ter{=} exp \Or exp} | ||
| 1126 | \produc{fieldsep}{\ter{,} \Or \ter{;}} | ||
| 1127 | \end{Produc} | ||
| 1128 | |||
| 1129 | Each field of the form \verb|[exp1] = exp2| adds to the new table an entry | ||
| 1130 | with key \verb|exp1| and value \verb|exp2|. | ||
| 1131 | A field of the form \verb|name = exp| is equivalent to | ||
| 1132 | \verb|["name"] = exp|. | ||
| 1133 | Finally, fields of the form \verb|exp| are equivalent to | ||
| 1134 | \verb|[i] = exp|, where \verb|i| are consecutive numerical integers, | ||
| 1135 | starting with 1. | ||
| 1136 | Fields in the other formats do not affect this counting. | ||
| 1137 | For example, | ||
| 1138 | \begin{verbatim} | ||
| 1139 | a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45} | ||
| 1140 | \end{verbatim} | ||
| 1141 | is equivalent to | ||
| 1142 | \begin{verbatim} | ||
| 1143 | do | ||
| 1144 | local temp = {} | ||
| 1145 | temp[f(1)] = g | ||
| 1146 | temp[1] = "x" -- 1st exp | ||
| 1147 | temp[2] = "y" -- 2nd exp | ||
| 1148 | temp.x = 1 -- temp["x"] = 1 | ||
| 1149 | temp[3] = f(x) -- 3rd exp | ||
| 1150 | temp[30] = 23 | ||
| 1151 | temp[4] = 45 -- 4th exp | ||
| 1152 | a = temp | ||
| 1153 | end | ||
| 1154 | \end{verbatim} | ||
| 1155 | |||
| 1156 | If the last expression in the list is a function call, | ||
| 1157 | then all values returned by the call enter the list consecutively | ||
| 1158 | \see{functioncall}. | ||
| 1159 | If you want to avoid this, | ||
| 1160 | enclose the function call in parentheses. | ||
| 1161 | |||
| 1162 | The field list may have an optional trailing separator, | ||
| 1163 | as a convenience for machine-generated code. | ||
| 1164 | |||
| 1165 | |||
| 1166 | \subsubsection{Function Calls} \label{functioncall} | ||
| 1167 | A \Index{function call} in Lua has the following syntax: | ||
| 1168 | \begin{Produc} | ||
| 1169 | \produc{functioncall}{prefixexp args} | ||
| 1170 | \end{Produc} | ||
| 1171 | In a function call, | ||
| 1172 | first \M{prefixexp} and \M{args} are evaluated. | ||
| 1173 | If the value of \M{prefixexp} has type \emph{function}, | ||
| 1174 | then that function is called, | ||
| 1175 | with the given arguments. | ||
| 1176 | Otherwise, its \Q{call} metamethod is called, | ||
| 1177 | having as first parameter the value of \M{prefixexp}, | ||
| 1178 | followed by the original call arguments | ||
| 1179 | \see{metatable}. | ||
| 1180 | |||
| 1181 | The form | ||
| 1182 | \begin{Produc} | ||
| 1183 | \produc{functioncall}{prefixexp \ter{:} \Nter{name} args} | ||
| 1184 | \end{Produc} | ||
| 1185 | can be used to call \Q{methods}. | ||
| 1186 | A call \verb|v:name(...)| | ||
| 1187 | is syntactic sugar for \verb|v.name(v, ...)|, | ||
| 1188 | except that \verb|v| is evaluated only once. | ||
| 1189 | |||
| 1190 | Arguments have the following syntax: | ||
| 1191 | \begin{Produc} | ||
| 1192 | \produc{args}{\ter{(} \opt{explist1} \ter{)}} | ||
| 1193 | \produc{args}{tableconstructor} | ||
| 1194 | \produc{args}{Literal} | ||
| 1195 | \end{Produc} | ||
| 1196 | All argument expressions are evaluated before the call. | ||
| 1197 | A call of the form \verb|f{...}| is syntactic sugar for | ||
| 1198 | \verb|f({...})|, that is, | ||
| 1199 | the argument list is a single new table. | ||
| 1200 | A call of the form \verb|f'...'| | ||
| 1201 | (or \verb|f"..."| or \verb|f[[...]]|) is syntactic sugar for | ||
| 1202 | \verb|f('...')|, that is, | ||
| 1203 | the argument list is a single literal string. | ||
| 1204 | |||
| 1205 | Because a function can return any number of results | ||
| 1206 | \see{return}, | ||
| 1207 | the number of results must be adjusted before they are used. | ||
| 1208 | If the function is called as a statement \see{funcstat}, | ||
| 1209 | then its return list is adjusted to\Nb{}0 elements, | ||
| 1210 | thus discarding all returned values. | ||
| 1211 | If the function is called inside another expression, | ||
| 1212 | or in the middle of a list of expressions, | ||
| 1213 | then its return list is adjusted to\Nb{}1 element, | ||
| 1214 | thus discarding all returned values but the first one. | ||
| 1215 | If the function is called as the last element of a list of expressions, | ||
| 1216 | then no adjustment is made | ||
| 1217 | (unless the call is enclosed in parentheses). | ||
| 1218 | |||
| 1219 | Here are some examples: | ||
| 1220 | \begin{verbatim} | ||
| 1221 | f() -- adjusted to 0 results | ||
| 1222 | g(f(), x) -- f() is adjusted to 1 result | ||
| 1223 | g(x, f()) -- g gets x plus all values returned by f() | ||
| 1224 | a,b,c = f(), x -- f() is adjusted to 1 result (and c gets nil) | ||
| 1225 | a,b,c = x, f() -- f() is adjusted to 2 | ||
| 1226 | a,b,c = f() -- f() is adjusted to 3 | ||
| 1227 | return f() -- returns all values returned by f() | ||
| 1228 | return x,y,f() -- returns x, y, and all values returned by f() | ||
| 1229 | {f()} -- creates a list with all values returned by f() | ||
| 1230 | {f(), nil} -- f() is adjusted to 1 result | ||
| 1231 | \end{verbatim} | ||
| 1232 | |||
| 1233 | If you enclose a function call in parentheses, | ||
| 1234 | then it is adjusted to return exactly one value: | ||
| 1235 | \begin{verbatim} | ||
| 1236 | return x,y,(f()) -- returns x, y, and the first value from f() | ||
| 1237 | {(f())} -- creates a table with exactly one element | ||
| 1238 | \end{verbatim} | ||
| 1239 | |||
| 1240 | As an exception to the format-free syntax of Lua, | ||
| 1241 | you cannot put a line break before the \verb|(| in a function call. | ||
| 1242 | That restriction avoids some ambiguities in the language. | ||
| 1243 | If you write | ||
| 1244 | \begin{verbatim} | ||
| 1245 | a = f | ||
| 1246 | (g).x(a) | ||
| 1247 | \end{verbatim} | ||
| 1248 | Lua would read that as \verb|a = f(g).x(a)|. | ||
| 1249 | So, if you want two statements, you must add a semi-colon between them. | ||
| 1250 | If you actually want to call \verb|f|, | ||
| 1251 | you must remove the line break before \verb|(g)|. | ||
| 1252 | |||
| 1253 | |||
| 1254 | \subsubsection{\Index{Function Definitions}} \label{func-def} | ||
| 1255 | |||
| 1256 | The syntax for function definition is\IndexKW{function} | ||
| 1257 | \begin{Produc} | ||
| 1258 | \produc{function}{\rwd{function} funcbody} | ||
| 1259 | \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}} | ||
| 1260 | \end{Produc} | ||
| 1261 | |||
| 1262 | The following syntactic sugar simplifies function definitions: | ||
| 1263 | \begin{Produc} | ||
| 1264 | \produc{stat}{\rwd{function} funcname funcbody} | ||
| 1265 | \produc{stat}{\rwd{local} \rwd{function} \Nter{name} funcbody} | ||
| 1266 | \produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} \opt{\ter{:} \Nter{name}}} | ||
| 1267 | \end{Produc} | ||
| 1268 | The statement | ||
| 1269 | \begin{verbatim} | ||
| 1270 | function f () ... end | ||
| 1271 | \end{verbatim} | ||
| 1272 | translates to | ||
| 1273 | \begin{verbatim} | ||
| 1274 | f = function () ... end | ||
| 1275 | \end{verbatim} | ||
| 1276 | The statement | ||
| 1277 | \begin{verbatim} | ||
| 1278 | function t.a.b.c.f () ... end | ||
| 1279 | \end{verbatim} | ||
| 1280 | translates to | ||
| 1281 | \begin{verbatim} | ||
| 1282 | t.a.b.c.f = function () ... end | ||
| 1283 | \end{verbatim} | ||
| 1284 | The statement | ||
| 1285 | \begin{verbatim} | ||
| 1286 | local function f () ... end | ||
| 1287 | \end{verbatim} | ||
| 1288 | translates to | ||
| 1289 | \begin{verbatim} | ||
| 1290 | local f; f = function () ... end | ||
| 1291 | \end{verbatim} | ||
| 1292 | |||
| 1293 | A function definition is an executable expression, | ||
| 1294 | whose value has type \emph{function}. | ||
| 1295 | When Lua pre-compiles a chunk, | ||
| 1296 | all its function bodies are pre-compiled too. | ||
| 1297 | Then, whenever Lua executes the function definition, | ||
| 1298 | the function is \emph{instantiated} (or \emph{closed}). | ||
| 1299 | This function instance (or \emph{closure}) | ||
| 1300 | is the final value of the expression. | ||
| 1301 | Different instances of the same function | ||
| 1302 | may refer to different non-local variables \see{visibility} | ||
| 1303 | and may have different tables of globals \see{global-table}. | ||
| 1304 | |||
| 1305 | Parameters act as local variables that are | ||
| 1306 | initialized with the argument values: | ||
| 1307 | \begin{Produc} | ||
| 1308 | \produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}} | ||
| 1309 | \produc{parlist1}{\ter{\ldots}} | ||
| 1310 | \end{Produc} | ||
| 1311 | \label{vararg} | ||
| 1312 | When a function is called, | ||
| 1313 | the list of \Index{arguments} is adjusted to | ||
| 1314 | the length of the list of parameters, | ||
| 1315 | unless the function is a \Def{vararg function}, | ||
| 1316 | which is | ||
| 1317 | indicated by three dots (`\verb|...|') at the end of its parameter list. | ||
| 1318 | A vararg function does not adjust its argument list; | ||
| 1319 | instead, it collects all extra arguments into an implicit parameter, | ||
| 1320 | called \IndexLIB{arg}. | ||
| 1321 | The value of \verb|arg| is a table, | ||
| 1322 | with a field\Nb{}\verb|n| whose value is the number of extra arguments, | ||
| 1323 | and with the extra arguments at positions 1,\Nb{}2,\Nb{}\ldots,\Nb{}\verb|n|. | ||
| 1324 | |||
| 1325 | As an example, consider the following definitions: | ||
| 1326 | \begin{verbatim} | ||
| 1327 | function f(a, b) end | ||
| 1328 | function g(a, b, ...) end | ||
| 1329 | function r() return 1,2,3 end | ||
| 1330 | \end{verbatim} | ||
| 1331 | Then, we have the following mapping from arguments to parameters: | ||
| 1332 | \begin{verbatim} | ||
| 1333 | CALL PARAMETERS | ||
| 1334 | |||
| 1335 | f(3) a=3, b=nil | ||
| 1336 | f(3, 4) a=3, b=4 | ||
| 1337 | f(3, 4, 5) a=3, b=4 | ||
| 1338 | f(r(), 10) a=1, b=10 | ||
| 1339 | f(r()) a=1, b=2 | ||
| 1340 | |||
| 1341 | g(3) a=3, b=nil, arg={n=0} | ||
| 1342 | g(3, 4) a=3, b=4, arg={n=0} | ||
| 1343 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} | ||
| 1344 | g(5, r()) a=5, b=1, arg={2, 3; n=2} | ||
| 1345 | \end{verbatim} | ||
| 1346 | |||
| 1347 | Results are returned using the \rwd{return} statement \see{return}. | ||
| 1348 | If control reaches the end of a function | ||
| 1349 | without encountering a \rwd{return} statement, | ||
| 1350 | then the function returns with no results. | ||
| 1351 | |||
| 1352 | The \emph{colon} syntax | ||
| 1353 | is used for defining \IndexEmph{methods}, | ||
| 1354 | that is, functions that have an implicit extra parameter \IndexVerb{self}. | ||
| 1355 | Thus, the statement | ||
| 1356 | \begin{verbatim} | ||
| 1357 | function t.a.b.c:f (...) ... end | ||
| 1358 | \end{verbatim} | ||
| 1359 | is syntactic sugar for | ||
| 1360 | \begin{verbatim} | ||
| 1361 | t.a.b.c.f = function (self, ...) ... end | ||
| 1362 | \end{verbatim} | ||
| 1363 | |||
| 1364 | |||
| 1365 | \subsection{Visibility Rules} \label{visibility} | ||
| 1366 | \index{visibility} | ||
| 1367 | |||
| 1368 | Lua is a lexically scoped language. | ||
| 1369 | The scope of variables begins at the first statement \emph{after} | ||
| 1370 | their declaration and lasts until the end of the innermost block that | ||
| 1371 | includes the declaration. | ||
| 1372 | For instance: | ||
| 1373 | \begin{verbatim} | ||
| 1374 | x = 10 -- global variable | ||
| 1375 | do -- new block | ||
| 1376 | local x = x -- new `x', with value 10 | ||
| 1377 | print(x) --> 10 | ||
| 1378 | x = x+1 | ||
| 1379 | do -- another block | ||
| 1380 | local x = x+1 -- another `x' | ||
| 1381 | print(x) --> 12 | ||
| 1382 | end | ||
| 1383 | print(x) --> 11 | ||
| 1384 | end | ||
| 1385 | print(x) --> 10 (the global one) | ||
| 1386 | \end{verbatim} | ||
| 1387 | Notice that, in a declaration like \verb|local x = x|, | ||
| 1388 | the new \verb|x| being declared is not in scope yet, | ||
| 1389 | so the second \verb|x| refers to the \Q{outside} variable. | ||
| 1390 | |||
| 1391 | Because of these \Index{lexical scoping} rules, | ||
| 1392 | local variables can be freely accessed by functions | ||
| 1393 | defined inside their scope. | ||
| 1394 | For instance: | ||
| 1395 | \begin{verbatim} | ||
| 1396 | local counter = 0 | ||
| 1397 | function inc (x) | ||
| 1398 | counter = counter + x | ||
| 1399 | return counter | ||
| 1400 | end | ||
| 1401 | \end{verbatim} | ||
| 1402 | |||
| 1403 | Notice that each execution of a \rwd{local} statement | ||
| 1404 | \Q{creates} new local variables. | ||
| 1405 | Consider the following example: | ||
| 1406 | \begin{verbatim} | ||
| 1407 | a = {} | ||
| 1408 | local x = 20 | ||
| 1409 | for i=1,10 do | ||
| 1410 | local y = 0 | ||
| 1411 | a[i] = function () y=y+1; return x+y end | ||
| 1412 | end | ||
| 1413 | \end{verbatim} | ||
| 1414 | The loop creates ten closures | ||
| 1415 | (that is, instances of the anonymous function). | ||
| 1416 | Each of these closures uses a different \verb|y| variable, | ||
| 1417 | while all of them share the same \verb|x|. | ||
| 1418 | |||
| 1419 | \subsection{Error Handling} \label{error} | ||
| 1420 | |||
| 1421 | Because Lua is an extension language, | ||
| 1422 | all Lua actions start from C\Nb{}code in the host program | ||
| 1423 | calling a function from the Lua library \see{pcall}. | ||
| 1424 | Whenever an error occurs during Lua compilation or execution, | ||
| 1425 | control returns to C, | ||
| 1426 | which can take appropriate measures | ||
| 1427 | (such as to print an error message). | ||
| 1428 | |||
| 1429 | Lua code can explicitly generate an error by calling the | ||
| 1430 | function \verb|error| \see{pdf-error}. | ||
| 1431 | If you need to catch errors in Lua, | ||
| 1432 | you can use the \verb|pcall| function \see{pdf-pcall}. | ||
| 1433 | |||
| 1434 | |||
| 1435 | \subsection{Metatables} \label{metatable} | ||
| 1436 | |||
| 1437 | Every table and userdata value in Lua may have a \emph{metatable}. | ||
| 1438 | This \IndexEmph{metatable} is a table that defines the behavior of | ||
| 1439 | the original table and userdata under certain special operations. | ||
| 1440 | You can query and change the metatable of an object with | ||
| 1441 | functions \verb|setmetatable| and \verb|getmetatable| \see{pdf-getmetatable}. | ||
| 1442 | |||
| 1443 | For each of those operations Lua associates a specific key | ||
| 1444 | called an \emph{event}. | ||
| 1445 | When Lua performs one of those operations over a table or a userdata, | ||
| 1446 | it checks whether that object has a metatable with the corresponding event. | ||
| 1447 | If so, the value associated with that key (the \IndexEmph{metamethod}) | ||
| 1448 | controls how Lua will perform the operation. | ||
| 1449 | |||
| 1450 | Metatables control the operations listed next. | ||
| 1451 | Each operation is identified by its corresponding name. | ||
| 1452 | The key for each operation is a string with its name prefixed by | ||
| 1453 | two underscores; | ||
| 1454 | for instance, the key for operation \Q{add} is the | ||
| 1455 | string \verb|"__add"|. | ||
| 1456 | The semantics of these operations is better explained by a Lua function | ||
| 1457 | describing how the interpreter executes that operation. | ||
| 1458 | \C{Each function shows how a handler is called,} | ||
| 1459 | \C{its arguments (that is, its signature),} | ||
| 1460 | \C{its results,} | ||
| 1461 | \C{and the default behavior in the absence of a handler.} | ||
| 1462 | The code shown here in Lua is only illustrative; | ||
| 1463 | the real behavior is hard coded in the interpreter, | ||
| 1464 | and it is much more efficient than this simulation. | ||
| 1465 | All functions used in these descriptions | ||
| 1466 | (\verb|rawget|, \verb|tonumber|, etc.) | ||
| 1467 | are described in \See{predefined}. | ||
| 1468 | |||
| 1469 | \begin{description} | ||
| 1470 | |||
| 1471 | \item[\Q{add}:]\IndexTM{add} | ||
| 1472 | the \verb|+| operation. | ||
| 1473 | |||
| 1474 | The function \verb|getbinhandler| below defines how Lua chooses a handler | ||
| 1475 | for a binary operation. | ||
| 1476 | First, Lua tries the first operand. | ||
| 1477 | If its type does not define a handler for the operation, | ||
| 1478 | then Lua tries the second operand. | ||
| 1479 | \begin{verbatim} | ||
| 1480 | function getbinhandler (op1, op2, event) | ||
| 1481 | return metatable(op1)[event] or metatable(op2)[event] | ||
| 1482 | end | ||
| 1483 | \end{verbatim} | ||
| 1484 | Using that function, | ||
| 1485 | the behavior of the \Q{add} operation is | ||
| 1486 | \begin{verbatim} | ||
| 1487 | function add_event (op1, op2) | ||
| 1488 | local o1, o2 = tonumber(op1), tonumber(op2) | ||
| 1489 | if o1 and o2 then -- both operands are numeric | ||
| 1490 | return o1+o2 -- '+' here is the primitive 'add' | ||
| 1491 | else -- at least one of the operands is not numeric | ||
| 1492 | local h = getbinhandler(op1, op2, "__add") | ||
| 1493 | if h then | ||
| 1494 | -- call the handler with both operands | ||
| 1495 | return h(op1, op2) | ||
| 1496 | else -- no handler available: default behavior | ||
| 1497 | error("unexpected type at arithmetic operation") | ||
| 1498 | end | ||
| 1499 | end | ||
| 1500 | end | ||
| 1501 | \end{verbatim} | ||
| 1502 | |||
| 1503 | \item[\Q{sub}:]\IndexTM{sub} | ||
| 1504 | the \verb|-| operation. | ||
| 1505 | Behavior similar to the \Q{add} operation. | ||
| 1506 | |||
| 1507 | \item[\Q{mul}:]\IndexTM{mul} | ||
| 1508 | the \verb|*| operation. | ||
| 1509 | Behavior similar to the \Q{add} operation. | ||
| 1510 | |||
| 1511 | \item[\Q{div}:]\IndexTM{div} | ||
| 1512 | the \verb|/| operation. | ||
| 1513 | Behavior similar to the \Q{add} operation. | ||
| 1514 | |||
| 1515 | \item[\Q{pow}:]\IndexTM{pow} | ||
| 1516 | the \verb|^| operation (exponentiation) operation. | ||
| 1517 | \begin{verbatim} ?? | ||
| 1518 | function pow_event (op1, op2) | ||
| 1519 | local h = getbinhandler(op1, op2, "__pow") ??? | ||
| 1520 | if h then | ||
| 1521 | -- call the handler with both operands | ||
| 1522 | return h(op1, op2) | ||
| 1523 | else -- no handler available: default behavior | ||
| 1524 | error("unexpected type at arithmetic operation") | ||
| 1525 | end | ||
| 1526 | end | ||
| 1527 | \end{verbatim} | ||
| 1528 | |||
| 1529 | \item[\Q{unm}:]\IndexTM{unm} | ||
| 1530 | the unary \verb|-| operation. | ||
| 1531 | \begin{verbatim} | ||
| 1532 | function unm_event (op) | ||
| 1533 | local o = tonumber(op) | ||
| 1534 | if o then -- operand is numeric | ||
| 1535 | return -o -- '-' here is the primitive 'unm' | ||
| 1536 | else -- the operand is not numeric. | ||
| 1537 | -- Try to get a handler from the operand; | ||
| 1538 | local h = metatable(op).__unm | ||
| 1539 | if h then | ||
| 1540 | -- call the handler with the operand and nil | ||
| 1541 | return h(op, nil) | ||
| 1542 | else -- no handler available: default behavior | ||
| 1543 | error("unexpected type at arithmetic operation") | ||
| 1544 | end | ||
| 1545 | end | ||
| 1546 | end | ||
| 1547 | \end{verbatim} | ||
| 1548 | |||
| 1549 | \item[\Q{lt}:]\IndexTM{lt} | ||
| 1550 | the \verb|<| operation. | ||
| 1551 | \begin{verbatim} | ||
| 1552 | function lt_event (op1, op2) | ||
| 1553 | if type(op1) == "number" and type(op2) == "number" then | ||
| 1554 | return op1 < op2 -- numeric comparison | ||
| 1555 | elseif type(op1) == "string" and type(op2) == "string" then | ||
| 1556 | return op1 < op2 -- lexicographic comparison | ||
| 1557 | else | ||
| 1558 | local h = getbinhandler(op1, op2, "__lt") | ||
| 1559 | if h then | ||
| 1560 | return h(op1, op2) | ||
| 1561 | else | ||
| 1562 | error("unexpected type at comparison"); | ||
| 1563 | end | ||
| 1564 | end | ||
| 1565 | end | ||
| 1566 | \end{verbatim} | ||
| 1567 | \verb|a>b| is equivalent to \verb|b<a|. | ||
| 1568 | |||
| 1569 | \item[\Q{le}:]\IndexTM{lt} | ||
| 1570 | the \verb|<=| operation. | ||
| 1571 | \begin{verbatim} | ||
| 1572 | function le_event (op1, op2) | ||
| 1573 | if type(op1) == "number" and type(op2) == "number" then | ||
| 1574 | return op1 <= op2 -- numeric comparison | ||
| 1575 | elseif type(op1) == "string" and type(op2) == "string" then | ||
| 1576 | return op1 <= op2 -- lexicographic comparison | ||
| 1577 | else | ||
| 1578 | local h = getbinhandler(op1, op2, "__le") | ||
| 1579 | if h then | ||
| 1580 | return h(op1, op2) | ||
| 1581 | else | ||
| 1582 | h = getbinhandler(op1, op2, "__lt") | ||
| 1583 | if h then | ||
| 1584 | return not h(op2, op1) | ||
| 1585 | else | ||
| 1586 | error("unexpected type at comparison"); | ||
| 1587 | end | ||
| 1588 | end | ||
| 1589 | end | ||
| 1590 | end | ||
| 1591 | \end{verbatim} | ||
| 1592 | \verb|a>=b| is equivalent to \verb|b<=a|. | ||
| 1593 | Notice that, in the absence of a \Q{le} metamethod, | ||
| 1594 | Lua tries the \Q{lt}, assuming that \verb|a<=b| is | ||
| 1595 | equivalent to \verb|not (b<a)|. | ||
| 1596 | |||
| 1597 | |||
| 1598 | \item[\Q{concat}:]\IndexTM{concatenation} | ||
| 1599 | the \verb|..| (concatenation) operation. | ||
| 1600 | \begin{verbatim} | ||
| 1601 | function concat_event (op1, op2) | ||
| 1602 | if (type(op1) == "string" or type(op1) == "number") and | ||
| 1603 | (type(op2) == "string" or type(op2) == "number") then | ||
| 1604 | return op1..op2 -- primitive string concatenation | ||
| 1605 | else | ||
| 1606 | local h = getbinhandler(op1, op2, "__concat") | ||
| 1607 | if h then | ||
| 1608 | return h(op1, op2) | ||
| 1609 | else | ||
| 1610 | error("unexpected type for concatenation") | ||
| 1611 | end | ||
| 1612 | end | ||
| 1613 | end | ||
| 1614 | \end{verbatim} | ||
| 1615 | |||
| 1616 | \item[\Q{index}:]\IndexTM{index} | ||
| 1617 | The \Q{gettable} operation \verb|table[key]|. | ||
| 1618 | \begin{verbatim} | ||
| 1619 | function gettable_event (table, key) | ||
| 1620 | local h | ||
| 1621 | if type(table) == "table" then | ||
| 1622 | local v = rawget(table, key) | ||
| 1623 | if v ~= nil then return v end | ||
| 1624 | h = metatable(table).__index | ||
| 1625 | if h == nil then return nil end | ||
| 1626 | else | ||
| 1627 | h = metatable(table).__index | ||
| 1628 | if h == nil then | ||
| 1629 | error("indexed expression not a table"); | ||
| 1630 | end | ||
| 1631 | end | ||
| 1632 | if type(h) == "function" then | ||
| 1633 | return h(table, key) -- call the handler | ||
| 1634 | else return h[key] -- or repeat operation with it | ||
| 1635 | end | ||
| 1636 | \end{verbatim} | ||
| 1637 | |||
| 1638 | \item[\Q{newindex}:]\IndexTM{index} | ||
| 1639 | The \Q{settable} operation \verb|table[key] = value|. | ||
| 1640 | \begin{verbatim} | ||
| 1641 | function settable_event (table, key, value) | ||
| 1642 | local h | ||
| 1643 | if type(table) == "table" then | ||
| 1644 | local v = rawget(table, key) | ||
| 1645 | if v ~= nil then rawset(table, key, value); return end | ||
| 1646 | h = metatable(table).__newindex | ||
| 1647 | if h == nil then rawset(table, key, value); return end | ||
| 1648 | else | ||
| 1649 | h = metatable(table).__newindex | ||
| 1650 | if h == nil then | ||
| 1651 | error("indexed expression not a table"); | ||
| 1652 | end | ||
| 1653 | end | ||
| 1654 | if type(h) == "function" then | ||
| 1655 | return h(table, key,value) -- call the handler | ||
| 1656 | else h[key] = value -- or repeat operation with it | ||
| 1657 | end | ||
| 1658 | \end{verbatim} | ||
| 1659 | |||
| 1660 | |||
| 1661 | \item[\Q{call}:]\IndexTM{call} | ||
| 1662 | called when Lua calls a value. | ||
| 1663 | \begin{verbatim} | ||
| 1664 | function function_event (func, ...) | ||
| 1665 | if type(func) == "function" then | ||
| 1666 | return func(unpack(arg)) -- regular call | ||
| 1667 | else | ||
| 1668 | local h = metatable(func).__call | ||
| 1669 | if h then | ||
| 1670 | table.insert(arg, 1, func) | ||
| 1671 | return h(unpack(arg)) | ||
| 1672 | else | ||
| 1673 | error("call expression not a function") | ||
| 1674 | end | ||
| 1675 | end | ||
| 1676 | end | ||
| 1677 | \end{verbatim} | ||
| 1678 | |||
| 1679 | \end{description} | ||
| 1680 | |||
| 1681 | \subsubsection{Metatables and Garbage collection} | ||
| 1682 | |||
| 1683 | Metatables may also define \IndexEmph{finalizer} methods | ||
| 1684 | for userdata values. | ||
| 1685 | For each userdata to be collected, | ||
| 1686 | Lua does the equivalent of the following function: | ||
| 1687 | \begin{verbatim} | ||
| 1688 | function gc_event (obj) | ||
| 1689 | local h = metatable(obj).__gc | ||
| 1690 | if h then | ||
| 1691 | h(obj) | ||
| 1692 | end | ||
| 1693 | end | ||
| 1694 | \end{verbatim} | ||
| 1695 | In a garbage-collection cycle, | ||
| 1696 | the finalizers for userdata are called in \emph{reverse} | ||
| 1697 | order of their creation, | ||
| 1698 | that is, the first finalizer to be called is the one associated | ||
| 1699 | with the last userdata created in the program | ||
| 1700 | (among those to be collected in the same cycle). | ||
| 1701 | |||
| 1702 | |||
| 1703 | |||
| 1704 | \subsection{Coroutines} | ||
| 1705 | |||
| 1706 | Lua supports coroutines, | ||
| 1707 | also called \emph{semi-coroutines} | ||
| 1708 | or \emph{collaborative multithreading}. | ||
| 1709 | A coroutine in Lua represents an independent thread of execution. | ||
| 1710 | Unlike \Q{real} threads, however, | ||
| 1711 | a coroutine only suspends its execution by explicitly calling | ||
| 1712 | an yield function. | ||
| 1713 | |||
| 1714 | You create a coroutine with a call to \IndexVerb{coroutine.create}. | ||
| 1715 | Its sole argument is a function | ||
| 1716 | that is the main function of the coroutine. | ||
| 1717 | The \verb|coroutine.create| only creates a new coroutine and | ||
| 1718 | returns a handle to it (an object of type \emph{thread}). | ||
| 1719 | It does not start the coroutine execution. | ||
| 1720 | |||
| 1721 | When you first call \IndexVerb{coroutine.resume}, | ||
| 1722 | passing as argument the thread returned by \verb|coroutine.create|, | ||
| 1723 | the coroutine starts its execution, | ||
| 1724 | at the first line of its main function. | ||
| 1725 | Extra arguments passed to \verb|coroutine.resume| are given as | ||
| 1726 | parameters for the coroutine main function. | ||
| 1727 | After the coroutine starts running, | ||
| 1728 | it runs until it terminates or it \emph{yields}. | ||
| 1729 | |||
| 1730 | A coroutine can terminate its execution in two ways: | ||
| 1731 | Normally, when its main function returns | ||
| 1732 | (explicitly or implicitly, after the last instruction); | ||
| 1733 | and abnormally, if there is an unprotected error. | ||
| 1734 | In the first case, \verb|coroutine.resume| returns \True{}, | ||
| 1735 | plus any values returned by the coroutine main function. | ||
| 1736 | In case of errors, \verb|coroutine.resume| returns \False{} | ||
| 1737 | plus an error message. | ||
| 1738 | |||
| 1739 | A coroutine yields by calling \IndexVerb{coroutine.yield}. | ||
| 1740 | When a coroutine yields, | ||
| 1741 | the corresponding \verb|coroutine.resume| returns immediately, | ||
| 1742 | even if the yield happens inside nested function calls | ||
| 1743 | (that is, not in the main function, | ||
| 1744 | but in a function directly or indirectly called by the main function). | ||
| 1745 | In the case of a yield, \verb|coroutine.resume| also returns \True{}, | ||
| 1746 | plus any values passed to \verb|coroutine.yield|. | ||
| 1747 | The next time you resume the same coroutine, | ||
| 1748 | it continues its execution from the point where it yielded, | ||
| 1749 | with the call to \verb|coroutine.yield| returning any extra | ||
| 1750 | arguments passed to \verb|coroutine.resume|. | ||
| 1751 | |||
| 1752 | The \IndexVerb{coroutine.wrap} function creates a coroutine | ||
| 1753 | like \verb|coroutine.create|, | ||
| 1754 | but instead of returning the coroutine itself, | ||
| 1755 | it returns a function that, when called, resumes the coroutine. | ||
| 1756 | Any arguments passed to that function | ||
| 1757 | go as extra arguments to resume. | ||
| 1758 | The function returns all the values returned by resume, | ||
| 1759 | but the first one (the boolean error code). | ||
| 1760 | Unlike \verb|coroutine.resume|, | ||
| 1761 | this function does not catch errors; | ||
| 1762 | any error is propagated to the caller. | ||
| 1763 | |||
| 1764 | As a complete example, | ||
| 1765 | consider the next code: | ||
| 1766 | \begin{verbatim} | ||
| 1767 | function foo1 (a) | ||
| 1768 | print("foo", a) | ||
| 1769 | return coroutine.yield(2*a) | ||
| 1770 | end | ||
| 1771 | |||
| 1772 | co = coroutine.create(function (a,b) | ||
| 1773 | print("co-body", a, b) | ||
| 1774 | local r = foo1(a+1) | ||
| 1775 | print("co-body", r) | ||
| 1776 | local r, s = coroutine.yield(a+b, a-b) | ||
| 1777 | print("co-body", r, s) | ||
| 1778 | return b, "end" | ||
| 1779 | end) | ||
| 1780 | |||
| 1781 | a, b = coroutine.resume(co, 1, 10) | ||
| 1782 | print("main", a, b) | ||
| 1783 | a, b, c = coroutine.resume(co, "r") | ||
| 1784 | print("main", a, b, c) | ||
| 1785 | a, b, c = coroutine.resume(co, "x", "y") | ||
| 1786 | print("main", a, b, c) | ||
| 1787 | a, b = coroutine.resume(co, "x", "y") | ||
| 1788 | print("main", a, b) | ||
| 1789 | \end{verbatim} | ||
| 1790 | When you run it, it produces the following output: | ||
| 1791 | \begin{verbatim} | ||
| 1792 | co-body 1 10 | ||
| 1793 | foo 2 | ||
| 1794 | main true 4 | ||
| 1795 | co-body r | ||
| 1796 | main true 11 -9 | ||
| 1797 | co-body x y | ||
| 1798 | main true 10 end | ||
| 1799 | main false cannot resume dead coroutine | ||
| 1800 | \end{verbatim} | ||
| 1801 | |||
| 1802 | |||
| 1803 | |||
| 1804 | \C{-------------------------------------------------------------------------} | ||
| 1805 | \section{The Application Program Interface}\label{API} | ||
| 1806 | \index{C API} | ||
| 1807 | |||
| 1808 | This section describes the API for Lua, that is, | ||
| 1809 | the set of C\Nb{}functions available to the host program to communicate | ||
| 1810 | with Lua. | ||
| 1811 | All API functions and related types and constants | ||
| 1812 | are declared in the header file \verb|lua.h|. | ||
| 1813 | |||
| 1814 | \NOTE | ||
| 1815 | Even when we use the term \Q{function}, | ||
| 1816 | any facility in the API may be provided as a \emph{macro} instead. | ||
| 1817 | All such macros use each of its arguments exactly once | ||
| 1818 | (except for the first argument, which is always a Lua state), | ||
| 1819 | and so do not generate hidden side-effects. | ||
| 1820 | |||
| 1821 | |||
| 1822 | \subsection{States} \label{mangstate} | ||
| 1823 | |||
| 1824 | The Lua library is fully reentrant: | ||
| 1825 | it has no global variables. | ||
| 1826 | \index{state} | ||
| 1827 | The whole state of the Lua interpreter | ||
| 1828 | (global variables, stack, etc.) | ||
| 1829 | is stored in a dynamically allocated structure of type \verb|lua_State|; | ||
| 1830 | \DefAPI{lua_State} | ||
| 1831 | this state must be passed as the first argument to | ||
| 1832 | every function in the library (except \verb|lua_open| below). | ||
| 1833 | |||
| 1834 | Before calling any API function, | ||
| 1835 | you must create a state by calling | ||
| 1836 | \begin{verbatim} | ||
| 1837 | lua_State *lua_open (void); | ||
| 1838 | \end{verbatim} | ||
| 1839 | \DefAPI{lua_open} | ||
| 1840 | |||
| 1841 | To release a state created with \verb|lua_open|, call | ||
| 1842 | \begin{verbatim} | ||
| 1843 | void lua_close (lua_State *L); | ||
| 1844 | \end{verbatim} | ||
| 1845 | \DefAPI{lua_close} | ||
| 1846 | This function destroys all objects in the given Lua environment | ||
| 1847 | (calling the corresponding garbage-collection metamethods, if any) | ||
| 1848 | and frees all dynamic memory used by that state. | ||
| 1849 | On several platforms, you may not need to call this function, | ||
| 1850 | because all resources are naturally released when the host program ends. | ||
| 1851 | On the other hand, | ||
| 1852 | long-running programs \Em{} | ||
| 1853 | like a daemon or a web server \Em{} | ||
| 1854 | might need to release states as soon as they are not needed, | ||
| 1855 | to avoid growing too large. | ||
| 1856 | |||
| 1857 | |||
| 1858 | \subsection{Threads} | ||
| 1859 | |||
| 1860 | Lua offers partial support for multiple threads of execution. | ||
| 1861 | If you have a C\Nb{}library that offers multi-threading, | ||
| 1862 | then Lua can cooperate with it to implement the equivalent facility in Lua. | ||
| 1863 | Also, Lua implements its own coroutine system on top of threads. | ||
| 1864 | The following function creates a new \Q{thread} in Lua: | ||
| 1865 | \begin{verbatim} | ||
| 1866 | lua_State *lua_newthread (lua_State *L); | ||
| 1867 | \end{verbatim} | ||
| 1868 | \DefAPI{lua_newthread} | ||
| 1869 | The new state returned by this function shares with the original state | ||
| 1870 | all global environment (such as tables), | ||
| 1871 | but has an independent run-time stack. | ||
| 1872 | (The use of these multiple stacks must be \Q{synchronized} with C. | ||
| 1873 | How to explain that? TO BE WRITTEN.) | ||
| 1874 | |||
| 1875 | Each thread has an independent table for global variables. | ||
| 1876 | When you create a thread, this table is the same as that of the given state, | ||
| 1877 | but you can change each one independently. | ||
| 1878 | |||
| 1879 | You destroy threads with \DefAPI{lua_closethread} | ||
| 1880 | \begin{verbatim} | ||
| 1881 | void lua_closethread (lua_State *L, lua_State *thread); | ||
| 1882 | \end{verbatim} | ||
| 1883 | You cannot close the sole (or last) thread of a state. | ||
| 1884 | Instead, you must close the state itself. | ||
| 1885 | |||
| 1886 | |||
| 1887 | \subsection{The Stack and Indices} | ||
| 1888 | |||
| 1889 | Lua uses a virtual \emph{stack} to pass values to and from C. | ||
| 1890 | Each element in this stack represents a Lua value | ||
| 1891 | (\nil{}, number, string, etc.). | ||
| 1892 | |||
| 1893 | Each C invocation has its own stack. | ||
| 1894 | Whenever Lua calls C, the called function gets a new stack, | ||
| 1895 | which is independent of previous stacks and of stacks of still | ||
| 1896 | active C functions. | ||
| 1897 | That stack initially contains any arguments to the C function, | ||
| 1898 | and it is where the C function pushes its results \see{LuacallC}. | ||
| 1899 | |||
| 1900 | For convenience, | ||
| 1901 | most query operations in the API do not follow a strict stack discipline. | ||
| 1902 | Instead, they can refer to any element in the stack by using an \emph{index}: | ||
| 1903 | A positive index represents an \emph{absolute} stack position | ||
| 1904 | (starting at\Nb{}1); | ||
| 1905 | a negative index represents an \emph{offset} from the top of the stack. | ||
| 1906 | More specifically, if the stack has \M{n} elements, | ||
| 1907 | then index\Nb{}1 represents the first element | ||
| 1908 | (that is, the element that was pushed onto the stack first), | ||
| 1909 | and | ||
| 1910 | index\Nb{}\M{n} represents the last element; | ||
| 1911 | index\Nb{}\Math{-1} also represents the last element | ||
| 1912 | (that is, the element at the top), | ||
| 1913 | and index \Math{-n} represents the first element. | ||
| 1914 | We say that an index is \emph{valid} | ||
| 1915 | if it lies between\Nb{}1 and the stack top | ||
| 1916 | (that is, if \verb|1 <= abs(index) <= top|). | ||
| 1917 | \index{stack index} \index{valid index} | ||
| 1918 | |||
| 1919 | At any time, you can get the index of the top element by calling | ||
| 1920 | \begin{verbatim} | ||
| 1921 | int lua_gettop (lua_State *L); | ||
| 1922 | \end{verbatim} | ||
| 1923 | \DefAPI{lua_gettop} | ||
| 1924 | Because indices start at\Nb{}1, | ||
| 1925 | the result of \verb|lua_gettop| is equal to the number of elements in the stack | ||
| 1926 | (and so 0\Nb{}means an empty stack). | ||
| 1927 | |||
| 1928 | When you interact with Lua API, | ||
| 1929 | \emph{you are responsible for controlling stack overflow}. | ||
| 1930 | The function | ||
| 1931 | \begin{verbatim} | ||
| 1932 | int lua_checkstack (lua_State *L, int extra); | ||
| 1933 | \end{verbatim} | ||
| 1934 | \DefAPI{lua_checkstack} | ||
| 1935 | grows the stack size to \verb|top + extra| elements; | ||
| 1936 | it returns false if it cannot grow the stack to that size. | ||
| 1937 | This function never shrinks the stack; | ||
| 1938 | if the stack is already bigger than the new size, | ||
| 1939 | it is left unchanged. | ||
| 1940 | |||
| 1941 | Whenever Lua calls C, \DefAPI{LUA_MINSTACK} | ||
| 1942 | it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true, | ||
| 1943 | that is, | ||
| 1944 | at least \verb|LUA_MINSTACK| positions are still available. | ||
| 1945 | \verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20, | ||
| 1946 | so that usually you do not have to worry about stack space | ||
| 1947 | unless your code has loops pushing elements onto the stack. | ||
| 1948 | |||
| 1949 | Most query functions accept as indices any value inside the | ||
| 1950 | available stack space, that is, indices up to the maximum stack size | ||
| 1951 | you (or Lua) have set through \verb|lua_checkstack|. | ||
| 1952 | Such indices are called \emph{acceptable indices}. | ||
| 1953 | More formally, we define an \IndexEmph{acceptable index} | ||
| 1954 | as follows: | ||
| 1955 | \begin{verbatim} | ||
| 1956 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) | ||
| 1957 | \end{verbatim} | ||
| 1958 | Note that 0 is never an acceptable index. | ||
| 1959 | |||
| 1960 | Unless otherwise noted, | ||
| 1961 | any function that accepts valid indices can also be called with | ||
| 1962 | \Index{pseudo-indices}, | ||
| 1963 | which represent some Lua values that are accessible to the C\Nb{}code | ||
| 1964 | but are not in the stack. | ||
| 1965 | Pseudo-indices are used to access the table of globals \see{globals}, | ||
| 1966 | the registry, and the upvalues of a C function \see{c-closure}. | ||
| 1967 | |||
| 1968 | \subsection{Stack Manipulation} | ||
| 1969 | The API offers the following functions for basic stack manipulation: | ||
| 1970 | \begin{verbatim} | ||
| 1971 | void lua_settop (lua_State *L, int index); | ||
| 1972 | void lua_pushvalue (lua_State *L, int index); | ||
| 1973 | void lua_remove (lua_State *L, int index); | ||
| 1974 | void lua_insert (lua_State *L, int index); | ||
| 1975 | void lua_replace (lua_State *L, int index); | ||
| 1976 | \end{verbatim} | ||
| 1977 | \DefAPI{lua_settop}\DefAPI{lua_pushvalue} | ||
| 1978 | \DefAPI{lua_remove}\DefAPI{lua_insert}\DefAPI{lua_replace} | ||
| 1979 | |||
| 1980 | \verb|lua_settop| accepts any acceptable index, | ||
| 1981 | or 0, | ||
| 1982 | and sets the stack top to that index. | ||
| 1983 | If the new top is larger than the old one, | ||
| 1984 | then the new elements are filled with \nil{}. | ||
| 1985 | If \verb|index| is 0, then all stack elements are removed. | ||
| 1986 | A useful macro defined in the \verb|lua.h| is | ||
| 1987 | \begin{verbatim} | ||
| 1988 | #define lua_pop(L,n) lua_settop(L, -(n)-1) | ||
| 1989 | \end{verbatim} | ||
| 1990 | \DefAPI{lua_pop} | ||
| 1991 | which pops \verb|n| elements from the stack. | ||
| 1992 | |||
| 1993 | \verb|lua_pushvalue| pushes onto the stack a copy of the element | ||
| 1994 | at the given index. | ||
| 1995 | \verb|lua_remove| removes the element at the given position, | ||
| 1996 | shifting down the elements above that position to fill the gap. | ||
| 1997 | \verb|lua_insert| moves the top element into the given position, | ||
| 1998 | shifting up the elements above that position to open space. | ||
| 1999 | \verb|lua_replace| moves the top element into the given position, | ||
| 2000 | without shifting any element (therefore replacing the value at | ||
| 2001 | the given position). | ||
| 2002 | These functions accept only valid indices. | ||
| 2003 | (Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with | ||
| 2004 | pseudo-indices, as they do not represent a stack position.) | ||
| 2005 | |||
| 2006 | As an example, if the stack starts as \verb|10 20 30 40 50*| | ||
| 2007 | (from bottom to top; the \verb|*| marks the top), | ||
| 2008 | then | ||
| 2009 | \begin{verbatim} | ||
| 2010 | lua_pushvalue(L, 3) --> 10 20 30 40 50 30* | ||
| 2011 | lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* | ||
| 2012 | lua_remove(L, -3) --> 10 20 30 40 30 30* | ||
| 2013 | lua_remove(L, 6) --> 10 20 30 40 30* | ||
| 2014 | lua_insert(L, 1) --> 30 10 20 30 40* | ||
| 2015 | lua_insert(L, -1) --> 30 10 20 30 40* (no effect) | ||
| 2016 | lua_replace(L, 2) --> 30 40 20 30* | ||
| 2017 | lua_settop(L, -3) --> 30 40* | ||
| 2018 | lua_settop(L, 6) --> 30 40 nil nil nil nil* | ||
| 2019 | \end{verbatim} | ||
| 2020 | |||
| 2021 | |||
| 2022 | |||
| 2023 | \subsection{Querying the Stack} | ||
| 2024 | |||
| 2025 | To check the type of a stack element, | ||
| 2026 | the following functions are available: | ||
| 2027 | \begin{verbatim} | ||
| 2028 | int lua_type (lua_State *L, int index); | ||
| 2029 | int lua_isnil (lua_State *L, int index); | ||
| 2030 | int lua_isboolean (lua_State *L, int index); | ||
| 2031 | int lua_isnumber (lua_State *L, int index); | ||
| 2032 | int lua_isstring (lua_State *L, int index); | ||
| 2033 | int lua_istable (lua_State *L, int index); | ||
| 2034 | int lua_isfunction (lua_State *L, int index); | ||
| 2035 | int lua_iscfunction (lua_State *L, int index); | ||
| 2036 | int lua_isuserdata (lua_State *L, int index); | ||
| 2037 | int lua_islightuserdata (lua_State *L, int index); | ||
| 2038 | \end{verbatim} | ||
| 2039 | \DefAPI{lua_type} | ||
| 2040 | \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} | ||
| 2041 | \DefAPI{lua_istable}\DefAPI{lua_isboolean} | ||
| 2042 | \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction} | ||
| 2043 | \DefAPI{lua_isuserdata}\DefAPI{lua_islightuserdata} | ||
| 2044 | These functions can be called with any acceptable index. | ||
| 2045 | |||
| 2046 | \verb|lua_type| returns the type of a value in the stack, | ||
| 2047 | or \verb|LUA_TNONE| for a non-valid index | ||
| 2048 | (that is, if that stack position is \Q{empty}). | ||
| 2049 | The types are coded by the following constants | ||
| 2050 | defined in \verb|lua.h|: | ||
| 2051 | \verb|LUA_TNIL|, | ||
| 2052 | \verb|LUA_TNUMBER|, | ||
| 2053 | \verb|LUA_TBOOLEAN|, | ||
| 2054 | \verb|LUA_TSTRING|, | ||
| 2055 | \verb|LUA_TTABLE|, | ||
| 2056 | \verb|LUA_TFUNCTION|, | ||
| 2057 | \verb|LUA_TUSERDATA|, | ||
| 2058 | \verb|LUA_TTHREAD|, | ||
| 2059 | \verb|LUA_TLIGHTUSERDATA|. | ||
| 2060 | The following function translates such constants to a type name: | ||
| 2061 | \begin{verbatim} | ||
| 2062 | const char *lua_typename (lua_State *L, int type); | ||
| 2063 | \end{verbatim} | ||
| 2064 | \DefAPI{lua_typename} | ||
| 2065 | |||
| 2066 | The \verb|lua_is*| functions return\Nb{}1 if the object is compatible | ||
| 2067 | with the given type, and 0 otherwise. | ||
| 2068 | \verb|lua_isboolean| is an exception to this rule, | ||
| 2069 | and it succeeds only for boolean values | ||
| 2070 | (otherwise it would be useless, | ||
| 2071 | as any value has a boolean value). | ||
| 2072 | They always return 0 for a non-valid index. | ||
| 2073 | \verb|lua_isnumber| accepts numbers and numerical strings, | ||
| 2074 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, | ||
| 2075 | \verb|lua_isfunction| accepts both Lua functions and C\Nb{}functions, | ||
| 2076 | and \verb|lua_isuserdata| accepts both full and light userdata. | ||
| 2077 | To distinguish between Lua functions and C\Nb{}functions, | ||
| 2078 | you should use \verb|lua_iscfunction|. | ||
| 2079 | To distinguish between full and light userdata, | ||
| 2080 | you can use \verb|lua_islightuserdata|. | ||
| 2081 | To distinguish between numbers and numerical strings, | ||
| 2082 | you can use \verb|lua_type|. | ||
| 2083 | |||
| 2084 | The API also has functions to compare two values in the stack: | ||
| 2085 | \begin{verbatim} | ||
| 2086 | int lua_equal (lua_State *L, int index1, int index2); | ||
| 2087 | int lua_lessthan (lua_State *L, int index1, int index2); | ||
| 2088 | \end{verbatim} | ||
| 2089 | \DefAPI{lua_equal} \DefAPI{lua_lessthan} | ||
| 2090 | These functions are equivalent to their counterparts in Lua \see{rel-ops}. | ||
| 2091 | Both functions return 0 if any of the indices are non-valid. | ||
| 2092 | |||
| 2093 | \subsection{Getting Values from the Stack}\label{lua-to} | ||
| 2094 | |||
| 2095 | To translate a value in the stack to a specific C\Nb{}type, | ||
| 2096 | you can use the following conversion functions: | ||
| 2097 | \begin{verbatim} | ||
| 2098 | int lua_toboolean (lua_State *L, int index); | ||
| 2099 | lua_Number lua_tonumber (lua_State *L, int index); | ||
| 2100 | const char *lua_tostring (lua_State *L, int index); | ||
| 2101 | size_t lua_strlen (lua_State *L, int index); | ||
| 2102 | lua_CFunction lua_tocfunction (lua_State *L, int index); | ||
| 2103 | void *lua_touserdata (lua_State *L, int index); | ||
| 2104 | \end{verbatim} | ||
| 2105 | \DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen} | ||
| 2106 | \DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}\DefAPI{lua_toboolean} | ||
| 2107 | These functions can be called with any acceptable index. | ||
| 2108 | When called with a non-valid index, | ||
| 2109 | they act as if the given value had an incorrect type. | ||
| 2110 | |||
| 2111 | \verb|lua_toboolean| converts the Lua value at the given index | ||
| 2112 | to a C \Q{boolean} value (that is, 0 or 1). | ||
| 2113 | Like all tests in Lua, it returns 1 for any Lua value different from | ||
| 2114 | \False{} and \nil{}; | ||
| 2115 | otherwise it returns 0. | ||
| 2116 | It also returns 0 when called with a non-valid index. | ||
| 2117 | (If you want to accept only real boolean values, | ||
| 2118 | use \verb|lua_isboolean| to test the type of the value.) | ||
| 2119 | |||
| 2120 | \verb|lua_tonumber| converts the Lua value at the given index | ||
| 2121 | to a number (by default, \verb|lua_Number| is \verb|double|). | ||
| 2122 | \DefAPI{lua_Number} | ||
| 2123 | The Lua value must be a number or a string convertible to number | ||
| 2124 | \see{coercion}; otherwise, \verb|lua_tonumber| returns\Nb{}0. | ||
| 2125 | |||
| 2126 | \verb|lua_tostring| converts the Lua value at the given index to a string | ||
| 2127 | (\verb|const char*|). | ||
| 2128 | The Lua value must be a string or a number; | ||
| 2129 | otherwise, the function returns \verb|NULL|. | ||
| 2130 | If the value is a number, | ||
| 2131 | then \verb|lua_tostring| also | ||
| 2132 | \emph{changes the actual value in the stack to a string}. | ||
| 2133 | (This change confuses \verb|lua_next| | ||
| 2134 | when \verb|lua_tostring| is applied to keys.) | ||
| 2135 | \verb|lua_tostring| returns a fully aligned pointer | ||
| 2136 | to a string inside the Lua environment. | ||
| 2137 | This string always has a zero (\verb|'\0'|) | ||
| 2138 | after its last character (as in\Nb{}C), | ||
| 2139 | but may contain other zeros in its body. | ||
| 2140 | If you do not know whether a string may contain zeros, | ||
| 2141 | you can use \verb|lua_strlen| to get its actual length. | ||
| 2142 | Because Lua has garbage collection, | ||
| 2143 | there is no guarantee that the pointer returned by \verb|lua_tostring| | ||
| 2144 | will be valid after the corresponding value is removed from the stack. | ||
| 2145 | If you need the string after the current function returns, | ||
| 2146 | then you should duplicate it (or put it into the registry \see{registry}). | ||
| 2147 | |||
| 2148 | \verb|lua_tocfunction| converts a value in the stack to a C\Nb{}function. | ||
| 2149 | This value must be a C\Nb{}function; | ||
| 2150 | otherwise, \verb|lua_tocfunction| returns \verb|NULL|. | ||
| 2151 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. | ||
| 2152 | |||
| 2153 | \verb|lua_touserdata| is explained in \See{userdata}. | ||
| 2154 | |||
| 2155 | |||
| 2156 | \subsection{Pushing Values onto the Stack} | ||
| 2157 | |||
| 2158 | The API has the following functions to | ||
| 2159 | push C\Nb{}values onto the stack: | ||
| 2160 | \begin{verbatim} | ||
| 2161 | void lua_pushboolean (lua_State *L, int b); | ||
| 2162 | void lua_pushnumber (lua_State *L, lua_Number n); | ||
| 2163 | void lua_pushlstring (lua_State *L, const char *s, size_t len); | ||
| 2164 | void lua_pushstring (lua_State *L, const char *s); | ||
| 2165 | void lua_pushnil (lua_State *L); | ||
| 2166 | void lua_pushcfunction (lua_State *L, lua_CFunction f); | ||
| 2167 | void lua_pushlightuserdata (lua_State *L, void *p); | ||
| 2168 | \end{verbatim} | ||
| 2169 | |||
| 2170 | \DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} | ||
| 2171 | \DefAPI{lua_pushcfunction}\DefAPI{lua_pushlightuserdata}\DefAPI{lua_pushboolean} | ||
| 2172 | \DefAPI{lua_pushnil}\label{pushing} | ||
| 2173 | These functions receive a C\Nb{}value, | ||
| 2174 | convert it to a corresponding Lua value, | ||
| 2175 | and push the result onto the stack. | ||
| 2176 | In particular, \verb|lua_pushlstring| and \verb|lua_pushstring| | ||
| 2177 | make an internal copy of the given string. | ||
| 2178 | \verb|lua_pushstring| can only be used to push proper C\Nb{}strings | ||
| 2179 | (that is, strings that end with a zero and do not contain embedded zeros); | ||
| 2180 | otherwise, you should use the more general \verb|lua_pushlstring|, | ||
| 2181 | which accepts an explicit size. | ||
| 2182 | |||
| 2183 | You can also push \Q{formatted} strings: | ||
| 2184 | \begin{verbatim} | ||
| 2185 | const char *lua_pushfstring (lua_State *L, const char *fmt, ...); | ||
| 2186 | const char *lua_pushvfstring (lua_State *L, const char *fmt, | ||
| 2187 | va_list argp); | ||
| 2188 | \end{verbatim} | ||
| 2189 | \DefAPI{lua_pushfstring}\DefAPI{lua_pushvfstring} | ||
| 2190 | Both functions push onto the stack a formatted string, | ||
| 2191 | and return a pointer to that string. | ||
| 2192 | These functions are similar to \verb|sprintf| and \verb|vsprintf|, | ||
| 2193 | but with some important differences: | ||
| 2194 | \begin{itemize} | ||
| 2195 | \item You do not have to allocate the space for the result; | ||
| 2196 | the result is a Lua string, and Lua takes care of memory allocation | ||
| 2197 | (and deallocation, later). | ||
| 2198 | \item The conversion specifiers are quite restricted. | ||
| 2199 | There are no flags, widths, or precisions. | ||
| 2200 | The conversion specifiers can be simply | ||
| 2201 | \verb|%%| (inserts a \verb|%| in the string), | ||
| 2202 | \verb|%s| (inserts a zero-terminated string, with no size restrictions), | ||
| 2203 | \verb|%f| (inserts a \verb|lua_Number|), | ||
| 2204 | \verb|%d| (inserts an \verb|int|), | ||
| 2205 | \verb|%c| (inserts an \verb|int| as a character). | ||
| 2206 | \end{itemize} | ||
| 2207 | |||
| 2208 | |||
| 2209 | \subsection{Controlling Garbage Collection}\label{GC-API} | ||
| 2210 | |||
| 2211 | Lua uses two numbers to control its garbage collection: | ||
| 2212 | the \emph{count} and the \emph{threshold} \see{GC}. | ||
| 2213 | The first counts the amount of memory in use by Lua; | ||
| 2214 | when the count reaches the threshold, | ||
| 2215 | Lua runs its garbage collector. | ||
| 2216 | After the collection, the count is updated, | ||
| 2217 | and the threshold is set to twice the count value. | ||
| 2218 | |||
| 2219 | You can access the current values of these two numbers through the | ||
| 2220 | following functions: | ||
| 2221 | \begin{verbatim} | ||
| 2222 | int lua_getgccount (lua_State *L); | ||
| 2223 | int lua_getgcthreshold (lua_State *L); | ||
| 2224 | \end{verbatim} | ||
| 2225 | \DefAPI{lua_getgcthreshold} \DefAPI{lua_getgccount} | ||
| 2226 | Both return their respective values in Kbytes. | ||
| 2227 | You can change the threshold value with | ||
| 2228 | \begin{verbatim} | ||
| 2229 | void lua_setgcthreshold (lua_State *L, int newthreshold); | ||
| 2230 | \end{verbatim} | ||
| 2231 | \DefAPI{lua_setgcthreshold} | ||
| 2232 | Again, the \verb|newthreshold| value is given in Kbytes. | ||
| 2233 | When you call this function, | ||
| 2234 | Lua sets the new threshold and checks it against the byte counter. | ||
| 2235 | If the new threshold is smaller than the byte counter, | ||
| 2236 | then Lua immediately runs the garbage collector. | ||
| 2237 | In particular | ||
| 2238 | \verb|lua_setgcthreshold(L,0)| forces a garbage collection. | ||
| 2239 | After the collection, | ||
| 2240 | a new threshold is set according to the previous rule. | ||
| 2241 | |||
| 2242 | \C{TODO do we need a new way to do that??} | ||
| 2243 | \C{ If you want to change the adaptive behavior of the garbage collector,} | ||
| 2244 | \C{ you can use the garbage-collection tag method for \nil{} } | ||
| 2245 | \C{ to set your own threshold} | ||
| 2246 | \C{ (the tag method is called after Lua resets the threshold).} | ||
| 2247 | |||
| 2248 | |||
| 2249 | \subsection{Userdata}\label{userdata} | ||
| 2250 | |||
| 2251 | Userdata represents C values in Lua. | ||
| 2252 | Lua supports two types of userdata: | ||
| 2253 | \Def{full userdata} and \Def{light userdata}. | ||
| 2254 | |||
| 2255 | A full userdata represents a block of memory. | ||
| 2256 | It is an object (like a table): | ||
| 2257 | You must create it, it can have its own metatable, | ||
| 2258 | and you can detect when it is being collected. | ||
| 2259 | A full userdata is only equal to itself (under raw equality). | ||
| 2260 | |||
| 2261 | A light userdata represents a pointer. | ||
| 2262 | It is a value (like a number): | ||
| 2263 | You do not create it, it has no metatables, | ||
| 2264 | it is not collected (as it was never created). | ||
| 2265 | A light userdata is equal to \Q{any} | ||
| 2266 | light userdata with the same address. | ||
| 2267 | |||
| 2268 | In Lua code, there is no way to test whether a userdata is full or light; | ||
| 2269 | both have type \verb|userdata|. | ||
| 2270 | In C code, \verb|lua_type| returns \verb|LUA_TUSERDATA| for full userdata, | ||
| 2271 | and \verb|LUA_LIGHTUSERDATA| for light userdata. | ||
| 2272 | |||
| 2273 | You can create new full userdata with the following function: | ||
| 2274 | \begin{verbatim} | ||
| 2275 | void *lua_newuserdata (lua_State *L, size_t size); | ||
| 2276 | \end{verbatim} | ||
| 2277 | \DefAPI{lua_newuserdata} | ||
| 2278 | It allocates a new block of memory with the given size, | ||
| 2279 | pushes on the stack a new userdata with the block address, | ||
| 2280 | and returns this address. | ||
| 2281 | |||
| 2282 | To push a light userdata into the stack you use | ||
| 2283 | \verb|lua_pushlightuserdata| \see{pushing}. | ||
| 2284 | |||
| 2285 | \verb|lua_touserdata| \see{lua-to} retrieves the value of a userdata. | ||
| 2286 | When applied on a full userdata, it returns the address of its block; | ||
| 2287 | when applied on a light userdata, it returns its pointer; | ||
| 2288 | when applied on a non-userdata value, it returns \verb|NULL|. | ||
| 2289 | |||
| 2290 | When Lua collects a full userdata, | ||
| 2291 | it calls its \verb|gc| metamethod, if any, | ||
| 2292 | and then it frees its corresponding memory. | ||
| 2293 | |||
| 2294 | |||
| 2295 | \subsection{Metatables} | ||
| 2296 | |||
| 2297 | The following functions allow you to manipulate the metatables | ||
| 2298 | of an object: | ||
| 2299 | \begin{verbatim} | ||
| 2300 | int lua_getmetatable (lua_State *L, int objindex); | ||
| 2301 | int lua_setmetatable (lua_State *L, int objindex); | ||
| 2302 | \end{verbatim} | ||
| 2303 | \DefAPI{lua_getmetatable}\DefAPI{lua_setmetatable} | ||
| 2304 | Both get at \verb|objindex| a valid index for an object. | ||
| 2305 | \verb|lua_getmetatable| pushes on the stack the metatable of that object; | ||
| 2306 | \verb|lua_setmetatable| sets the table on the top of the stack as the | ||
| 2307 | new metatable for that object (and pops the table). | ||
| 2308 | |||
| 2309 | If the object does not have a metatable, | ||
| 2310 | \verb|lua_getmetatable| returns 0, and pushes nothing on the stack. | ||
| 2311 | \verb|lua_setmetatable| returns 0 when it cannot | ||
| 2312 | set the metatable of the given object | ||
| 2313 | (that is, when the object is not a userdata nor a table); | ||
| 2314 | even then it pops the table from the stack. | ||
| 2315 | |||
| 2316 | \subsection{Loading Lua Chunks} | ||
| 2317 | |||
| 2318 | You can load a Lua chunk with | ||
| 2319 | \begin{verbatim} | ||
| 2320 | typedef const char * (*lua_Chunkreader) | ||
| 2321 | (lua_State *L, void *data, size_t *size); | ||
| 2322 | |||
| 2323 | int lua_load (lua_State *L, lua_Chunkreader reader, void *data, | ||
| 2324 | const char *chunkname); | ||
| 2325 | \end{verbatim} | ||
| 2326 | \DefAPI{Chunkreader}\DefAPI{lua_load} | ||
| 2327 | The return values of \verb|lua_load| are: | ||
| 2328 | \begin{itemize} | ||
| 2329 | \item 0 \Em{} no errors; | ||
| 2330 | \item \IndexAPI{LUA_ERRSYNTAX} \Em{} | ||
| 2331 | syntax error during pre-compilation. | ||
| 2332 | \item \IndexAPI{LUA_ERRMEM} \Em{} | ||
| 2333 | memory allocation error. | ||
| 2334 | \end{itemize} | ||
| 2335 | If there are no errors, | ||
| 2336 | \verb|lua_load| pushes the compiled chunk as a Lua | ||
| 2337 | function on top of the stack. | ||
| 2338 | Otherwise, it pushes an error message. | ||
| 2339 | |||
| 2340 | \verb|lua_load| automatically detects whether the chunk is text or binary, | ||
| 2341 | and loads it accordingly (see program \IndexVerb{luac}). | ||
| 2342 | |||
| 2343 | \verb|lua_load| uses the \emph{reader} to read the chunk. | ||
| 2344 | Everytime it needs another piece of the chunk, | ||
| 2345 | it calls the reader, | ||
| 2346 | passing along its \verb|data| parameter. | ||
| 2347 | The reader must return a pointer to a block of memory | ||
| 2348 | with a new part of the chunk, | ||
| 2349 | and set \verb|size| to the block size. | ||
| 2350 | To signal the end of the chunk, the reader must return \verb|NULL|. | ||
| 2351 | The reader function may return pieces of any size greater than zero. | ||
| 2352 | |||
| 2353 | In the current implementation, | ||
| 2354 | the reader function cannot call any Lua function; | ||
| 2355 | to ensure that, it always receives \verb|NULL| as the Lua state. | ||
| 2356 | |||
| 2357 | The \emph{chunkname} is used for error messages | ||
| 2358 | and debug information \see{debugI}. | ||
| 2359 | |||
| 2360 | See the auxiliary library (\verb|lauxlib|) | ||
| 2361 | for examples of how to use \verb|lua_load|, | ||
| 2362 | and for some ready-to-use functions to load chunks | ||
| 2363 | from files and from strings. | ||
| 2364 | |||
| 2365 | \subsection{Manipulating Tables} | ||
| 2366 | |||
| 2367 | Tables are created by calling | ||
| 2368 | the function | ||
| 2369 | \begin{verbatim} | ||
| 2370 | void lua_newtable (lua_State *L); | ||
| 2371 | \end{verbatim} | ||
| 2372 | \DefAPI{lua_newtable} | ||
| 2373 | This function creates a new, empty table and pushes it onto the stack. | ||
| 2374 | |||
| 2375 | To read a value from a table that resides somewhere in the stack, | ||
| 2376 | call | ||
| 2377 | \begin{verbatim} | ||
| 2378 | void lua_gettable (lua_State *L, int index); | ||
| 2379 | \end{verbatim} | ||
| 2380 | \DefAPI{lua_gettable} | ||
| 2381 | where \verb|index| points to the table. | ||
| 2382 | \verb|lua_gettable| pops a key from the stack | ||
| 2383 | and returns (on the stack) the contents of the table at that key. | ||
| 2384 | The table is left where it was in the stack; | ||
| 2385 | this is convenient for getting multiple values from a table. | ||
| 2386 | |||
| 2387 | As in Lua, this function may trigger a metamethod | ||
| 2388 | for the \Q{index} event \see{metatable}. | ||
| 2389 | To get the real value of any table key, | ||
| 2390 | without invoking any metamethod, | ||
| 2391 | use the \emph{raw} version: | ||
| 2392 | \begin{verbatim} | ||
| 2393 | void lua_rawget (lua_State *L, int index); | ||
| 2394 | \end{verbatim} | ||
| 2395 | \DefAPI{lua_rawget} | ||
| 2396 | |||
| 2397 | To store a value into a table that resides somewhere in the stack, | ||
| 2398 | you push the key and the value onto the stack | ||
| 2399 | (in this order), | ||
| 2400 | and then call | ||
| 2401 | \begin{verbatim} | ||
| 2402 | void lua_settable (lua_State *L, int index); | ||
| 2403 | \end{verbatim} | ||
| 2404 | \DefAPI{lua_settable} | ||
| 2405 | where \verb|index| points to the table. | ||
| 2406 | \verb|lua_settable| pops from the stack both the key and the value. | ||
| 2407 | The table is left where it was in the stack; | ||
| 2408 | this is convenient for setting multiple values in a table. | ||
| 2409 | |||
| 2410 | As in Lua, this operation may trigger a metamethod | ||
| 2411 | for the \Q{settable} or \Q{newindex} events. | ||
| 2412 | To set the real value of any table index, | ||
| 2413 | without invoking any metamethod, | ||
| 2414 | use the \emph{raw} version: | ||
| 2415 | \begin{verbatim} | ||
| 2416 | void lua_rawset (lua_State *L, int index); | ||
| 2417 | \end{verbatim} | ||
| 2418 | \DefAPI{lua_rawset} | ||
| 2419 | |||
| 2420 | You can traverse a table with the function | ||
| 2421 | \begin{verbatim} | ||
| 2422 | int lua_next (lua_State *L, int index); | ||
| 2423 | \end{verbatim} | ||
| 2424 | \DefAPI{lua_next} | ||
| 2425 | where \verb|index| points to the table to be traversed. | ||
| 2426 | The function pops a key from the stack, | ||
| 2427 | and pushes a key-value pair from the table | ||
| 2428 | (the \Q{next} pair after the given key). | ||
| 2429 | If there are no more elements, then \verb|lua_next| returns 0 | ||
| 2430 | (and pushes nothing). | ||
| 2431 | Use a \nil{} key to signal the start of a traversal. | ||
| 2432 | |||
| 2433 | A typical traversal looks like this: | ||
| 2434 | \begin{verbatim} | ||
| 2435 | /* table is in the stack at index `t' */ | ||
| 2436 | lua_pushnil(L); /* first key */ | ||
| 2437 | while (lua_next(L, t) != 0) { | ||
| 2438 | /* `key' is at index -2 and `value' at index -1 */ | ||
| 2439 | printf("%s - %s\n", | ||
| 2440 | lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); | ||
| 2441 | lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */ | ||
| 2442 | } | ||
| 2443 | \end{verbatim} | ||
| 2444 | |||
| 2445 | NOTE: | ||
| 2446 | While traversing a table, | ||
| 2447 | do not call \verb|lua_tostring| on a key, | ||
| 2448 | unless you know the key is actually a string. | ||
| 2449 | Recall that \verb|lua_tostring| \emph{changes} the value at the given index; | ||
| 2450 | this confuses the next call to \verb|lua_next|. | ||
| 2451 | |||
| 2452 | \subsection{Manipulating Global Variables} \label{globals} | ||
| 2453 | |||
| 2454 | All global variables are kept in an ordinary Lua table. | ||
| 2455 | This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}. | ||
| 2456 | |||
| 2457 | To access and change the value of global variables, | ||
| 2458 | you can use regular table operations over the global table. | ||
| 2459 | For instance, to access the value of a global variable, do | ||
| 2460 | \begin{verbatim} | ||
| 2461 | lua_pushstring(L, varname); | ||
| 2462 | lua_gettable(L, LUA_GLOBALSINDEX); | ||
| 2463 | \end{verbatim} | ||
| 2464 | |||
| 2465 | You can change the global table of a Lua thread using \verb|lua_replace|. | ||
| 2466 | |||
| 2467 | |||
| 2468 | \subsection{Using Tables as Arrays} | ||
| 2469 | The API has functions that help to use Lua tables as arrays, | ||
| 2470 | that is, | ||
| 2471 | tables indexed by numbers only: | ||
| 2472 | \begin{verbatim} | ||
| 2473 | void lua_rawgeti (lua_State *L, int index, int n); | ||
| 2474 | void lua_rawseti (lua_State *L, int index, int n); | ||
| 2475 | \end{verbatim} | ||
| 2476 | \DefAPI{lua_rawgeti} | ||
| 2477 | \DefAPI{lua_rawseti} | ||
| 2478 | |||
| 2479 | \verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table | ||
| 2480 | at stack position \verb|index|. | ||
| 2481 | \verb|lua_rawseti| sets the value of the \M{n}-th element of the table | ||
| 2482 | at stack position \verb|index| to the value at the top of the stack, | ||
| 2483 | removing this value from the stack. | ||
| 2484 | |||
| 2485 | |||
| 2486 | \subsection{Calling Functions} | ||
| 2487 | |||
| 2488 | Functions defined in Lua | ||
| 2489 | and C\Nb{}functions registered in Lua | ||
| 2490 | can be called from the host program. | ||
| 2491 | This is done using the following protocol: | ||
| 2492 | First, the function to be called is pushed onto the stack; | ||
| 2493 | then, the arguments to the function are pushed | ||
| 2494 | in \emph{direct order}, that is, the first argument is pushed first. | ||
| 2495 | Finally, the function is called using | ||
| 2496 | \begin{verbatim} | ||
| 2497 | void lua_call (lua_State *L, int nargs, int nresults); | ||
| 2498 | \end{verbatim} | ||
| 2499 | \DefAPI{lua_call} | ||
| 2500 | \verb|nargs| is the number of arguments that you pushed onto the stack. | ||
| 2501 | All arguments and the function value are popped from the stack, | ||
| 2502 | and the function results are pushed. | ||
| 2503 | The number of results are adjusted to \verb|nresults|, | ||
| 2504 | unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. | ||
| 2505 | In that case, \emph{all} results from the function are pushed. | ||
| 2506 | Lua takes care that the returned values fit into the stack space. | ||
| 2507 | The function results are pushed onto the stack in direct order | ||
| 2508 | (the first result is pushed first), | ||
| 2509 | so that after the call the last result is on the top. | ||
| 2510 | |||
| 2511 | The following example shows how the host program may do the | ||
| 2512 | equivalent to this Lua code: | ||
| 2513 | \begin{verbatim} | ||
| 2514 | a = f("how", t.x, 14) | ||
| 2515 | \end{verbatim} | ||
| 2516 | Here it is in\Nb{}C: | ||
| 2517 | \begin{verbatim} | ||
| 2518 | lua_pushstring(L, "t"); | ||
| 2519 | lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */ | ||
| 2520 | lua_pushstring(L, "a"); /* var name */ | ||
| 2521 | lua_pushstring(L, "f"); /* function name */ | ||
| 2522 | lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */ | ||
| 2523 | lua_pushstring(L, "how"); /* 1st argument */ | ||
| 2524 | lua_pushstring(L, "x"); /* push the string "x" */ | ||
| 2525 | lua_gettable(L, -5); /* push result of t.x (2nd arg) */ | ||
| 2526 | lua_pushnumber(L, 14); /* 3rd argument */ | ||
| 2527 | lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */ | ||
| 2528 | lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */ | ||
| 2529 | lua_pop(L, 1); /* remove `t' from the stack */ | ||
| 2530 | \end{verbatim} | ||
| 2531 | Notice that the code above is \Q{balanced}: | ||
| 2532 | at its end, the stack is back to its original configuration. | ||
| 2533 | This is considered good programming practice. | ||
| 2534 | |||
| 2535 | (We did this example using only the raw functions provided by Lua's API, | ||
| 2536 | to show all the details. | ||
| 2537 | Usually programmers use several macros and auxiliary functions that | ||
| 2538 | provide higher level access to Lua.) | ||
| 2539 | |||
| 2540 | |||
| 2541 | \subsection{Protected Calls}\label{pcall} | ||
| 2542 | |||
| 2543 | When you call a function with \verb|lua_call|, | ||
| 2544 | any error inside the called function is propagated upwards | ||
| 2545 | (with a \verb|longjmp|). | ||
| 2546 | If you need to handle errors, | ||
| 2547 | then you should use \verb|lua_pcall|: | ||
| 2548 | \begin{verbatim} | ||
| 2549 | int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); | ||
| 2550 | \end{verbatim} | ||
| 2551 | Both \verb|nargs| and \verb|nresults| have the same meaning as | ||
| 2552 | in \verb|lua_call|. | ||
| 2553 | If there are no errors during the call, | ||
| 2554 | \verb|lua_pcall| behaves exactly like \verb|lua_call|. | ||
| 2555 | Like \verb|lua_call|, | ||
| 2556 | \verb|lua_pcall| always removes the function | ||
| 2557 | and its arguments from the stack. | ||
| 2558 | However, if there is any error, | ||
| 2559 | \verb|lua_pcall| catches it, | ||
| 2560 | pushes a single value at the stack (the error message), | ||
| 2561 | and returns an error code. | ||
| 2562 | |||
| 2563 | If \verb|errfunc| is 0, | ||
| 2564 | then the error message returned is exactly the original error message. | ||
| 2565 | Otherwise, \verb|errfunc| gives the stack index for an | ||
| 2566 | \emph{error handler function}. | ||
| 2567 | (In the current implementation, that index cannot be a pseudo-index.) | ||
| 2568 | In case of runtime errors, | ||
| 2569 | that function will be called with the error message, | ||
| 2570 | and its return value will be the message returned by \verb|lua_pcall|. | ||
| 2571 | |||
| 2572 | Typically, the error handler function is used to add more debug | ||
| 2573 | information to the error message, such as a stack traceback. | ||
| 2574 | Such information cannot be gathered after the return of \verb|lua_pcall|, | ||
| 2575 | since by then the stack has unwound. | ||
| 2576 | |||
| 2577 | The \verb|lua_pcall| function returns 0 in case of success, | ||
| 2578 | or one of the following error codes | ||
| 2579 | (defined in \verb|lua.h|): | ||
| 2580 | \begin{itemize} | ||
| 2581 | \item \IndexAPI{LUA_ERRRUN} \Em{} a runtime error. | ||
| 2582 | \item \IndexAPI{LUA_ERRMEM} \Em{} memory allocation error. | ||
| 2583 | For such errors, Lua does not call the error handler function. | ||
| 2584 | \item \IndexAPI{LUA_ERRERR} \Em{} | ||
| 2585 | error while running the error handler function. | ||
| 2586 | \end{itemize} | ||
| 2587 | |||
| 2588 | |||
| 2589 | \medskip | ||
| 2590 | |||
| 2591 | >>>> | ||
| 2592 | \C{ TODO: mover essas 2 para algum lugar melhor.} | ||
| 2593 | Some special Lua functions have their own C\Nb{}interfaces. | ||
| 2594 | The host program can generate a Lua error calling the function | ||
| 2595 | \begin{verbatim} | ||
| 2596 | void lua_error (lua_State *L); | ||
| 2597 | \end{verbatim} | ||
| 2598 | \DefAPI{lua_error} | ||
| 2599 | The error message (which actually can be any type of object) | ||
| 2600 | is popped from the stack. | ||
| 2601 | This function never returns. | ||
| 2602 | If \verb|lua_error| is called from a C\Nb{}function that | ||
| 2603 | has been called from Lua, | ||
| 2604 | then the corresponding Lua execution terminates, | ||
| 2605 | as if an error had occurred inside Lua code. | ||
| 2606 | Otherwise, the whole host program terminates with a call to | ||
| 2607 | \verb|exit(EXIT_FAILURE)|. | ||
| 2608 | \C{ TODO: at_panic} | ||
| 2609 | |||
| 2610 | The function | ||
| 2611 | \begin{verbatim} | ||
| 2612 | void lua_concat (lua_State *L, int n); | ||
| 2613 | \end{verbatim} | ||
| 2614 | \DefAPI{lua_concat} | ||
| 2615 | concatenates the \verb|n| values at the top of the stack, | ||
| 2616 | pops them, and leaves the result at the top. | ||
| 2617 | If \verb|n| is 1, the result is that single string | ||
| 2618 | (that is, the function does nothing); | ||
| 2619 | if \verb|n| is 0, the result is the empty string. | ||
| 2620 | Concatenation is done following the usual semantics of Lua | ||
| 2621 | \see{concat}. | ||
| 2622 | |||
| 2623 | |||
| 2624 | \subsection{Defining C Functions} \label{LuacallC} | ||
| 2625 | |||
| 2626 | Lua can be extended with functions written in\Nb{}C. | ||
| 2627 | These functions must be of type \verb|lua_CFunction|, | ||
| 2628 | which is defined as | ||
| 2629 | \begin{verbatim} | ||
| 2630 | typedef int (*lua_CFunction) (lua_State *L); | ||
| 2631 | \end{verbatim} | ||
| 2632 | \DefAPI{lua_CFunction} | ||
| 2633 | A C\Nb{}function receives a Lua environment and returns an integer, | ||
| 2634 | the number of values it has returned to Lua. | ||
| 2635 | |||
| 2636 | In order to communicate properly with Lua, | ||
| 2637 | a C\Nb{}function must follow the following protocol, | ||
| 2638 | which defines the way parameters and results are passed: | ||
| 2639 | A C\Nb{}function receives its arguments from Lua in its stack, | ||
| 2640 | in direct order (the first argument is pushed first). | ||
| 2641 | So, when the function starts, | ||
| 2642 | its first argument (if any) is at index 1. | ||
| 2643 | To return values to Lua, a C\Nb{}function just pushes them onto the stack, | ||
| 2644 | in direct order (the first result is pushed first), | ||
| 2645 | and returns the number of results. | ||
| 2646 | Any other value in the stack below the results will be properly | ||
| 2647 | discharged by Lua. | ||
| 2648 | Like a Lua function, a C\Nb{}function called by Lua can also return | ||
| 2649 | many results. | ||
| 2650 | |||
| 2651 | As an example, the following function receives a variable number | ||
| 2652 | of numerical arguments and returns their average and sum: | ||
| 2653 | \begin{verbatim} | ||
| 2654 | static int foo (lua_State *L) { | ||
| 2655 | int n = lua_gettop(L); /* number of arguments */ | ||
| 2656 | lua_Number sum = 0; | ||
| 2657 | int i; | ||
| 2658 | for (i = 1; i <= n; i++) { | ||
| 2659 | if (!lua_isnumber(L, i)) { | ||
| 2660 | lua_pushstring(L, "incorrect argument to function `average'"); | ||
| 2661 | lua_error(L); | ||
| 2662 | } | ||
| 2663 | sum += lua_tonumber(L, i); | ||
| 2664 | } | ||
| 2665 | lua_pushnumber(L, sum/n); /* first result */ | ||
| 2666 | lua_pushnumber(L, sum); /* second result */ | ||
| 2667 | return 2; /* number of results */ | ||
| 2668 | } | ||
| 2669 | \end{verbatim} | ||
| 2670 | |||
| 2671 | To register a C\Nb{}function to Lua, | ||
| 2672 | there is the following convenience macro: | ||
| 2673 | \begin{verbatim} | ||
| 2674 | #define lua_register(L,n,f) \ | ||
| 2675 | (lua_pushstring(L, n), \ | ||
| 2676 | lua_pushcfunction(L, f), \ | ||
| 2677 | lua_settable(L, LUA_GLOBALSINDEX)) | ||
| 2678 | /* const char *n; */ | ||
| 2679 | /* lua_CFunction f; */ | ||
| 2680 | \end{verbatim} | ||
| 2681 | \DefAPI{lua_register} | ||
| 2682 | which receives the name the function will have in Lua, | ||
| 2683 | and a pointer to the function. | ||
| 2684 | Thus, | ||
| 2685 | the C\Nb{}function `\verb|foo|' above may be registered in Lua as `\verb|average|' | ||
| 2686 | by calling | ||
| 2687 | \begin{verbatim} | ||
| 2688 | lua_register(L, "average", foo); | ||
| 2689 | \end{verbatim} | ||
| 2690 | |||
| 2691 | \subsection{Defining C Closures} \label{c-closure} | ||
| 2692 | |||
| 2693 | When a C\Nb{}function is created, | ||
| 2694 | it is possible to associate some values with it, | ||
| 2695 | thus creating a \IndexEmph{C\Nb{}closure}; | ||
| 2696 | these values are then accessible to the function whenever it is called. | ||
| 2697 | To associate values with a C\Nb{}function, | ||
| 2698 | first these values should be pushed onto the stack | ||
| 2699 | (when there are multiple values, the first value is pushed first). | ||
| 2700 | Then the function | ||
| 2701 | \begin{verbatim} | ||
| 2702 | void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); | ||
| 2703 | \end{verbatim} | ||
| 2704 | \DefAPI{lua_pushcclosure} | ||
| 2705 | is used to push the C\Nb{}function onto the stack, | ||
| 2706 | with the argument \verb|n| telling how many values should be | ||
| 2707 | associated with the function | ||
| 2708 | (\verb|lua_pushcclosure| also pops these values from the stack); | ||
| 2709 | in fact, the macro \verb|lua_pushcfunction| is defined as | ||
| 2710 | \verb|lua_pushcclosure| with \verb|n| set to 0. | ||
| 2711 | |||
| 2712 | Then, whenever the C\Nb{}function is called, | ||
| 2713 | those values are located at specific pseudo-indices. | ||
| 2714 | Those pseudo-indices are produced by a macro \IndexAPI{lua_upvalueindex}. | ||
| 2715 | The first value associated with a function is at position | ||
| 2716 | \verb|lua_upvalueindex(1)|, and so on. | ||
| 2717 | |||
| 2718 | For examples of C\Nb{}functions and closures, see files | ||
| 2719 | \verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| | ||
| 2720 | in the official Lua distribution. | ||
| 2721 | |||
| 2722 | |||
| 2723 | \subsubsection*{Registry} \label{registry} | ||
| 2724 | |||
| 2725 | Lua provides a pre-defined table that can be used by any C\Nb{}code to | ||
| 2726 | store whatever Lua value it needs to store, | ||
| 2727 | especially if the C\Nb{}code needs to keep that Lua value | ||
| 2728 | outside the life span of a C\Nb{}function. | ||
| 2729 | This table is always located at pseudo-index | ||
| 2730 | \IndexAPI{LUA_REGISTRYINDEX}. | ||
| 2731 | Any C\Nb{}library can store data into this table, | ||
| 2732 | as long as it chooses keys different from other libraries. | ||
| 2733 | Typically, you should use as key a string containing your library name, | ||
| 2734 | or a light userdata with the address of a C object in your code. | ||
| 2735 | |||
| 2736 | The integer keys in the registry are used by the reference mechanism, | ||
| 2737 | implemented by the auxiliary library, | ||
| 2738 | and therefore should not be used by other purposes. | ||
| 2739 | |||
| 2740 | |||
| 2741 | \C{-------------------------------------------------------------------------} | ||
| 2742 | \section{The Debug Interface} \label{debugI} | ||
| 2743 | |||
| 2744 | Lua has no built-in debugging facilities. | ||
| 2745 | Instead, it offers a special interface | ||
| 2746 | by means of functions and \emph{hooks}. | ||
| 2747 | This interface allows the construction of different | ||
| 2748 | kinds of debuggers, profilers, and other tools | ||
| 2749 | that need \Q{inside information} from the interpreter. | ||
| 2750 | |||
| 2751 | \subsection{Stack and Function Information} | ||
| 2752 | |||
| 2753 | The main function to get information about the interpreter stack is | ||
| 2754 | \begin{verbatim} | ||
| 2755 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); | ||
| 2756 | \end{verbatim} | ||
| 2757 | \DefAPI{lua_getstack} | ||
| 2758 | This function fills parts of a \verb|lua_Debug| structure with | ||
| 2759 | an identification of the \emph{activation record} | ||
| 2760 | of the function executing at a given level. | ||
| 2761 | Level\Nb{}0 is the current running function, | ||
| 2762 | whereas level \Math{n+1} is the function that has called level \Math{n}. | ||
| 2763 | Usually, \verb|lua_getstack| returns 1; | ||
| 2764 | when called with a level greater than the stack depth, | ||
| 2765 | it returns 0. | ||
| 2766 | |||
| 2767 | The structure \verb|lua_Debug| is used to carry different pieces of | ||
| 2768 | information about an active function: | ||
| 2769 | \begin{verbatim} | ||
| 2770 | typedef struct lua_Debug { | ||
| 2771 | int event; | ||
| 2772 | const char *name; /* (n) */ | ||
| 2773 | const char *namewhat; /* (n) `global', `local', `field', `method' */ | ||
| 2774 | const char *what; /* (S) `Lua' function, `C' function, Lua `main' */ | ||
| 2775 | const char *source; /* (S) */ | ||
| 2776 | int currentline; /* (l) */ | ||
| 2777 | int nups; /* (u) number of upvalues */ | ||
| 2778 | int linedefined; /* (S) */ | ||
| 2779 | char short_src[LUA_IDSIZE]; /* (S) */ | ||
| 2780 | |||
| 2781 | /* private part */ | ||
| 2782 | ... | ||
| 2783 | } lua_Debug; | ||
| 2784 | \end{verbatim} | ||
| 2785 | \DefAPI{lua_Debug} | ||
| 2786 | \verb|lua_getstack| fills only the private part | ||
| 2787 | of this structure, for future use. | ||
| 2788 | To fill the other fields of \verb|lua_Debug| with useful information, | ||
| 2789 | call | ||
| 2790 | \begin{verbatim} | ||
| 2791 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); | ||
| 2792 | \end{verbatim} | ||
| 2793 | \DefAPI{lua_getinfo} | ||
| 2794 | This function returns 0 on error | ||
| 2795 | (for instance, an invalid option in \verb|what|). | ||
| 2796 | Each character in the string \verb|what| | ||
| 2797 | selects some fields of \verb|ar| to be filled, | ||
| 2798 | as indicated by the letter in parentheses in the definition of \verb|lua_Debug| | ||
| 2799 | above: | ||
| 2800 | `\verb|S|' fills in the fields \verb|source|, \verb|linedefined|, | ||
| 2801 | and \verb|what|; | ||
| 2802 | `\verb|l|' fills in the field \verb|currentline|, etc. | ||
| 2803 | Moreover, `\verb|f|' pushes onto the stack the function that is | ||
| 2804 | running at the given level. | ||
| 2805 | |||
| 2806 | To get information about a function that is not active (that is, | ||
| 2807 | it is not in the stack), | ||
| 2808 | you push the function onto the stack, | ||
| 2809 | and start the \verb|what| string with the character `\verb|>|'. | ||
| 2810 | For instance, to know in which line a function \verb|f| was defined, | ||
| 2811 | you can write | ||
| 2812 | \begin{verbatim} | ||
| 2813 | lua_Debug ar; | ||
| 2814 | lua_pushstring(L, "f"); | ||
| 2815 | lua_gettable(L, LUA_GLOBALSINDEX); /* get global `f' */ | ||
| 2816 | lua_getinfo(L, ">S", &ar); | ||
| 2817 | printf("%d\n", ar.linedefined); | ||
| 2818 | \end{verbatim} | ||
| 2819 | The fields of \verb|lua_Debug| have the following meaning: | ||
| 2820 | \begin{description}\leftskip=20pt | ||
| 2821 | |||
| 2822 | \item[source] | ||
| 2823 | If the function was defined in a string, | ||
| 2824 | then \verb|source| is that string; | ||
| 2825 | if the function was defined in a file, | ||
| 2826 | then \verb|source| starts with a \At{} followed by the file name. | ||
| 2827 | |||
| 2828 | \item[short_src] | ||
| 2829 | A \Q{printable} version of \verb|source|, to be used in error messages. | ||
| 2830 | |||
| 2831 | \item[linedefined] | ||
| 2832 | the line number where the definition of the function starts. | ||
| 2833 | |||
| 2834 | \item[what] the string \verb|"Lua"| if this is a Lua function, | ||
| 2835 | \verb|"C"| if this is a C\Nb{}function, | ||
| 2836 | or \verb|"main"| if this is the main part of a chunk. | ||
| 2837 | |||
| 2838 | \item[currentline] | ||
| 2839 | the current line where the given function is executing. | ||
| 2840 | When no line information is available, | ||
| 2841 | \verb|currentline| is set to \Math{-1}. | ||
| 2842 | |||
| 2843 | \item[name] | ||
| 2844 | a reasonable name for the given function. | ||
| 2845 | Because functions in Lua are first class values, | ||
| 2846 | they do not have a fixed name: | ||
| 2847 | Some functions may be the value of many global variables, | ||
| 2848 | while others may be stored only in a table field. | ||
| 2849 | The \verb|lua_getinfo| function checks how the function was | ||
| 2850 | called or whether it is the value of a global variable to | ||
| 2851 | find a suitable name. | ||
| 2852 | If it cannot find a name, | ||
| 2853 | then \verb|name| is set to \verb|NULL|. | ||
| 2854 | |||
| 2855 | \item[namewhat] | ||
| 2856 | Explains the previous field. | ||
| 2857 | It can be \verb|"global"|, \verb|"local"|, \verb|"method"|, | ||
| 2858 | \verb|"field"|, or \verb|""| (the empty string), | ||
| 2859 | according to how the function was called. | ||
| 2860 | (Lua uses the empty string when no other option seems to apply.) | ||
| 2861 | |||
| 2862 | \item[nups] | ||
| 2863 | Number of upvalues of the function. | ||
| 2864 | |||
| 2865 | \end{description} | ||
| 2866 | |||
| 2867 | |||
| 2868 | \subsection{Manipulating Local Variables} | ||
| 2869 | |||
| 2870 | For the manipulation of local variables, | ||
| 2871 | \verb|luadebug.h| uses indices: | ||
| 2872 | The first parameter or local variable has index\Nb{}1, and so on, | ||
| 2873 | until the last active local variable. | ||
| 2874 | |||
| 2875 | The following functions allow the manipulation of the | ||
| 2876 | local variables of a given activation record: | ||
| 2877 | \begin{verbatim} | ||
| 2878 | const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); | ||
| 2879 | const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); | ||
| 2880 | \end{verbatim} | ||
| 2881 | \DefAPI{lua_getlocal}\DefAPI{lua_setlocal} | ||
| 2882 | The parameter \verb|ar| must be a valid activation record that was | ||
| 2883 | filled by a previous call to \verb|lua_getstack| or | ||
| 2884 | was given as argument to a hook \see{sub-hooks}. | ||
| 2885 | \verb|lua_getlocal| gets the index \verb|n| of a local variable, | ||
| 2886 | pushes the variable's value onto the stack, | ||
| 2887 | and returns its name. | ||
| 2888 | \verb|lua_setlocal| assigns the value at the top of the stack | ||
| 2889 | to the variable and returns its name. | ||
| 2890 | Both functions return \verb|NULL| | ||
| 2891 | when the index is greater than | ||
| 2892 | the number of active local variables. | ||
| 2893 | |||
| 2894 | As an example, the following function lists the names of all | ||
| 2895 | local variables for a function at a given level of the stack: | ||
| 2896 | \begin{verbatim} | ||
| 2897 | int listvars (lua_State *L, int level) { | ||
| 2898 | lua_Debug ar; | ||
| 2899 | int i = 1; | ||
| 2900 | const char *name; | ||
| 2901 | if (lua_getstack(L, level, &ar) == 0) | ||
| 2902 | return 0; /* failure: no such level in the stack */ | ||
| 2903 | while ((name = lua_getlocal(L, &ar, i++)) != NULL) { | ||
| 2904 | printf("%s\n", name); | ||
| 2905 | lua_pop(L, 1); /* remove variable value */ | ||
| 2906 | } | ||
| 2907 | return 1; | ||
| 2908 | } | ||
| 2909 | \end{verbatim} | ||
| 2910 | |||
| 2911 | |||
| 2912 | \subsection{Hooks}\label{sub-hooks} | ||
| 2913 | |||
| 2914 | The Lua interpreter offers a mechanism of hooks, which are | ||
| 2915 | user-defined C functions that are called during the program execution. | ||
| 2916 | A hook may be called in four different events: | ||
| 2917 | a \emph{call} event, when Lua calls a function; | ||
| 2918 | a \emph{return} event, when Lua returns from a function; | ||
| 2919 | a \emph{line} event, when Lua starts executing a new line of code; | ||
| 2920 | and a \emph{count} event, which happens every \Q{count} instructions. | ||
| 2921 | Lua identifies them with the following constants: | ||
| 2922 | \verb|LUA_HOOKCALL|\DefAPI{LUA_HOOKCALL}, | ||
| 2923 | \verb|LUA_HOOKRET|\DefAPI{LUA_HOOKRET}, | ||
| 2924 | \verb|LUA_HOOKLINE|\DefAPI{LUA_HOOKLINE}, | ||
| 2925 | and \verb|LUA_HOOKCOUNT|\DefAPI{LUA_HOOKCOUNT}. | ||
| 2926 | |||
| 2927 | A hook has type \verb|lua_Hook|, defined as follows: | ||
| 2928 | \begin{verbatim} | ||
| 2929 | typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); | ||
| 2930 | \end{verbatim} | ||
| 2931 | \DefAPI{lua_Hook} | ||
| 2932 | You can set the hook with the following function: | ||
| 2933 | \begin{verbatim} | ||
| 2934 | int lua_sethook (lua_State *L, lua_Hook func, unsigned long mask); | ||
| 2935 | \end{verbatim} | ||
| 2936 | \DefAPI{lua_sethook} | ||
| 2937 | \verb|func| is the hook, | ||
| 2938 | and \verb|mask| specifies at which events it will be called. | ||
| 2939 | It is formed by a disjunction of the constants | ||
| 2940 | \verb|LUA_MASKCALL|, | ||
| 2941 | \verb|LUA_MASKRET|, | ||
| 2942 | \verb|LUA_MASKLINE|, | ||
| 2943 | plus the macro \verb|LUA_MASKCOUNT(count)|. | ||
| 2944 | For each event, the hook is called as explained below: | ||
| 2945 | \begin{description} | ||
| 2946 | \item{The call hook} is called when the interpreter calls a function. | ||
| 2947 | The hook is called just after Lua \Q{enters} the new function. | ||
| 2948 | \item{The return hook} is called when the interpreter returns from a function. | ||
| 2949 | The hook is called just before Lua \Q{leaves} the function. | ||
| 2950 | \item{The line hook} is called when the interpreter is about to | ||
| 2951 | start the execution of a new line of code, | ||
| 2952 | or when it jumps back (even for the same line). | ||
| 2953 | (For obvious reasons, this event does not happen while Lua is executing | ||
| 2954 | a C function.) | ||
| 2955 | \item{The count hook} is called after the interpreter executes every | ||
| 2956 | \verb|count| instructions. | ||
| 2957 | (For obvious reasons, this event does not happen while Lua is executing | ||
| 2958 | a C function.) | ||
| 2959 | \end{description} | ||
| 2960 | |||
| 2961 | A hook is disabled with the mask zero. | ||
| 2962 | |||
| 2963 | You can get the current hook and the current mask with the next functions: | ||
| 2964 | \begin{verbatim} | ||
| 2965 | lua_Hook lua_gethook (lua_State *L); | ||
| 2966 | unsigned long lua_gethookmask (lua_State *L); | ||
| 2967 | \end{verbatim} | ||
| 2968 | \DefAPI{lua_gethook}\DefAPI{lua_gethookmask} | ||
| 2969 | You can get the count inside a mask with the macro \verb|lua_getmaskcount|. | ||
| 2970 | |||
| 2971 | Whenever a hook is called, its \verb|ar| argument has its field | ||
| 2972 | \verb|event| set to the specific event that triggered the hook. | ||
| 2973 | Moreover, for line events, the field \verb|currentline| is also set. | ||
| 2974 | For the value of any other field, the hook must call \verb|lua_getinfo|. | ||
| 2975 | |||
| 2976 | While Lua is running a hook, it disables other calls to hooks. | ||
| 2977 | Therefore, if a hook calls Lua to execute a function or a chunk, | ||
| 2978 | that execution occurs without any calls to hooks. | ||
| 2979 | |||
| 2980 | |||
| 2981 | \C{-------------------------------------------------------------------------} | ||
| 2982 | \section{Standard Libraries}\label{libraries} | ||
| 2983 | |||
| 2984 | The standard libraries provide useful functions | ||
| 2985 | that are implemented directly through the standard C\Nb{}API. | ||
| 2986 | Some of these functions provide essential services to the language | ||
| 2987 | (e.g. \verb|type| and \verb|getmetatable|); | ||
| 2988 | others provide access to \Q{outside} services (e.g. I/O); | ||
| 2989 | and others could be implemented in Lua itself, | ||
| 2990 | but are quite useful or have critical performance to | ||
| 2991 | deserve an implementation in C (e.g. \verb|sort|). | ||
| 2992 | |||
| 2993 | All libraries are implemented through the official C API, | ||
| 2994 | and are provided as separate C\Nb{}modules. | ||
| 2995 | Currently, Lua has the following standard libraries: | ||
| 2996 | \begin{itemize} | ||
| 2997 | \item basic library; | ||
| 2998 | \item string manipulation; | ||
| 2999 | \item table manipulation; | ||
| 3000 | \item mathematical functions (sin, log, etc.); | ||
| 3001 | \item input and output; | ||
| 3002 | \item operating system facilities; | ||
| 3003 | \item debug facilities. | ||
| 3004 | \end{itemize} | ||
| 3005 | Except for the basic library, | ||
| 3006 | each library provides all its functions as fields of a global table | ||
| 3007 | or as methods of its objects. | ||
| 3008 | |||
| 3009 | To have access to these libraries, | ||
| 3010 | the C\Nb{}host program must call the functions | ||
| 3011 | \verb|lua_baselibopen| (for the basic library), | ||
| 3012 | \verb|lua_strlibopen| (for the string library), | ||
| 3013 | \verb|lua_tablibopen| (for the table library), | ||
| 3014 | \verb|lua_mathlibopen| (for the mathematical library), | ||
| 3015 | \verb|lua_iolibopen| (for the I/O and the Operating System libraries), | ||
| 3016 | and \verb|lua_dblibopen| (for the debug library), | ||
| 3017 | which are declared in \verb|lualib.h|. | ||
| 3018 | \DefAPI{lua_baselibopen} | ||
| 3019 | \DefAPI{lua_strlibopen} | ||
| 3020 | \DefAPI{lua_tablibopen} | ||
| 3021 | \DefAPI{lua_mathlibopen} | ||
| 3022 | \DefAPI{lua_iolibopen} | ||
| 3023 | \DefAPI{lua_dblibopen} | ||
| 3024 | |||
| 3025 | |||
| 3026 | \subsection{Basic Functions} \label{predefined} | ||
| 3027 | |||
| 3028 | The basic library provides some core functions to Lua. | ||
| 3029 | If you do not include this library in your application, | ||
| 3030 | you should check carefully whether you need to provide some alternative | ||
| 3031 | implementation for some facilities. | ||
| 3032 | |||
| 3033 | The basic library also defines a global variable \IndexLIB{_VERSION} | ||
| 3034 | with a string containing the current interpreter version. | ||
| 3035 | The current content of this string is {\tt "Lua \Version"}. | ||
| 3036 | |||
| 3037 | \subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert} | ||
| 3038 | Issues an \emph{\Q{assertion failed!}} error | ||
| 3039 | when its argument \verb|v| is \nil{} or \False{}; | ||
| 3040 | otherwise, returns this argument. | ||
| 3041 | This function is equivalent to the following Lua function: | ||
| 3042 | \begin{verbatim} | ||
| 3043 | function assert (v, m) | ||
| 3044 | if not v then | ||
| 3045 | error(m or "assertion failed!") | ||
| 3046 | end | ||
| 3047 | return v | ||
| 3048 | end | ||
| 3049 | \end{verbatim} | ||
| 3050 | |||
| 3051 | \subsubsection*{\ff \T{collectgarbage ([limit])}}\DefLIB{collectgarbage} | ||
| 3052 | |||
| 3053 | Sets the garbage-collection threshold to the given limit | ||
| 3054 | (in Kbytes), and checks it against the byte counter. | ||
| 3055 | If the new threshold is smaller than the byte counter, | ||
| 3056 | then Lua immediately runs the garbage collector \see{GC}. | ||
| 3057 | If \verb|limit| is absent, it defaults to zero | ||
| 3058 | (thus forcing a garbage-collection cycle). | ||
| 3059 | |||
| 3060 | \subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile} | ||
| 3061 | Receives a file name, | ||
| 3062 | opens the named file, and executes its contents as a Lua chunk. | ||
| 3063 | When called without arguments, | ||
| 3064 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). | ||
| 3065 | Returns any value returned by the chunk. | ||
| 3066 | |||
| 3067 | \subsubsection*{\ff \T{error (message [, level])}} | ||
| 3068 | \DefLIB{error}\label{pdf-error} | ||
| 3069 | Terminates the last protected function called, | ||
| 3070 | and returns \verb|message| as the error message. | ||
| 3071 | Function \verb|error| never returns. | ||
| 3072 | |||
| 3073 | The \verb|level| argument specifies where the error | ||
| 3074 | message points the error. | ||
| 3075 | With level 1 (the default), the error position is where the | ||
| 3076 | \verb|error| function was called. | ||
| 3077 | Level 2 points the error to where the function | ||
| 3078 | that called \verb|error| was called; and so on. | ||
| 3079 | |||
| 3080 | \subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals} | ||
| 3081 | Returns the current table of globals in use by the function. | ||
| 3082 | \verb|function| can be a Lua function or a number, | ||
| 3083 | which specifies the function at that stack level: | ||
| 3084 | Level 1 is the function calling \verb|getglobals|. | ||
| 3085 | If the given function is not a Lua function, | ||
| 3086 | returns the \Q{global} table of globals. | ||
| 3087 | The default for \verb|function| is 1. | ||
| 3088 | |||
| 3089 | \subsubsection*{\ff \T{getmetatable (object)}} | ||
| 3090 | \DefLIB{getmetatable}\label{pdf-getmetatable} | ||
| 3091 | |||
| 3092 | Returns the metatable of the given object. | ||
| 3093 | If the object does not have a metatable, returns \nil{}. | ||
| 3094 | |||
| 3095 | \subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo} | ||
| 3096 | Returns the number of Kbytes of dynamic memory Lua is using, | ||
| 3097 | and (as a second result) the | ||
| 3098 | current garbage collector threshold (also in Kbytes). | ||
| 3099 | |||
| 3100 | \subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs} | ||
| 3101 | |||
| 3102 | Returns a generator function and the table \verb|t|, | ||
| 3103 | so that the construction | ||
| 3104 | \begin{verbatim} | ||
| 3105 | for i,v in ipairs(t) do ... end | ||
| 3106 | \end{verbatim} | ||
| 3107 | will iterate over the pairs \verb|1, t[1]|, \verb|2, t[2]|, \ldots, | ||
| 3108 | up to the first nil value of the table. | ||
| 3109 | |||
| 3110 | \subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile} | ||
| 3111 | Loads a file as a Lua chunk. | ||
| 3112 | If there are no errors, | ||
| 3113 | returns the compiled chunk as a function; | ||
| 3114 | otherwise, returns \nil{} plus an error message. | ||
| 3115 | |||
| 3116 | \subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring} | ||
| 3117 | Loads a string as a Lua chunk. | ||
| 3118 | If there are no errors, | ||
| 3119 | returns the compiled chunk as a function; | ||
| 3120 | otherwise, returns \nil{} plus an error message. | ||
| 3121 | |||
| 3122 | The optional parameter \verb|chunkname| | ||
| 3123 | is the \Q{name of the chunk}, | ||
| 3124 | which is used in error messages and debug information. | ||
| 3125 | |||
| 3126 | To load and run a given string, use the idiom | ||
| 3127 | \begin{verbatim} | ||
| 3128 | assert(loadstring(s))() | ||
| 3129 | \end{verbatim} | ||
| 3130 | |||
| 3131 | \subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} | ||
| 3132 | Allows a program to traverse all fields of a table. | ||
| 3133 | Its first argument is a table and its second argument | ||
| 3134 | is an index in this table. | ||
| 3135 | \verb|next| returns the next index of the table and the | ||
| 3136 | value associated with the index. | ||
| 3137 | When called with \nil{} as its second argument, | ||
| 3138 | \verb|next| returns the first index | ||
| 3139 | of the table and its associated value. | ||
| 3140 | When called with the last index, | ||
| 3141 | or with \nil{} in an empty table, | ||
| 3142 | \verb|next| returns \nil{}. | ||
| 3143 | If the second argument is absent, then it is interpreted as \nil{}. | ||
| 3144 | |||
| 3145 | Lua has no declaration of fields; | ||
| 3146 | semantically, there is no difference between a | ||
| 3147 | field not present in a table or a field with value \nil{}. | ||
| 3148 | Therefore, \verb|next| only considers fields with non-\nil{} values. | ||
| 3149 | The order in which the indices are enumerated is not specified, | ||
| 3150 | \emph{even for numeric indices}. | ||
| 3151 | (To traverse a table in numeric order, | ||
| 3152 | use a numerical \rwd{for} or the function \verb|ipairs|.) | ||
| 3153 | |||
| 3154 | The behavior of \verb|next| is \emph{undefined} if you modify | ||
| 3155 | the table during the traversal. | ||
| 3156 | |||
| 3157 | \subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs} | ||
| 3158 | |||
| 3159 | Returns the function \verb|next| and the table \verb|t| (plus a \nil{}), | ||
| 3160 | so that the construction | ||
| 3161 | \begin{verbatim} | ||
| 3162 | for k,v in pairs(t) do ... end | ||
| 3163 | \end{verbatim} | ||
| 3164 | will iterate over all pairs of key\En{}value of table \verb|t|. | ||
| 3165 | |||
| 3166 | \subsubsection*{\ff \T{pcall (func, arg1, arg2, ...)}}\DefLIB{pcall} | ||
| 3167 | \label{pdf-pcall} | ||
| 3168 | Calls function \verb|func| with | ||
| 3169 | the given arguments in protected mode. | ||
| 3170 | That means that any error inside \verb|func| is not propagated; | ||
| 3171 | instead, \verb|pcall| catches the error | ||
| 3172 | and returns a status code. | ||
| 3173 | Its first result is the status code (a boolean), | ||
| 3174 | which is true if the call succeeds without errors. | ||
| 3175 | In such case, \verb|pcall| also returns all results from the call, | ||
| 3176 | after this first result. | ||
| 3177 | In case of any error, \verb|pcall| returns false plus the error message. | ||
| 3178 | |||
| 3179 | \subsubsection*{\ff \T{print (e1, e2, ...)}}\DefLIB{print} | ||
| 3180 | Receives any number of arguments, | ||
| 3181 | and prints their values in \verb|stdout|, | ||
| 3182 | using the strings returned by \verb|tostring|. | ||
| 3183 | This function is not intended for formatted output, | ||
| 3184 | but only as a quick way to show a value, | ||
| 3185 | typically for debugging. | ||
| 3186 | For formatted output, see \verb|format| \see{format}. | ||
| 3187 | |||
| 3188 | \subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget} | ||
| 3189 | Gets the real value of \verb|table[index]|, | ||
| 3190 | without invoking any metamethod. | ||
| 3191 | \verb|table| must be a table; | ||
| 3192 | \verb|index| is any value different from \nil{}. | ||
| 3193 | |||
| 3194 | \subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset} | ||
| 3195 | Sets the real value of \verb|table[index]| to \verb|value|, | ||
| 3196 | without invoking any metamethod. | ||
| 3197 | \verb|table| must be a table; | ||
| 3198 | \verb|index| is any value different from \nil{}; | ||
| 3199 | and \verb|value| is any Lua value. | ||
| 3200 | |||
| 3201 | \subsubsection*{\ff \T{require (packagename)}}\DefLIB{require} | ||
| 3202 | |||
| 3203 | Loads the given package. | ||
| 3204 | The function starts by looking into the table \IndexVerb{_LOADED} | ||
| 3205 | to determine whether \verb|packagename| is already loaded. | ||
| 3206 | If it is, then \verb|require| is done. | ||
| 3207 | Otherwise, it searches a path looking for a file to load. | ||
| 3208 | |||
| 3209 | If the global variable \IndexVerb{LUA_PATH} is a string, | ||
| 3210 | this string is the path. | ||
| 3211 | Otherwise, \verb|require| tries the environment variable \verb|LUA_PATH|. | ||
| 3212 | As a last resort, it uses a predefined path. | ||
| 3213 | |||
| 3214 | The path is a sequence of \emph{templates} separated by semicolons. | ||
| 3215 | For each template, \verb|require| will change an eventual interrogation | ||
| 3216 | mark in the template to \verb|packagename|, | ||
| 3217 | and then will try to load the resulting file name. | ||
| 3218 | So, for instance, if the path is | ||
| 3219 | \begin{verbatim} | ||
| 3220 | "./?.lua;./?.lc;/usr/local/?/init.lua;/lasttry" | ||
| 3221 | \end{verbatim} | ||
| 3222 | a \verb|require "mod"| will try to load the files | ||
| 3223 | \verb|./mod.lua|, | ||
| 3224 | \verb|./mod.lc|, | ||
| 3225 | \verb|/usr/local/mod/init.lua|, | ||
| 3226 | and \verb|/lasttry|, in that order. | ||
| 3227 | |||
| 3228 | The function stops the search as soon as it can load a file, | ||
| 3229 | and then it runs the file. | ||
| 3230 | If there is any error loading or running the file, | ||
| 3231 | or if it cannot find any file in the path, | ||
| 3232 | then \verb|require| signals an error. | ||
| 3233 | Otherwise, it marks in table \verb|_LOADED| | ||
| 3234 | that the package is loaded, and returns. | ||
| 3235 | |||
| 3236 | While running a packaged file, | ||
| 3237 | \verb|require| defines the global variable \IndexVerb{_REQUIREDNAME} | ||
| 3238 | with the package name. | ||
| 3239 | |||
| 3240 | \subsubsection*{\ff \T{setglobals (function, table)}}\DefLIB{setglobals} | ||
| 3241 | Sets the current table of globals to be used by the given function. | ||
| 3242 | \verb|function| can be a Lua function or a number, | ||
| 3243 | which specifies the function at that stack level: | ||
| 3244 | Level 1 is the function calling \verb|setglobals|. | ||
| 3245 | |||
| 3246 | \subsubsection*{\ff \T{setmetatable (table, metatable)}}\DefLIB{setmetatable} | ||
| 3247 | |||
| 3248 | Sets the metatable for the given table. | ||
| 3249 | (You cannot change the metatable of a userdata from Lua.) | ||
| 3250 | If \verb|metatable| is \nil{}, removes the metatable of the given table. | ||
| 3251 | |||
| 3252 | \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} | ||
| 3253 | Tries to convert its argument to a number. | ||
| 3254 | If the argument is already a number or a string convertible | ||
| 3255 | to a number, then \verb|tonumber| returns that number; | ||
| 3256 | otherwise, it returns \nil{}. | ||
| 3257 | |||
| 3258 | An optional argument specifies the base to interpret the numeral. | ||
| 3259 | The base may be any integer between 2 and 36, inclusive. | ||
| 3260 | In bases above\Nb{}10, the letter `A' (in either upper or lower case) | ||
| 3261 | represents\Nb{}10, `B' represents\Nb{}11, and so forth, with `Z' representing 35. | ||
| 3262 | In base 10 (the default), the number may have a decimal part, | ||
| 3263 | as well as an optional exponent part \see{coercion}. | ||
| 3264 | In other bases, only unsigned integers are accepted. | ||
| 3265 | |||
| 3266 | \subsubsection*{\ff \T{tostring (e)}}\DefLIB{tostring} | ||
| 3267 | Receives an argument of any type and | ||
| 3268 | converts it to a string in a reasonable format. | ||
| 3269 | For complete control of how numbers are converted, | ||
| 3270 | use \verb|format| \see{format}. | ||
| 3271 | |||
| 3272 | \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} | ||
| 3273 | Returns the type of its only argument, coded as a string. | ||
| 3274 | The possible results of this function are | ||
| 3275 | \verb|"nil"| (a string, not the value \nil{}), | ||
| 3276 | \verb|"number"|, | ||
| 3277 | \verb|"string"|, | ||
| 3278 | \verb|"table"|, | ||
| 3279 | \verb|"function"|, | ||
| 3280 | and \verb|"userdata"|. | ||
| 3281 | |||
| 3282 | \subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack} | ||
| 3283 | Returns all elements from the given list. | ||
| 3284 | This function is equivalent to | ||
| 3285 | \begin{verbatim} | ||
| 3286 | return list[1], list[2], ..., list[n] | ||
| 3287 | \end{verbatim} | ||
| 3288 | except that the above code can be valid only for a fixed \M{n}. | ||
| 3289 | The number \M{n} of returned values | ||
| 3290 | is either the value of \verb|list.n|, if it is a number, | ||
| 3291 | or one less the index of the first absent (\nil{}) value. | ||
| 3292 | |||
| 3293 | \subsection{String Manipulation} | ||
| 3294 | This library provides generic functions for string manipulation, | ||
| 3295 | such as finding and extracting substrings and pattern matching. | ||
| 3296 | When indexing a string in Lua, the first character is at position\Nb{}1 | ||
| 3297 | (not at\Nb{}0, as in C). | ||
| 3298 | Indices are allowed to be negative and are interpreted as indexing backwards, | ||
| 3299 | from the end of the string. | ||
| 3300 | Thus, the last character is at position \Math{-1}, and so on. | ||
| 3301 | |||
| 3302 | The string library provides all its functions inside the table | ||
| 3303 | \IndexLIB{string}. | ||
| 3304 | |||
| 3305 | \subsubsection*{\ff \T{string.byte (s [, i])}}\DefLIB{string.byte} | ||
| 3306 | Returns the internal numerical code of the \M{i}-th character of \verb|s|. | ||
| 3307 | If \verb|i| is absent, then it is assumed to be\Nb{}1. | ||
| 3308 | \verb|i| may be negative. | ||
| 3309 | |||
| 3310 | \NOTE | ||
| 3311 | Numerical codes are not necessarily portable across platforms. | ||
| 3312 | |||
| 3313 | \subsubsection*{\ff \T{string.char (i1, i2, \ldots)}}\DefLIB{string.char} | ||
| 3314 | Receives 0 or more integers. | ||
| 3315 | Returns a string with length equal to the number of arguments, | ||
| 3316 | in which each character has the internal numerical code equal | ||
| 3317 | to its correspondent argument. | ||
| 3318 | |||
| 3319 | \NOTE | ||
| 3320 | Numerical codes are not necessarily portable across platforms. | ||
| 3321 | |||
| 3322 | \subsubsection*{\ff \T{string.find (s, pattern [, init [, plain]])}} | ||
| 3323 | \DefLIB{string.find} | ||
| 3324 | Looks for the first \emph{match} of | ||
| 3325 | \verb|pattern| in the string \verb|s|. | ||
| 3326 | If it finds one, then \verb|find| returns the indices of \verb|s| | ||
| 3327 | where this occurrence starts and ends; | ||
| 3328 | otherwise, it returns \nil{}. | ||
| 3329 | If the pattern specifies captures (see \verb|string.gsub| below), | ||
| 3330 | the captured strings are returned as extra results. | ||
| 3331 | A third, optional numerical argument \verb|init| specifies | ||
| 3332 | where to start the search; | ||
| 3333 | its default value is\Nb{}1, and may be negative. | ||
| 3334 | A value of \True{} as a fourth, optional argument \verb|plain| | ||
| 3335 | turns off the pattern matching facilities, | ||
| 3336 | so the function does a plain \Q{find substring} operation, | ||
| 3337 | with no characters in \verb|pattern| being considered \Q{magic}. | ||
| 3338 | Note that if \verb|plain| is given, then \verb|init| must be given too. | ||
| 3339 | |||
| 3340 | \subsubsection*{\ff \T{string.len (s)}}\DefLIB{string.len} | ||
| 3341 | Receives a string and returns its length. | ||
| 3342 | The empty string \verb|""| has length 0. | ||
| 3343 | Embedded zeros are counted, | ||
| 3344 | so \verb|"a\000b\000c"| has length 5. | ||
| 3345 | |||
| 3346 | \subsubsection*{\ff \T{string.lower (s)}}\DefLIB{string.lower} | ||
| 3347 | Receives a string and returns a copy of that string with all | ||
| 3348 | uppercase letters changed to lowercase. | ||
| 3349 | All other characters are left unchanged. | ||
| 3350 | The definition of what is an uppercase letter depends on the current locale. | ||
| 3351 | |||
| 3352 | \subsubsection*{\ff \T{string.rep (s, n)}}\DefLIB{string.rep} | ||
| 3353 | Returns a string that is the concatenation of \verb|n| copies of | ||
| 3354 | the string \verb|s|. | ||
| 3355 | |||
| 3356 | \subsubsection*{\ff \T{string.sub (s, i [, j])}}\DefLIB{string.sub} | ||
| 3357 | Returns another string, which is the substring of \verb|s| that | ||
| 3358 | starts at \verb|i| and continues until \verb|j|; | ||
| 3359 | \verb|i| and \verb|j| may be negative. | ||
| 3360 | If \verb|j| is absent, then it is assumed to be equal to \Math{-1} | ||
| 3361 | (which is the same as the string length). | ||
| 3362 | In particular, | ||
| 3363 | the call \verb|string.sub(s,1,j)| returns a prefix of \verb|s| | ||
| 3364 | with length \verb|j|, | ||
| 3365 | and the call \verb|string.sub(s, -i)| returns a suffix of \verb|s| | ||
| 3366 | with length \verb|i|. | ||
| 3367 | |||
| 3368 | \subsubsection*{\ff \T{string.upper (s)}}\DefLIB{string.upper} | ||
| 3369 | Receives a string and returns a copy of that string with all | ||
| 3370 | lowercase letters changed to uppercase. | ||
| 3371 | All other characters are left unchanged. | ||
| 3372 | The definition of what is a lowercase letter depends on the current locale. | ||
| 3373 | |||
| 3374 | \subsubsection*{\ff \T{string.format (formatstring, e1, e2, \ldots)}} | ||
| 3375 | \DefLIB{string.format}\label{format} | ||
| 3376 | Returns a formatted version of its variable number of arguments | ||
| 3377 | following the description given in its first argument (which must be a string). | ||
| 3378 | The format string follows the same rules as the \verb|printf| family of | ||
| 3379 | standard C\Nb{}functions. | ||
| 3380 | The only differences are that the options/modifiers | ||
| 3381 | \verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|, | ||
| 3382 | and \verb|h| are not supported, | ||
| 3383 | and there is an extra option, \verb|q|. | ||
| 3384 | The \verb|q| option formats a string in a form suitable to be safely read | ||
| 3385 | back by the Lua interpreter: | ||
| 3386 | The string is written between double quotes, | ||
| 3387 | and all double quotes, returns, and backslashes in the string | ||
| 3388 | are correctly escaped when written. | ||
| 3389 | For instance, the call | ||
| 3390 | \begin{verbatim} | ||
| 3391 | string.format('%q', 'a string with "quotes" and \n new line') | ||
| 3392 | \end{verbatim} | ||
| 3393 | will produce the string: | ||
| 3394 | \begin{verbatim} | ||
| 3395 | "a string with \"quotes\" and \ | ||
| 3396 | new line" | ||
| 3397 | \end{verbatim} | ||
| 3398 | |||
| 3399 | The options \verb|c|, \verb|d|, \verb|E|, \verb|e|, \verb|f|, | ||
| 3400 | \verb|g|, \verb|G|, \verb|i|, \verb|o|, \verb|u|, \verb|X|, and \verb|x| all | ||
| 3401 | expect a number as argument, | ||
| 3402 | whereas \verb|q| and \verb|s| expect a string. | ||
| 3403 | The \verb|*| modifier can be simulated by building | ||
| 3404 | the appropriate format string. | ||
| 3405 | For example, \verb|"%*g"| can be simulated with | ||
| 3406 | \verb|"%"..width.."g"|. | ||
| 3407 | |||
| 3408 | \NOTE | ||
| 3409 | String values to be formatted with | ||
| 3410 | \verb|%s| cannot contain embedded zeros. | ||
| 3411 | |||
| 3412 | \subsubsection*{\ff \T{string.gfind (s, pat)}} | ||
| 3413 | |||
| 3414 | Returns a generator function that, | ||
| 3415 | each time it is called, | ||
| 3416 | returns the next captures from pattern \verb|pat| over string \verb|s|. | ||
| 3417 | |||
| 3418 | If \verb|pat| specifies no captures, | ||
| 3419 | then the whole match is produced in each call. | ||
| 3420 | |||
| 3421 | As an example, the following loop | ||
| 3422 | \begin{verbatim} | ||
| 3423 | s = "hello world from Lua" | ||
| 3424 | for w in string.gfind(s, "%a+") do | ||
| 3425 | print(w) | ||
| 3426 | end | ||
| 3427 | \end{verbatim} | ||
| 3428 | will iterate over all the words from string \verb|s|, | ||
| 3429 | printing one per line. | ||
| 3430 | The next example collects all pairs \verb|key=value| from the | ||
| 3431 | given string into a table: | ||
| 3432 | \begin{verbatim} | ||
| 3433 | t = {} | ||
| 3434 | s = "from=world, to=Lua" | ||
| 3435 | for k, v in string.gfind(s, "(%w+)=(%w+)") do | ||
| 3436 | t[k] = v | ||
| 3437 | end | ||
| 3438 | \end{verbatim} | ||
| 3439 | |||
| 3440 | \subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}} | ||
| 3441 | \DefLIB{string.gsub} | ||
| 3442 | Returns a copy of \verb|s| | ||
| 3443 | in which all occurrences of the pattern \verb|pat| have been | ||
| 3444 | replaced by a replacement string specified by \verb|repl|. | ||
| 3445 | \verb|gsub| also returns, as a second value, | ||
| 3446 | the total number of substitutions made. | ||
| 3447 | |||
| 3448 | If \verb|repl| is a string, then its value is used for replacement. | ||
| 3449 | Any sequence in \verb|repl| of the form \verb|%|\M{n}, | ||
| 3450 | with \M{n} between 1 and 9, | ||
| 3451 | stands for the value of the \M{n}-th captured substring. | ||
| 3452 | |||
| 3453 | If \verb|repl| is a function, then this function is called every time a | ||
| 3454 | match occurs, with all captured substrings passed as arguments, | ||
| 3455 | in order (see below); | ||
| 3456 | if the pattern specifies no captures, | ||
| 3457 | then the whole match is passed as a sole argument. | ||
| 3458 | If the value returned by this function is a string, | ||
| 3459 | then it is used as the replacement string; | ||
| 3460 | otherwise, the replacement string is the empty string. | ||
| 3461 | |||
| 3462 | The last, optional parameter \verb|n| limits | ||
| 3463 | the maximum number of substitutions to occur. | ||
| 3464 | For instance, when \verb|n| is 1 only the first occurrence of | ||
| 3465 | \verb|pat| is replaced. | ||
| 3466 | |||
| 3467 | Here are some examples: | ||
| 3468 | \begin{verbatim} | ||
| 3469 | x = string.gsub("hello world", "(%w+)", "%1 %1") | ||
| 3470 | --> x="hello hello world world" | ||
| 3471 | |||
| 3472 | x = string.gsub("hello world", "(%w+)", "%1 %1", 1) | ||
| 3473 | --> x="hello hello world" | ||
| 3474 | |||
| 3475 | x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") | ||
| 3476 | --> x="world hello Lua from" | ||
| 3477 | |||
| 3478 | x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) | ||
| 3479 | --> x="home = /home/roberto, user = roberto" (for instance) | ||
| 3480 | |||
| 3481 | x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) | ||
| 3482 | return loadstring(s)() | ||
| 3483 | end) | ||
| 3484 | --> x="4+5 = 9" | ||
| 3485 | |||
| 3486 | local t = {name="Lua", version="5.0"} | ||
| 3487 | x = string.gsub("$name - $version", "%$(%w+)", function (v) | ||
| 3488 | return t[v] | ||
| 3489 | end) | ||
| 3490 | --> x="Lua - 5.0" | ||
| 3491 | \end{verbatim} | ||
| 3492 | |||
| 3493 | |||
| 3494 | \subsubsection*{Patterns} \label{pm} | ||
| 3495 | |||
| 3496 | \paragraph{Character Class:} | ||
| 3497 | a \Def{character class} is used to represent a set of characters. | ||
| 3498 | The following combinations are allowed in describing a character class: | ||
| 3499 | \begin{description}\leftskip=20pt | ||
| 3500 | \item[\emph{x}] (where \emph{x} is not one of the magic characters | ||
| 3501 | \verb|^$()%.[]*+-?|) | ||
| 3502 | \Em{} represents the character \emph{x} itself. | ||
| 3503 | \item[\T{.}] \Em{} (a dot) represents all characters. | ||
| 3504 | \item[\T{%a}] \Em{} represents all letters. | ||
| 3505 | \item[\T{%c}] \Em{} represents all control characters. | ||
| 3506 | \item[\T{%d}] \Em{} represents all digits. | ||
| 3507 | \item[\T{%l}] \Em{} represents all lowercase letters. | ||
| 3508 | \item[\T{%p}] \Em{} represents all punctuation characters. | ||
| 3509 | \item[\T{%s}] \Em{} represents all space characters. | ||
| 3510 | \item[\T{%u}] \Em{} represents all uppercase letters. | ||
| 3511 | \item[\T{%w}] \Em{} represents all alphanumeric characters. | ||
| 3512 | \item[\T{%x}] \Em{} represents all hexadecimal digits. | ||
| 3513 | \item[\T{%z}] \Em{} represents the character with representation 0. | ||
| 3514 | \item[\T{%\M{x}}] (where \M{x} is any non-alphanumeric character) \Em{} | ||
| 3515 | represents the character \M{x}. | ||
| 3516 | This is the standard way to escape the magic characters. | ||
| 3517 | We recommend that any punctuation character (even the non magic) | ||
| 3518 | should be preceded by a \verb|%| | ||
| 3519 | when used to represent itself in a pattern. | ||
| 3520 | |||
| 3521 | \item[\T{[\M{set}]}] \Em{} | ||
| 3522 | represents the class which is the union of all | ||
| 3523 | characters in \M{set}. | ||
| 3524 | A range of characters may be specified by | ||
| 3525 | separating the end characters of the range with a \verb|-|. | ||
| 3526 | All classes \verb|%|\emph{x} described above may also be used as | ||
| 3527 | components in \M{set}. | ||
| 3528 | All other characters in \M{set} represent themselves. | ||
| 3529 | For example, \verb|[%w_]| (or \verb|[_%w]|) | ||
| 3530 | represents all alphanumeric characters plus the underscore, | ||
| 3531 | \verb|[0-7]| represents the octal digits, | ||
| 3532 | and \verb|[0-7%l%-]| represents the octal digits plus | ||
| 3533 | the lowercase letters plus the \verb|-| character. | ||
| 3534 | |||
| 3535 | The interaction between ranges and classes is not defined. | ||
| 3536 | Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]| | ||
| 3537 | have no meaning. | ||
| 3538 | |||
| 3539 | \item[\T{[^\M{set}]}] \Em{} | ||
| 3540 | represents the complement of \M{set}, | ||
| 3541 | where \M{set} is interpreted as above. | ||
| 3542 | \end{description} | ||
| 3543 | For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), | ||
| 3544 | the corresponding uppercase letter represents the complement of the class. | ||
| 3545 | For instance, \verb|%S| represents all non-space characters. | ||
| 3546 | |||
| 3547 | The definitions of letter, space, etc.{} depend on the current locale. | ||
| 3548 | In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. | ||
| 3549 | The second form should be preferred for portability. | ||
| 3550 | |||
| 3551 | \paragraph{Pattern Item:} | ||
| 3552 | a \Def{pattern item} may be | ||
| 3553 | \begin{itemize} | ||
| 3554 | \item | ||
| 3555 | a single character class, | ||
| 3556 | which matches any single character in the class; | ||
| 3557 | \item | ||
| 3558 | a single character class followed by \verb|*|, | ||
| 3559 | which matches 0 or more repetitions of characters in the class. | ||
| 3560 | These repetition items will always match the longest possible sequence; | ||
| 3561 | \item | ||
| 3562 | a single character class followed by \verb|+|, | ||
| 3563 | which matches 1 or more repetitions of characters in the class. | ||
| 3564 | These repetition items will always match the longest possible sequence; | ||
| 3565 | \item | ||
| 3566 | a single character class followed by \verb|-|, | ||
| 3567 | which also matches 0 or more repetitions of characters in the class. | ||
| 3568 | Unlike \verb|*|, | ||
| 3569 | these repetition items will always match the \emph{shortest} possible sequence; | ||
| 3570 | \item | ||
| 3571 | a single character class followed by \verb|?|, | ||
| 3572 | which matches 0 or 1 occurrence of a character in the class; | ||
| 3573 | \item | ||
| 3574 | \T{%\M{n}}, for \M{n} between 1 and 9; | ||
| 3575 | such item matches a substring equal to the \M{n}-th captured string | ||
| 3576 | (see below); | ||
| 3577 | \item | ||
| 3578 | \T{%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; | ||
| 3579 | such item matches strings that start with\Nb{}\M{x}, end with\Nb{}\M{y}, | ||
| 3580 | and where the \M{x} and \M{y} are \emph{balanced}. | ||
| 3581 | This means that, if one reads the string from left to right, | ||
| 3582 | counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y}, | ||
| 3583 | the ending \M{y} is the first \M{y} where the count reaches 0. | ||
| 3584 | For instance, the item \verb|%b()| matches expressions with | ||
| 3585 | balanced parentheses. | ||
| 3586 | \end{itemize} | ||
| 3587 | |||
| 3588 | \paragraph{Pattern:} | ||
| 3589 | a \Def{pattern} is a sequence of pattern items. | ||
| 3590 | A \verb|^| at the beginning of a pattern anchors the match at the | ||
| 3591 | beginning of the subject string. | ||
| 3592 | A \verb|$| at the end of a pattern anchors the match at the | ||
| 3593 | end of the subject string. | ||
| 3594 | At other positions, | ||
| 3595 | \verb|^| and \verb|$| have no special meaning and represent themselves. | ||
| 3596 | |||
| 3597 | \paragraph{Captures:} | ||
| 3598 | A pattern may contain sub-patterns enclosed in parentheses; | ||
| 3599 | they describe \Def{captures}. | ||
| 3600 | When a match succeeds, the substrings of the subject string | ||
| 3601 | that match captures are stored (\emph{captured}) for future use. | ||
| 3602 | Captures are numbered according to their left parentheses. | ||
| 3603 | For instance, in the pattern \verb|"(a*(.)%w(%s*))"|, | ||
| 3604 | the part of the string matching \verb|"a*(.)%w(%s*)"| is | ||
| 3605 | stored as the first capture (and therefore has number\Nb{}1); | ||
| 3606 | the character matching \verb|.| is captured with number\Nb{}2, | ||
| 3607 | and the part matching \verb|%s*| has number\Nb{}3. | ||
| 3608 | |||
| 3609 | As a special case, the empty capture \verb|()| captures | ||
| 3610 | the current string position (a number). | ||
| 3611 | For instance, if we apply the pattern \verb|"()aa()"| on the | ||
| 3612 | string \verb|"flaaap"|, there will be two captures: 3 and 5. | ||
| 3613 | |||
| 3614 | \NOTE | ||
| 3615 | A pattern cannot contain embedded zeros. Use \verb|%z| instead. | ||
| 3616 | |||
| 3617 | |||
| 3618 | \subsection{Table Manipulation} | ||
| 3619 | This library provides generic functions for table manipulation. | ||
| 3620 | It provides all its functions inside the table \IndexLIB{table}. | ||
| 3621 | |||
| 3622 | Most functions in the table library assume that the table | ||
| 3623 | represents an array or a list. | ||
| 3624 | For those functions, an important concept is the \emph{size} of the array. | ||
| 3625 | There are three ways to specify that size: | ||
| 3626 | \begin{itemize} | ||
| 3627 | \item the field \verb|"n"| \Em{} | ||
| 3628 | When the table has a field \verb|"n"| with a numerical value, | ||
| 3629 | that value is assumed as its size. | ||
| 3630 | \item \verb|setn| \Em{} | ||
| 3631 | You can call the \verb|table.setn| function to explicitly set | ||
| 3632 | the size of a table. | ||
| 3633 | \item implicit size \Em{} | ||
| 3634 | Otherwise, the size of the object is one less the first integer index | ||
| 3635 | with a \nil{} value. | ||
| 3636 | \end{itemize} | ||
| 3637 | For more details, see the descriptions of the \verb|table.getn| and | ||
| 3638 | \verb|table.setn| functions. | ||
| 3639 | |||
| 3640 | \subsubsection*{\ff \T{table.concat (table [, sep [, i [, j]]])}} | ||
| 3641 | \DefLIB{table.concat} | ||
| 3642 | Returns \verb|table[i]..sep..table[i+1] ... sep..table[j]|. | ||
| 3643 | The default value for \verb|sep| is the empty string, | ||
| 3644 | the default for \verb|i| is 1, | ||
| 3645 | and the default for \verb|j| is the size of the table. | ||
| 3646 | If \verb|i| is greater than \verb|j|, returns the empty string. | ||
| 3647 | |||
| 3648 | \subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach} | ||
| 3649 | Executes the given \verb|func| over all elements of \verb|table|. | ||
| 3650 | For each element, \verb|func| is called with the index and | ||
| 3651 | respective value as arguments. | ||
| 3652 | If \verb|func| returns a non-\nil{} value, | ||
| 3653 | then the loop is broken, and this value is returned | ||
| 3654 | as the final value of \verb|foreach|. | ||
| 3655 | |||
| 3656 | The behavior of \verb|foreach| is \emph{undefined} if you change | ||
| 3657 | the table \verb|t| during the traversal. | ||
| 3658 | |||
| 3659 | |||
| 3660 | \subsubsection*{\ff \T{table.foreachi (table, func)}}\DefLIB{table.foreachi} | ||
| 3661 | Executes the given \verb|func| over the | ||
| 3662 | numerical indices of \verb|table|. | ||
| 3663 | For each index, \verb|func| is called with the index and | ||
| 3664 | respective value as arguments. | ||
| 3665 | Indices are visited in sequential order, | ||
| 3666 | from\Nb{}1 to \verb|n|, | ||
| 3667 | where \verb|n| is the size of the table \see{getn}. | ||
| 3668 | If \verb|func| returns a non-\nil{} value, | ||
| 3669 | then the loop is broken, and this value is returned | ||
| 3670 | as the final value of \verb|foreachi|. | ||
| 3671 | |||
| 3672 | \subsubsection*{\ff \T{table.getn (table)}}\DefLIB{table.getn}\label{getn} | ||
| 3673 | Returns the \Q{size} of a table, when seen as a list. | ||
| 3674 | If the table has an \verb|n| field with a numeric value, | ||
| 3675 | this value is the \Q{size} of the table. | ||
| 3676 | Otherwise, if there was a previous call to | ||
| 3677 | \verb|table.getn| or to \verb|table.setn| over this table, | ||
| 3678 | the respective value is returned. | ||
| 3679 | Otherwise, the \Q{size} is one less the first integer index with | ||
| 3680 | a \nil{} value. | ||
| 3681 | |||
| 3682 | Notice that the last option happens only once for a table. | ||
| 3683 | If you call \verb|table.getn| again over the same table, | ||
| 3684 | it will return the same previous result, | ||
| 3685 | even if the table has been modified. | ||
| 3686 | The only way to change the value of \verb|table.getn| is by calling | ||
| 3687 | \verb|table.setn| or assigning to field \verb|"n"| in the table. | ||
| 3688 | |||
| 3689 | \subsubsection*{\ff \T{table.sort (table [, comp])}}\DefLIB{table.sort} | ||
| 3690 | Sorts table elements in a given order, \emph{in-place}, | ||
| 3691 | from \verb|table[1]| to \verb|table[n]|, | ||
| 3692 | where \verb|n| is the size of the table \see{getn}. | ||
| 3693 | If \verb|comp| is given, | ||
| 3694 | then it must be a function that receives two table elements, | ||
| 3695 | and returns true | ||
| 3696 | when the first is less than the second | ||
| 3697 | (so that \verb|not comp(a[i+1],a[i])| will be true after the sort). | ||
| 3698 | If \verb|comp| is not given, | ||
| 3699 | then the standard Lua operator \verb|<| is used instead. | ||
| 3700 | |||
| 3701 | The sort algorithm is \emph{not} stable | ||
| 3702 | (that is, elements considered equal by the given order | ||
| 3703 | may have their relative positions changed by the sort). | ||
| 3704 | |||
| 3705 | \subsubsection*{\ff \T{table.insert (table, [pos,] value)}}\DefLIB{table.insert} | ||
| 3706 | |||
| 3707 | Inserts element \verb|value| at position \verb|pos| in \verb|table|, | ||
| 3708 | shifting other elements up to open space, if necessary. | ||
| 3709 | The default value for \verb|pos| is \verb|n+1|, | ||
| 3710 | where \verb|n| is the size of the table \see{getn}, | ||
| 3711 | so that a call \verb|table.insert(t,x)| inserts \verb|x| at the end | ||
| 3712 | of table \verb|t|. | ||
| 3713 | This function also updates the size of the table by | ||
| 3714 | calling \verb|table.setn(table, n+1)|. | ||
| 3715 | |||
| 3716 | \subsubsection*{\ff \T{table.remove (table [, pos])}}\DefLIB{table.remove} | ||
| 3717 | |||
| 3718 | Removes from \verb|table| the element at position \verb|pos|, | ||
| 3719 | shifting other elements down to close the space, if necessary. | ||
| 3720 | Returns the value of the removed element. | ||
| 3721 | The default value for \verb|pos| is \verb|n|, | ||
| 3722 | where \verb|n| is the size of the table \see{getn}, | ||
| 3723 | so that a call \verb|tremove(t)| removes the last element | ||
| 3724 | of table \verb|t|. | ||
| 3725 | This function also updates the size of the table by | ||
| 3726 | calling \verb|table.setn(table, n-1)|. | ||
| 3727 | |||
| 3728 | \subsubsection*{\ff \T{table.setn (table, n)}}\DefLIB{table.setn} | ||
| 3729 | |||
| 3730 | Updates the \Q{size} of a table. | ||
| 3731 | If the table has a field \verb|"n"| with a numerical value, | ||
| 3732 | that value is changed to the given \verb|n|. | ||
| 3733 | Otherwise, it updates an internal state of the \verb|table| library | ||
| 3734 | so that subsequent calls to \verb|table.getn(table)| return \verb|n|. | ||
| 3735 | |||
| 3736 | |||
| 3737 | \subsection{Mathematical Functions} \label{mathlib} | ||
| 3738 | |||
| 3739 | This library is an interface to most of the functions of the | ||
| 3740 | standard C\Nb{}math library. | ||
| 3741 | (Some have slightly different names.) | ||
| 3742 | It provides all its functions inside the table \IndexLIB{math}. | ||
| 3743 | In addition, | ||
| 3744 | it registers a ??tag method for the binary exponentiation operator \verb|^| | ||
| 3745 | that returns \Math{x\sp{y}} when applied to numbers \verb|x| and \verb|y|. | ||
| 3746 | |||
| 3747 | The library provides the following functions: | ||
| 3748 | \DefLIB{math.abs}\DefLIB{math.acos}\DefLIB{math.asin}\DefLIB{math.atan} | ||
| 3749 | \DefLIB{math.atan2}\DefLIB{math.ceil}\DefLIB{math.cos} | ||
| 3750 | \DefLIB{math.def}\DefLIB{math.exp} | ||
| 3751 | \DefLIB{math.floor}\DefLIB{math.log}\DefLIB{math.log10} | ||
| 3752 | \DefLIB{math.max}\DefLIB{math.min} | ||
| 3753 | \DefLIB{math.mod}\DefLIB{math.rad}\DefLIB{math.sin} | ||
| 3754 | \DefLIB{math.sqrt}\DefLIB{math.tan} | ||
| 3755 | \DefLIB{math.frexp}\DefLIB{math.ldexp}\DefLIB{math.random} | ||
| 3756 | \DefLIB{math.randomseed} | ||
| 3757 | \begin{verbatim} | ||
| 3758 | math.abs math.acos math.asin math.atan math.atan2 | ||
| 3759 | math.ceil math.cos math.deg math.exp math.floor | ||
| 3760 | math.log math.log10 math.max math.min math.mod | ||
| 3761 | math.rad math.sin math.sqrt math.tan math.frexp | ||
| 3762 | math.ldexp math.random math.randomseed | ||
| 3763 | \end{verbatim} | ||
| 3764 | plus a variable \IndexLIB{math.pi}. | ||
| 3765 | Most of them | ||
| 3766 | are only interfaces to the corresponding functions in the C\Nb{}library. | ||
| 3767 | All trigonometric functions work in radians. | ||
| 3768 | The functions \verb|math.deg| and \verb|math.rad| convert | ||
| 3769 | between radians and degrees. | ||
| 3770 | |||
| 3771 | The function \verb|math.max| returns the maximum | ||
| 3772 | value of its numeric arguments. | ||
| 3773 | Similarly, \verb|math.min| computes the minimum. | ||
| 3774 | Both can be used with 1, 2, or more arguments. | ||
| 3775 | |||
| 3776 | The functions \verb|math.random| and \verb|math.randomseed| | ||
| 3777 | are interfaces to the simple random generator functions | ||
| 3778 | \verb|rand| and \verb|srand| that are provided by ANSI\Nb{}C. | ||
| 3779 | (No guarantees can be given for their statistical properties.) | ||
| 3780 | When called without arguments, | ||
| 3781 | \verb|math.random| returns a pseudo-random real number | ||
| 3782 | in the range \Math{[0,1)}. \C{]} | ||
| 3783 | When called with a number \Math{n}, | ||
| 3784 | \verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}. | ||
| 3785 | When called with two arguments, \Math{l} and \Math{u}, | ||
| 3786 | \verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}. | ||
| 3787 | The \verb|math.randomseed| function sets a \Q{seed} | ||
| 3788 | for the pseudo-random generator: | ||
| 3789 | Equal seeds produce equal sequences of numbers. | ||
| 3790 | |||
| 3791 | |||
| 3792 | \subsection{Input and Output Facilities} \label{libio} | ||
| 3793 | |||
| 3794 | The I/O library provides two different styles for file manipulation. | ||
| 3795 | The first one uses implicit file descriptors; | ||
| 3796 | that is, there are operations to set a default input file and a | ||
| 3797 | default output file, | ||
| 3798 | and all input/output operations are over those default files. | ||
| 3799 | The second style uses explicit file descriptors. | ||
| 3800 | |||
| 3801 | When using implicit file descriptors, | ||
| 3802 | all operations are supplied by table \IndexLIB{io}. | ||
| 3803 | When using explicit file descriptors, | ||
| 3804 | the operation \IndexLIB{io.open} returns a file descriptor, | ||
| 3805 | and then all operations are supplied as methods by the file descriptor. | ||
| 3806 | |||
| 3807 | The table \verb|io| also provides | ||
| 3808 | three predefined file descriptors with their usual meanings from C: | ||
| 3809 | \IndexLIB{io.stdin}, \IndexLIB{io.stdout}, and \IndexLIB{io.stderr}. | ||
| 3810 | |||
| 3811 | A file handle is a userdata containing the file stream (\verb|FILE*|), | ||
| 3812 | with a distinctive metatable created by the I/O library. | ||
| 3813 | |||
| 3814 | Unless otherwise stated, | ||
| 3815 | all I/O functions return \nil{} on failure | ||
| 3816 | (plus an error message as a second result) | ||
| 3817 | and some value different from \nil{} on success. | ||
| 3818 | |||
| 3819 | \subsubsection*{\ff \T{io.close ([file])}}\DefLIB{io.close} | ||
| 3820 | |||
| 3821 | Equivalent to \verb|file:close()|. | ||
| 3822 | Without a \verb|file|, closes the default output file. | ||
| 3823 | |||
| 3824 | \subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush} | ||
| 3825 | |||
| 3826 | Equivalent to \verb|file:flush| over the default output file. | ||
| 3827 | |||
| 3828 | \subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input} | ||
| 3829 | |||
| 3830 | When called with a file name, it opens the named file (in text mode), | ||
| 3831 | and sets its handle as the default input file | ||
| 3832 | (and returns nothing). | ||
| 3833 | When called with a file handle, | ||
| 3834 | it simply sets that file handle as the default input file. | ||
| 3835 | When called without parameters, | ||
| 3836 | it returns the current default input file. | ||
| 3837 | |||
| 3838 | In case of errors this function raises the error, | ||
| 3839 | instead of returning an error code. | ||
| 3840 | |||
| 3841 | \subsubsection*{\ff \T{io.lines ([filename])}}\DefLIB{io.lines} | ||
| 3842 | |||
| 3843 | Opens the given file name in read mode, | ||
| 3844 | and returns a generator function that, | ||
| 3845 | each time it is called, | ||
| 3846 | returns a new line from the file. | ||
| 3847 | Therefore, the construction | ||
| 3848 | \begin{verbatim} | ||
| 3849 | for line in io.lines(filename) do ... end | ||
| 3850 | \end{verbatim} | ||
| 3851 | will iterate over all lines of the file. | ||
| 3852 | When the generator function detects the end of file, | ||
| 3853 | it returns nil (to finish the loop) and automatically closes the file. | ||
| 3854 | |||
| 3855 | The call \verb|io.lines()| (without a file name) is equivalent | ||
| 3856 | to \verb|io.input():lines()|, that is, it iterates over the | ||
| 3857 | lines of the default input file. | ||
| 3858 | |||
| 3859 | \subsubsection*{\ff \T{io.open (filename [, mode])}}\DefLIB{io.open} | ||
| 3860 | |||
| 3861 | This function opens a file, | ||
| 3862 | in the mode specified in the string \verb|mode|. | ||
| 3863 | It returns a new file handle, | ||
| 3864 | or, in case of errors, \nil{} plus an error message. | ||
| 3865 | |||
| 3866 | The \verb|mode| string can be any of the following: | ||
| 3867 | \begin{description}\leftskip=20pt | ||
| 3868 | \item[\Q{r}] read mode (the default); | ||
| 3869 | \item[\Q{w}] write mode; | ||
| 3870 | \item[\Q{a}] append mode; | ||
| 3871 | \item[\Q{r+}] update mode, all previous data is preserved; | ||
| 3872 | \item[\Q{w+}] update mode, all previous data is erased; | ||
| 3873 | \item[\Q{a+}] append update mode, previous data is preserved, | ||
| 3874 | writing is only allowed at the end of file. | ||
| 3875 | \end{description} | ||
| 3876 | The \verb|mode| string may also have a \verb|b| at the end, | ||
| 3877 | which is needed in some systems to open the file in binary mode. | ||
| 3878 | This string is exactly what is used in the standard\Nb{}C function \verb|fopen|. | ||
| 3879 | |||
| 3880 | \subsubsection*{\ff \T{io.output ([file])}}\DefLIB{io.output} | ||
| 3881 | |||
| 3882 | Similar to \verb|io.input|, but operates over the default output file. | ||
| 3883 | |||
| 3884 | \subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read} | ||
| 3885 | |||
| 3886 | Equivalent to \verb|file:read| over the default input file. | ||
| 3887 | |||
| 3888 | \subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile} | ||
| 3889 | |||
| 3890 | Returns a handle for a temporary file. | ||
| 3891 | This file is open in read/write mode, | ||
| 3892 | and it is automatically removed when the program ends. | ||
| 3893 | |||
| 3894 | \subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write} | ||
| 3895 | |||
| 3896 | Equivalent to \verb|file:write| over the default output file. | ||
| 3897 | |||
| 3898 | |||
| 3899 | |||
| 3900 | \subsubsection*{\ff \T{file:close ()}}\DefLIB{file:close} | ||
| 3901 | |||
| 3902 | Closes the file \verb|file|. | ||
| 3903 | |||
| 3904 | \subsubsection*{\ff \T{file:flush ()}}\DefLIB{file:flush} | ||
| 3905 | |||
| 3906 | Saves any written data to the file \verb|file|. | ||
| 3907 | |||
| 3908 | \subsubsection*{\ff \T{file:lines ()}}\DefLIB{file:lines} | ||
| 3909 | |||
| 3910 | Returns a generator function that, | ||
| 3911 | each time it is called, | ||
| 3912 | returns a new line from the file. | ||
| 3913 | Therefore, the construction | ||
| 3914 | \begin{verbatim} | ||
| 3915 | for line in file:lines() do ... end | ||
| 3916 | \end{verbatim} | ||
| 3917 | will iterate over all lines of the file. | ||
| 3918 | (Unlike \verb|io.lines|, this function does not close the file | ||
| 3919 | when the loop ends.) | ||
| 3920 | |||
| 3921 | \subsubsection*{\ff \T{file:read (format1, ...)}}\DefLIB{file:read} | ||
| 3922 | |||
| 3923 | Reads the file \verb|file|, | ||
| 3924 | according to the given formats, which specify what to read. | ||
| 3925 | For each format, | ||
| 3926 | the function returns a string (or a number) with the characters read, | ||
| 3927 | or \nil{} if it cannot read data with the specified format. | ||
| 3928 | When called without formats, | ||
| 3929 | it uses a default format that reads the entire next line | ||
| 3930 | (see below). | ||
| 3931 | |||
| 3932 | The available formats are | ||
| 3933 | \begin{description}\leftskip=20pt | ||
| 3934 | \item[\Q{*n}] reads a number; | ||
| 3935 | this is the only format that returns a number instead of a string. | ||
| 3936 | \item[\Q{*a}] reads the whole file, starting at the current position. | ||
| 3937 | On end of file, it returns the empty string. | ||
| 3938 | \item[\Q{*l}] reads the next line (skipping the end of line), | ||
| 3939 | returning \nil{} on end of file. | ||
| 3940 | This is the default format. | ||
| 3941 | \item[\emph{number}] reads a string with up to that number of characters, | ||
| 3942 | or \nil{} on end of file. | ||
| 3943 | If number is zero, | ||
| 3944 | it reads nothing and returns an empty string, | ||
| 3945 | or \nil{} on end of file. | ||
| 3946 | \end{description} | ||
| 3947 | |||
| 3948 | \subsubsection*{\ff \T{file:seek ([whence] [, offset])}}\DefLIB{file:seek} | ||
| 3949 | |||
| 3950 | Sets and gets the file position, | ||
| 3951 | measured in bytes from the beginning of the file, | ||
| 3952 | to the position given by \verb|offset| plus a base | ||
| 3953 | specified by the string \verb|whence|, as follows: | ||
| 3954 | \begin{description}\leftskip=20pt | ||
| 3955 | \item[\Q{set}] base is position 0 (beginning of the file); | ||
| 3956 | \item[\Q{cur}] base is current position; | ||
| 3957 | \item[\Q{end}] base is end of file; | ||
| 3958 | \end{description} | ||
| 3959 | In case of success, function \verb|seek| returns the final file position, | ||
| 3960 | measured in bytes from the beginning of the file. | ||
| 3961 | If this function fails, it returns \nil{}, | ||
| 3962 | plus a string describing the error. | ||
| 3963 | |||
| 3964 | The default value for \verb|whence| is \verb|"cur"|, | ||
| 3965 | and for \verb|offset| is 0. | ||
| 3966 | Therefore, the call \verb|file:seek()| returns the current | ||
| 3967 | file position, without changing it; | ||
| 3968 | the call \verb|file:seek("set")| sets the position to the | ||
| 3969 | beginning of the file (and returns 0); | ||
| 3970 | and the call \verb|file:seek("end")| sets the position to the | ||
| 3971 | end of the file, and returns its size. | ||
| 3972 | |||
| 3973 | \subsubsection*{\ff \T{file:write (value1, ...)}}\DefLIB{file:write} | ||
| 3974 | |||
| 3975 | Writes the value of each of its arguments to | ||
| 3976 | the filehandle \verb|file|. | ||
| 3977 | The arguments must be strings or numbers. | ||
| 3978 | To write other values, | ||
| 3979 | use \verb|tostring| or \verb|format| before \verb|write|. | ||
| 3980 | If this function fails, it returns \nil{}, | ||
| 3981 | plus a string describing the error. | ||
| 3982 | |||
| 3983 | |||
| 3984 | \subsection{Operating System Facilities} \label{libiosys} | ||
| 3985 | |||
| 3986 | This library is implemented through table \IndexLIB{os}. | ||
| 3987 | |||
| 3988 | \subsubsection*{\ff \T{os.clock ()}}\DefLIB{os.clock} | ||
| 3989 | |||
| 3990 | Returns an approximation of the amount of CPU time | ||
| 3991 | used by the program, in seconds. | ||
| 3992 | |||
| 3993 | \subsubsection*{\ff \T{os.date ([format [, time]])}}\DefLIB{os.date} | ||
| 3994 | |||
| 3995 | Returns a string or a table containing date and time, | ||
| 3996 | formatted according to the given string \verb|format|. | ||
| 3997 | |||
| 3998 | If the \verb|time| argument is present, | ||
| 3999 | this is the time to be formatted | ||
| 4000 | (see the \verb|time| function for a description of this value). | ||
| 4001 | Otherwise, \verb|date| formats the current time. | ||
| 4002 | |||
| 4003 | If \verb|format| starts with \verb|!|, | ||
| 4004 | then the date is formatted in Coordinated Universal Time. | ||
| 4005 | |||
| 4006 | After that optional character, | ||
| 4007 | if \verb|format| is \verb|*t|, | ||
| 4008 | then \verb|date| returns a table with the following fields: | ||
| 4009 | \verb|year| (four digits), \verb|month| (1--12), \verb|day| (1--31), | ||
| 4010 | \verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--61), | ||
| 4011 | \verb|wday| (weekday, Sunday is 1), | ||
| 4012 | \verb|yday| (day of the year), | ||
| 4013 | and \verb|isdst| (daylight saving flag, a boolean). | ||
| 4014 | |||
| 4015 | If format is not \verb|*t|, | ||
| 4016 | then \verb|date| returns the date as a string, | ||
| 4017 | formatted according with the same rules as the C\Nb{}function \verb|strftime|. | ||
| 4018 | When called without arguments, | ||
| 4019 | \verb|date| returns a reasonable date and time representation that depends on | ||
| 4020 | the host system and on the current locale | ||
| 4021 | (that is, \verb|os.date()| is equivalent to \verb|os.date("%c")|). | ||
| 4022 | |||
| 4023 | \subsubsection*{\ff \T{os.difftime (t2, t1)}}\DefLIB{os.difftime} | ||
| 4024 | |||
| 4025 | Returns the number of seconds from time \verb|t1| to time \verb|t2|. | ||
| 4026 | In Posix, Windows, and some other systems, | ||
| 4027 | this value is exactly \verb|t2|\Math{-}\verb|t1|. | ||
| 4028 | |||
| 4029 | \subsubsection*{\ff \T{os.execute (command)}}\DefLIB{os.execute} | ||
| 4030 | |||
| 4031 | This function is equivalent to the C\Nb{}function \verb|system|. | ||
| 4032 | It passes \verb|command| to be executed by an operating system shell. | ||
| 4033 | It returns a status code, which is system-dependent. | ||
| 4034 | |||
| 4035 | \subsubsection*{\ff \T{os.exit ([code])}}\DefLIB{os.exit} | ||
| 4036 | |||
| 4037 | Calls the C\Nb{}function \verb|exit|, | ||
| 4038 | with an optional \verb|code|, | ||
| 4039 | to terminate the host program. | ||
| 4040 | The default value for \verb|code| is the success code. | ||
| 4041 | |||
| 4042 | \subsubsection*{\ff \T{os.getenv (varname)}}\DefLIB{os.getenv} | ||
| 4043 | |||
| 4044 | Returns the value of the process environment variable \verb|varname|, | ||
| 4045 | or \nil{} if the variable is not defined. | ||
| 4046 | |||
| 4047 | \subsubsection*{\ff \T{os.remove (filename)}}\DefLIB{os.remove} | ||
| 4048 | |||
| 4049 | Deletes the file with the given name. | ||
| 4050 | If this function fails, it returns \nil{}, | ||
| 4051 | plus a string describing the error. | ||
| 4052 | |||
| 4053 | \subsubsection*{\ff \T{os.rename (name1, name2)}}\DefLIB{os.rename} | ||
| 4054 | |||
| 4055 | Renames file named \verb|name1| to \verb|name2|. | ||
| 4056 | If this function fails, it returns \nil{}, | ||
| 4057 | plus a string describing the error. | ||
| 4058 | |||
| 4059 | \subsubsection*{\ff \T{os.setlocale (locale [, category])}}\DefLIB{os.setlocale} | ||
| 4060 | |||
| 4061 | This function is an interface to the C\Nb{}function \verb|setlocale|. | ||
| 4062 | \verb|locale| is a string specifying a locale; | ||
| 4063 | \verb|category| is an optional string describing which category to change: | ||
| 4064 | \verb|"all"|, \verb|"collate"|, \verb|"ctype"|, | ||
| 4065 | \verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|; | ||
| 4066 | the default category is \verb|"all"|. | ||
| 4067 | The function returns the name of the new locale, | ||
| 4068 | or \nil{} if the request cannot be honored. | ||
| 4069 | |||
| 4070 | \subsubsection*{\ff \T{os.time ([table])}}\DefLIB{os.time} | ||
| 4071 | |||
| 4072 | Returns the current time when called without arguments, | ||
| 4073 | or a time representing the date and time specified by the given table. | ||
| 4074 | This table must have fields \verb|year|, \verb|month|, and \verb|day|, | ||
| 4075 | and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| | ||
| 4076 | (for a description of these fields, see the \verb|os.date| function). | ||
| 4077 | |||
| 4078 | The returned value is a number, whose meaning depends on your system. | ||
| 4079 | In Posix, Windows, and some other systems, this number counts the number | ||
| 4080 | of seconds since some given start time (the \Q{epoch}). | ||
| 4081 | In other systems, the meaning is not specified, | ||
| 4082 | and the number returned by \verb|time| can be used only as an argument to | ||
| 4083 | \verb|date| and \verb|difftime|. | ||
| 4084 | |||
| 4085 | \subsubsection*{\ff \T{os.tmpname ()}}\DefLIB{os.tmpname} | ||
| 4086 | |||
| 4087 | Returns a string with a file name that can | ||
| 4088 | be used for a temporary file. | ||
| 4089 | The file must be explicitly opened before its use | ||
| 4090 | and removed when no longer needed. | ||
| 4091 | |||
| 4092 | This function is equivalent to the \verb|tmpnam| C\Nb{}function, | ||
| 4093 | and many people (and even some compilers!) advise against its use, | ||
| 4094 | because between the time you call this function | ||
| 4095 | and the time you open the file, | ||
| 4096 | it is possible for another process | ||
| 4097 | to create a file with the same name. | ||
| 4098 | |||
| 4099 | |||
| 4100 | \subsection{The Reflexive Debug Interface} | ||
| 4101 | |||
| 4102 | The library \verb|ldblib| provides | ||
| 4103 | the functionality of the debug interface to Lua programs. | ||
| 4104 | You should exert great care when using this library. | ||
| 4105 | The functions provided here should be used exclusively for debugging | ||
| 4106 | and similar tasks, such as profiling. | ||
| 4107 | Please resist the temptation to use them as a | ||
| 4108 | usual programming tool: | ||
| 4109 | They can be very slow. | ||
| 4110 | Moreover, \verb|setlocal| and \verb|getlocal| | ||
| 4111 | violate the privacy of local variables, | ||
| 4112 | and therefore can compromise some (otherwise) secure code. | ||
| 4113 | |||
| 4114 | All functions in this library are provided | ||
| 4115 | inside a \IndexVerb{debug} table. | ||
| 4116 | |||
| 4117 | |||
| 4118 | \subsubsection*{\ff \T{debug.getinfo (function, [what])}}\DefLIB{debug.getinfo} | ||
| 4119 | |||
| 4120 | This function returns a table with information about a function. | ||
| 4121 | You can give the function directly, | ||
| 4122 | or you can give a number as the value of \verb|function|, | ||
| 4123 | which means the function running at level \verb|function| of the stack: | ||
| 4124 | Level 0 is the current function (\verb|getinfo| itself); | ||
| 4125 | level 1 is the function that called \verb|getinfo|; | ||
| 4126 | and so on. | ||
| 4127 | If \verb|function| is a number larger than the number of active functions, | ||
| 4128 | then \verb|getinfo| returns \nil{}. | ||
| 4129 | |||
| 4130 | The returned table contains all the fields returned by \verb|lua_getinfo|, | ||
| 4131 | with the string \verb|what| describing which fields to fill in. | ||
| 4132 | The default for \verb|what| is to get all information available. | ||
| 4133 | If present, | ||
| 4134 | the option \verb|f| | ||
| 4135 | adds a field named \verb|func| with the function itself. | ||
| 4136 | |||
| 4137 | For instance, the expression \verb|debug.getinfo(1,"n").name| returns | ||
| 4138 | the name of the current function, if a reasonable name can be found, | ||
| 4139 | and \verb|debug.getinfo(print)| returns a table with all available information | ||
| 4140 | about the \verb|print| function. | ||
| 4141 | |||
| 4142 | |||
| 4143 | \subsubsection*{\ff \T{debug.getlocal (level, local)}}\DefLIB{debug.getlocal} | ||
| 4144 | |||
| 4145 | This function returns the name and the value of the local variable | ||
| 4146 | with index \verb|local| of the function at level \verb|level| of the stack. | ||
| 4147 | (The first parameter or local variable has index\Nb{}1, and so on, | ||
| 4148 | until the last active local variable.) | ||
| 4149 | The function returns \nil{} if there is no local | ||
| 4150 | variable with the given index, | ||
| 4151 | and raises an error when called with a \verb|level| out of range. | ||
| 4152 | (You can call \verb|getinfo| to check whether the level is valid.) | ||
| 4153 | |||
| 4154 | \subsubsection*{\ff \T{debug.setlocal (level, local, value)}} | ||
| 4155 | \DefLIB{debug.setlocal} | ||
| 4156 | |||
| 4157 | This function assigns the value \verb|value| to the local variable | ||
| 4158 | with index \verb|local| of the function at level \verb|level| of the stack. | ||
| 4159 | The function returns \nil{} if there is no local | ||
| 4160 | variable with the given index, | ||
| 4161 | and raises an error when called with a \verb|level| out of range. | ||
| 4162 | (You can call \verb|getinfo| to check whether the level is valid.) | ||
| 4163 | |||
| 4164 | \subsubsection*{\ff \T{debug.sethook (hook, mask [, count])}} | ||
| 4165 | \DefLIB{debug.sethook} | ||
| 4166 | |||
| 4167 | Sets the given function as a hook. | ||
| 4168 | The string \verb|mask| and the number \verb|count| describe | ||
| 4169 | when the hook will be called. | ||
| 4170 | The string mask may have the following characters, | ||
| 4171 | with the given meaning: | ||
| 4172 | \begin{description} | ||
| 4173 | \item[{\tt "c"}] The hook is called every time Lua calls a function; | ||
| 4174 | \item[{\tt "r"}] The hook is called every time Lua returns from a function; | ||
| 4175 | \item[{\tt "l"}] The hook is called every time Lua enters a new line of code. | ||
| 4176 | \end{description} | ||
| 4177 | With a \verb|count| different from zero, | ||
| 4178 | the hook is called after every \verb|count| instructions. | ||
| 4179 | |||
| 4180 | When called without arguments, | ||
| 4181 | the \verb|debug.sethook| function turns off the hook. | ||
| 4182 | |||
| 4183 | When the hook is called, its first parameter is always a string | ||
| 4184 | describing the event that triggered its call: | ||
| 4185 | \verb|"call"|, \verb|"return"|, \verb|"line"|, and \verb|"count"|. | ||
| 4186 | Moreover, for line events, | ||
| 4187 | it also gets as its second parameter the new line number. | ||
| 4188 | Inside a hook, | ||
| 4189 | you can call \verb|getinfo| with level 2 to get more information about | ||
| 4190 | the running function | ||
| 4191 | (level\Nb{}0 is the \verb|getinfo| function, | ||
| 4192 | and level\Nb{}1 is the hook function). | ||
| 4193 | |||
| 4194 | \subsubsection*{\ff \T{debug.gethook ()}}\DefLIB{debug.gethook} | ||
| 4195 | |||
| 4196 | Returns the current hook settings, as three values: | ||
| 4197 | the current hook function, the current hook mask, | ||
| 4198 | and the current hook count (as set by the \verb|debug.sethook| function). | ||
| 4199 | |||
| 4200 | |||
| 4201 | \C{-------------------------------------------------------------------------} | ||
| 4202 | \section{\Index{Lua Stand-alone}} \label{lua-sa} | ||
| 4203 | |||
| 4204 | Although Lua has been designed as an extension language, | ||
| 4205 | to be embedded in a host C\Nb{}program, | ||
| 4206 | it is also frequently used as a stand-alone language. | ||
| 4207 | An interpreter for Lua as a stand-alone language, | ||
| 4208 | called simply \verb|lua|, | ||
| 4209 | is provided with the standard distribution. | ||
| 4210 | The stand-alone interpreter includes | ||
| 4211 | all standard libraries plus the reflexive debug interface. | ||
| 4212 | Its usage is: | ||
| 4213 | \begin{verbatim} | ||
| 4214 | lua [options] [script [args]] | ||
| 4215 | \end{verbatim} | ||
| 4216 | The options are: | ||
| 4217 | \begin{description}\leftskip=20pt | ||
| 4218 | \item[\T{-} ] executes \verb|stdin| as a file; | ||
| 4219 | \item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; | ||
| 4220 | \item[\T{-l} \rm\emph{file}] \Q{requires} \emph{file}; | ||
| 4221 | \item[\T{-i}] enters interactive mode after running \emph{script}; | ||
| 4222 | \item[\T{-v}] prints version information; | ||
| 4223 | \item[\T{--}] stop handling options. | ||
| 4224 | \end{description} | ||
| 4225 | After handling its options, \verb|lua| runs the given \emph{script}, | ||
| 4226 | passing to it the given \emph{args}. | ||
| 4227 | When called without arguments, | ||
| 4228 | \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, | ||
| 4229 | and as \verb|lua -| otherwise. | ||
| 4230 | |||
| 4231 | Before running any argument, | ||
| 4232 | the interpreter checks for an environment variable \IndexVerb{LUA_INIT}. | ||
| 4233 | If its format is \At{}\emph{filename}, | ||
| 4234 | then lua executes the file. | ||
| 4235 | Otherwise, lua executes the string itself. | ||
| 4236 | |||
| 4237 | All options are handled in order, except \verb|-i|. | ||
| 4238 | For instance, an invocation like | ||
| 4239 | \begin{verbatim} | ||
| 4240 | $ lua -e'a=1' -e 'print(a)' script.lua | ||
| 4241 | \end{verbatim} | ||
| 4242 | will first set \verb|a| to 1, then print \verb|a|, | ||
| 4243 | and finally run the file \verb|script.lua|. | ||
| 4244 | (Here, \verb|$| is the shell prompt. Your prompt may be different.) | ||
| 4245 | |||
| 4246 | Before starting to run the script, | ||
| 4247 | \verb|lua| collects all arguments in the command line | ||
| 4248 | in a global table called \verb|arg|. | ||
| 4249 | The script name is stored in index 0, | ||
| 4250 | the first argument after the script name goes to index 1, | ||
| 4251 | and so on. | ||
| 4252 | The field \verb|n| gets the number of arguments after the script name. | ||
| 4253 | Any arguments before the script name | ||
| 4254 | (that is, the interpreter name plus the options) | ||
| 4255 | go to negative indices. | ||
| 4256 | For instance, in the call | ||
| 4257 | \begin{verbatim} | ||
| 4258 | $ lua -la.lua b.lua t1 t2 | ||
| 4259 | \end{verbatim} | ||
| 4260 | the interpreter first runs the file \T{a.lua}, | ||
| 4261 | then creates a table | ||
| 4262 | \begin{verbatim} | ||
| 4263 | arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua", | ||
| 4264 | [1] = "t1", [2] = "t2"; n = 2 } | ||
| 4265 | \end{verbatim} | ||
| 4266 | and finally runs the file \T{b.lua}. | ||
| 4267 | |||
| 4268 | In interactive mode, | ||
| 4269 | if you write an incomplete statement, | ||
| 4270 | the interpreter waits for its completion. | ||
| 4271 | |||
| 4272 | If the global variable \IndexVerb{_PROMPT} is defined as a string, | ||
| 4273 | then its value is used as the prompt. | ||
| 4274 | Therefore, the prompt can be changed directly on the command line: | ||
| 4275 | \begin{verbatim} | ||
| 4276 | $ lua -e"_PROMPT='myprompt> '" -i | ||
| 4277 | \end{verbatim} | ||
| 4278 | (the first pair of quotes is for the shell, | ||
| 4279 | the second is for Lua), | ||
| 4280 | or in any Lua programs by assigning to \verb|_PROMPT|. | ||
| 4281 | Note the use of \verb|-i| to enter interactive mode; otherwise, | ||
| 4282 | the program would end just after the assignment to \verb|_PROMPT|. | ||
| 4283 | |||
| 4284 | In Unix systems, Lua scripts can be made into executable programs | ||
| 4285 | by using \verb|chmod +x| and the\Nb{}\verb|#!| form, | ||
| 4286 | as in | ||
| 4287 | \begin{verbatim} | ||
| 4288 | #!/usr/local/bin/lua | ||
| 4289 | \end{verbatim} | ||
| 4290 | (Of course, | ||
| 4291 | the location of the Lua interpreter may be different in your machine. | ||
| 4292 | If \verb|lua| is in your \verb|PATH|, | ||
| 4293 | then | ||
| 4294 | \begin{verbatim} | ||
| 4295 | #!/usr/bin/env lua | ||
| 4296 | \end{verbatim} | ||
| 4297 | is a more portable solution.) | ||
| 4298 | |||
| 4299 | \C{-------------------------------------------------------------------------} | ||
| 4300 | \section*{Acknowledgments} | ||
| 4301 | |||
| 4302 | The Lua team is grateful to \tecgraf{} for its continued support to Lua. | ||
| 4303 | We thank everyone at \tecgraf{}, | ||
| 4304 | specially the head of the group, Marcelo Gattass. | ||
| 4305 | At the risk of omitting several names, | ||
| 4306 | we also thank the following individuals for supporting, | ||
| 4307 | contributing to, and spreading the word about Lua: | ||
| 4308 | Alan Watson. | ||
| 4309 | André Clinio, | ||
| 4310 | André Costa, | ||
| 4311 | Antonio Scuri, | ||
| 4312 | Bret Mogilefsky, | ||
| 4313 | Cameron Laird, | ||
| 4314 | Carlos Cassino, | ||
| 4315 | Carlos Henrique Levy, | ||
| 4316 | Claudio Terra, | ||
| 4317 | David Jeske, | ||
| 4318 | Edgar Toernig, | ||
| 4319 | Erik Hougaard, | ||
| 4320 | Jim Mathies, | ||
| 4321 | John Belmonte, | ||
| 4322 | John Passaniti, | ||
| 4323 | John Roll, | ||
| 4324 | Jon Erickson, | ||
| 4325 | Jon Kleiser, | ||
| 4326 | Mark Ian Barlow, | ||
| 4327 | Nick Trout, | ||
| 4328 | Noemi Rodriguez, | ||
| 4329 | Norman Ramsey, | ||
| 4330 | Philippe Lhoste, | ||
| 4331 | Renata Ratton, | ||
| 4332 | Renato Borges, | ||
| 4333 | Renato Cerqueira, | ||
| 4334 | Reuben Thomas, | ||
| 4335 | Stephan Herrmann, | ||
| 4336 | Steve Dekorte, | ||
| 4337 | Thatcher Ulrich, | ||
| 4338 | Tomás Gorham, | ||
| 4339 | Vincent Penquerc'h, | ||
| 4340 | Thank you! | ||
| 4341 | |||
| 4342 | |||
| 4343 | \appendix | ||
| 4344 | |||
| 4345 | \section*{Incompatibilities with Previous Versions} | ||
| 4346 | \addcontentsline{toc}{section}{Incompatibilities with Previous Versions} | ||
| 4347 | |||
| 4348 | \subsection*{Incompatibilities with \Index{version 4.0}} | ||
| 4349 | |||
| 4350 | \subsubsection*{Changes in the Language} | ||
| 4351 | \begin{itemize} | ||
| 4352 | |||
| 4353 | \item | ||
| 4354 | Function calls written between parentheses result in exactly one value. | ||
| 4355 | |||
| 4356 | \item | ||
| 4357 | A function call as the last expression in a list constructor | ||
| 4358 | (like \verb|{a,b,f()}|) has all its return values inserted in the list. | ||
| 4359 | |||
| 4360 | \item | ||
| 4361 | The precedence of \rwd{or} is smaller than the precedence of \rwd{and}. | ||
| 4362 | |||
| 4363 | \item | ||
| 4364 | \rwd{in} is a reserved word. | ||
| 4365 | |||
| 4366 | \item | ||
| 4367 | The old construction \verb|for k,v in t|, where \verb|t| is a table, | ||
| 4368 | is deprecated (although it is still supported). | ||
| 4369 | Use \verb|for k,v in pairs(t)| instead. | ||
| 4370 | |||
| 4371 | \item | ||
| 4372 | When a literal string of the form \verb|[[...]]| starts with a newline, | ||
| 4373 | this newline is ignored. | ||
| 4374 | |||
| 4375 | \item Old pre-compiled code is obsolete, and must be re-compiled. | ||
| 4376 | |||
| 4377 | \end{itemize} | ||
| 4378 | |||
| 4379 | |||
| 4380 | \subsubsection*{Changes in the Libraries} | ||
| 4381 | \begin{itemize} | ||
| 4382 | |||
| 4383 | \item | ||
| 4384 | Most library functions now are defined inside tables. | ||
| 4385 | There is a compatibility script (\verb|compat.lua|) that | ||
| 4386 | redefine most of them as global names. | ||
| 4387 | |||
| 4388 | \item | ||
| 4389 | In the math library, angles are expressed in radians. | ||
| 4390 | With the compatibility script (\verb|compat.lua|), | ||
| 4391 | functions still work in degrees. | ||
| 4392 | |||
| 4393 | \item | ||
| 4394 | The \verb|call| function is deprecated. | ||
| 4395 | Use \verb|f(unpack(tab))| instead of \verb|call(f, tab)| | ||
| 4396 | for unprotected calls, | ||
| 4397 | or the new \verb|pcall| function for protected calls. | ||
| 4398 | |||
| 4399 | \item | ||
| 4400 | \verb|dofile| do not handle errors, but simply propagates them. | ||
| 4401 | |||
| 4402 | \item | ||
| 4403 | The \verb|read| option \verb|*w| is obsolete. | ||
| 4404 | |||
| 4405 | \item | ||
| 4406 | The \verb|format| option \verb|%n$| is obsolete. | ||
| 4407 | |||
| 4408 | \end{itemize} | ||
| 4409 | |||
| 4410 | |||
| 4411 | \subsubsection*{Changes in the API} | ||
| 4412 | \begin{itemize} | ||
| 4413 | |||
| 4414 | \item | ||
| 4415 | Userdata!! | ||
| 4416 | |||
| 4417 | \end{itemize} | ||
| 4418 | |||
| 4419 | |||
| 4420 | |||
| 4421 | \C{[===============================================================} | ||
| 4422 | \newpage | ||
| 4423 | \section*{The Complete Syntax of Lua} \label{BNF} | ||
| 4424 | \addcontentsline{toc}{section}{The Complete Syntax of Lua} | ||
| 4425 | |||
| 4426 | The notation used here is the usual extended BNF, | ||
| 4427 | in which | ||
| 4428 | \rep{\emph{a}}\Nb{}means 0 or more \emph{a}'s, and | ||
| 4429 | \opt{\emph{a}}\Nb{}means an optional \emph{a}. | ||
| 4430 | Non-terminals are shown in \emph{italics}, | ||
| 4431 | keywords are shown in {\bf bold}, | ||
| 4432 | and other terminal symbols are shown in {\tt typewriter} font, | ||
| 4433 | enclosed in single quotes. | ||
| 4434 | |||
| 4435 | |||
| 4436 | \index{grammar} | ||
| 4437 | |||
| 4438 | \begin{Produc} | ||
| 4439 | |||
| 4440 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | ||
| 4441 | |||
| 4442 | \produc{block}{chunk} | ||
| 4443 | |||
| 4444 | \produc{stat}{ | ||
| 4445 | varlist1 \ter{=} explist1 | ||
| 4446 | \OrNL functioncall | ||
| 4447 | \OrNL \rwd{do} block \rwd{end} | ||
| 4448 | \OrNL \rwd{while} exp \rwd{do} block \rwd{end} | ||
| 4449 | \OrNL \rwd{repeat} block \rwd{until} exp | ||
| 4450 | \OrNL \rwd{if} exp \rwd{then} block | ||
| 4451 | \rep{\rwd{elseif} exp \rwd{then} block} | ||
| 4452 | \opt{\rwd{else} block} \rwd{end} | ||
| 4453 | \OrNL \rwd{return} \opt{explist1} | ||
| 4454 | \OrNL \rwd{break} | ||
| 4455 | \OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp} | ||
| 4456 | \rwd{do} block \rwd{end} | ||
| 4457 | \OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 | ||
| 4458 | \rwd{do} block \rwd{end} | ||
| 4459 | \OrNL \rwd{function} funcname funcbody | ||
| 4460 | \OrNL \rwd{local} \rwd{function} \Nter{Name} funcbody | ||
| 4461 | \OrNL \rwd{local} namelist \opt{init} | ||
| 4462 | } | ||
| 4463 | |||
| 4464 | \produc{funcname}{\Nter{Name} \rep{\ter{.} \Nter{Name}} | ||
| 4465 | \opt{\ter{:} \Nter{Name}}} | ||
| 4466 | |||
| 4467 | \produc{varlist1}{var \rep{\ter{,} var}} | ||
| 4468 | |||
| 4469 | \produc{var}{ | ||
| 4470 | \Nter{Name} | ||
| 4471 | \Or prefixexp \ter{[} exp \ter{]} | ||
| 4472 | \Or prefixexp \ter{.} \Nter{Name} | ||
| 4473 | } | ||
| 4474 | |||
| 4475 | \produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}} | ||
| 4476 | |||
| 4477 | \produc{init}{\ter{=} explist1} | ||
| 4478 | |||
| 4479 | \produc{explist1}{\rep{exp \ter{,}} exp} | ||
| 4480 | |||
| 4481 | \produc{exp}{ | ||
| 4482 | \rwd{nil} | ||
| 4483 | \rwd{false} | ||
| 4484 | \rwd{true} | ||
| 4485 | \Or \Nter{Number} | ||
| 4486 | \OrNL \Nter{Literal} | ||
| 4487 | \Or function | ||
| 4488 | \Or prefixexp | ||
| 4489 | \OrNL tableconstructor | ||
| 4490 | \Or exp binop exp | ||
| 4491 | \Or unop exp | ||
| 4492 | } | ||
| 4493 | |||
| 4494 | \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}} | ||
| 4495 | |||
| 4496 | \produc{functioncall}{ | ||
| 4497 | prefixexp args | ||
| 4498 | \Or prefixexp \ter{:} \Nter{Name} args | ||
| 4499 | } | ||
| 4500 | |||
| 4501 | \produc{args}{ | ||
| 4502 | \ter{(} \opt{explist1} \ter{)} | ||
| 4503 | \Or tableconstructor | ||
| 4504 | \Or \Nter{Literal} | ||
| 4505 | } | ||
| 4506 | |||
| 4507 | \produc{function}{\rwd{function} funcbody} | ||
| 4508 | |||
| 4509 | \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}} | ||
| 4510 | |||
| 4511 | \produc{parlist1}{ | ||
| 4512 | \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}} | ||
| 4513 | \Or \ter{\ldots} | ||
| 4514 | } | ||
| 4515 | |||
| 4516 | \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}} | ||
| 4517 | \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}} | ||
| 4518 | \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp} | ||
| 4519 | \produc{fieldsep}{\ter{,} \Or \ter{;}} | ||
| 4520 | |||
| 4521 | \produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{^} \Or | ||
| 4522 | \ter{..} \OrNL \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=} | ||
| 4523 | \Or \ter{==} \Or \ter{~=} \OrNL \rwd{and} \Or \rwd{or}} | ||
| 4524 | |||
| 4525 | \produc{unop}{\ter{-} \Or \rwd{not}} | ||
| 4526 | |||
| 4527 | \end{Produc} | ||
| 4528 | |||
| 4529 | \C{]===============================================================} | ||
| 4530 | |||
| 4531 | \C{ Index} | ||
| 4532 | |||
| 4533 | \newpage | ||
| 4534 | \addcontentsline{toc}{section}{Index} | ||
| 4535 | \input{manual.id} | ||
| 4536 | |||
| 4537 | \end{document} | ||
| 4538 | %)]} | ||
| 4539 | |||
