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