AppPkg: Add the Lua interpreter and library.
[mirror_edk2.git] / AppPkg / Applications / Lua / doc / manual.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3
4 <head>
5 <title>Lua 5.2 Reference Manual</title>
6 <link rel="stylesheet" type="text/css" href="lua.css">
7 <link rel="stylesheet" type="text/css" href="manual.css">
8 <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
9 </head>
10
11 <body>
12
13 <hr>
14 <h1>
15 <a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16 Lua 5.2 Reference Manual
17 </h1>
18
19 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
20 <p>
21 <small>
22 Copyright &copy; 2011&ndash;2013 Lua.org, PUC-Rio.
23 Freely available under the terms of the
24 <a href="http://www.lua.org/license.html">Lua license</a>.
25 </small>
26 <hr>
27 <p>
28
29 <a href="contents.html#contents">contents</A>
30 &middot;
31 <a href="contents.html#index">index</A>
32
33 <!-- ====================================================================== -->
34 <p>
35
36 <!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ -->
37
38
39
40
41 <h1>1 &ndash; <a name="1">Introduction</a></h1>
42
43 <p>
44 Lua is an extension programming language designed to support
45 general procedural programming with data description
46 facilities.
47 It also offers good support for object-oriented programming,
48 functional programming, and data-driven programming.
49 Lua is intended to be used as a powerful, lightweight,
50 embeddable scripting language for any program that needs one.
51 Lua is implemented as a library, written in <em>clean C</em>,
52 the common subset of Standard&nbsp;C and C++.
53
54
55 <p>
56 Being an extension language, Lua has no notion of a "main" program:
57 it only works <em>embedded</em> in a host client,
58 called the <em>embedding program</em> or simply the <em>host</em>.
59 The host program can invoke functions to execute a piece of Lua code,
60 can write and read Lua variables,
61 and can register C&nbsp;functions to be called by Lua code.
62 Through the use of C&nbsp;functions, Lua can be augmented to cope with
63 a wide range of different domains,
64 thus creating customized programming languages sharing a syntactical framework.
65 The Lua distribution includes a sample host program called <code>lua</code>,
66 which uses the Lua library to offer a complete, standalone Lua interpreter,
67 for interactive or batch use.
68
69
70 <p>
71 Lua is free software,
72 and is provided as usual with no guarantees,
73 as stated in its license.
74 The implementation described in this manual is available
75 at Lua's official web site, <code>www.lua.org</code>.
76
77
78 <p>
79 Like any other reference manual,
80 this document is dry in places.
81 For a discussion of the decisions behind the design of Lua,
82 see the technical papers available at Lua's web site.
83 For a detailed introduction to programming in Lua,
84 see Roberto's book, <em>Programming in Lua</em>.
85
86
87
88 <h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
89
90 <p>
91 This section describes the basic concepts of the language.
92
93
94
95 <h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
96
97 <p>
98 Lua is a <em>dynamically typed language</em>.
99 This means that
100 variables do not have types; only values do.
101 There are no type definitions in the language.
102 All values carry their own type.
103
104
105 <p>
106 All values in Lua are <em>first-class values</em>.
107 This means that all values can be stored in variables,
108 passed as arguments to other functions, and returned as results.
109
110
111 <p>
112 There are eight basic types in Lua:
113 <em>nil</em>, <em>boolean</em>, <em>number</em>,
114 <em>string</em>, <em>function</em>, <em>userdata</em>,
115 <em>thread</em>, and <em>table</em>.
116 <em>Nil</em> is the type of the value <b>nil</b>,
117 whose main property is to be different from any other value;
118 it usually represents the absence of a useful value.
119 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
120 Both <b>nil</b> and <b>false</b> make a condition false;
121 any other value makes it true.
122 <em>Number</em> represents real (double-precision floating-point) numbers.
123 Operations on numbers follow the same rules of
124 the underlying C&nbsp;implementation,
125 which, in turn, usually follows the IEEE 754 standard.
126 (It is easy to build Lua interpreters that use other
127 internal representations for numbers,
128 such as single-precision floats or long integers;
129 see file <code>luaconf.h</code>.)
130 <em>String</em> represents immutable sequences of bytes.
131
132 Lua is 8-bit clean:
133 strings can contain any 8-bit value,
134 including embedded zeros ('<code>\0</code>').
135
136
137 <p>
138 Lua can call (and manipulate) functions written in Lua and
139 functions written in C
140 (see <a href="#3.4.9">&sect;3.4.9</a>).
141
142
143 <p>
144 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
145 be stored in Lua variables.
146 A userdata value is a pointer to a block of raw memory.
147 There are two kinds of userdata:
148 full userdata, where the block of memory is managed by Lua,
149 and light userdata, where the block of memory is managed by the host.
150 Userdata has no predefined operations in Lua,
151 except assignment and identity test.
152 By using <em>metatables</em>,
153 the programmer can define operations for full userdata values
154 (see <a href="#2.4">&sect;2.4</a>).
155 Userdata values cannot be created or modified in Lua,
156 only through the C&nbsp;API.
157 This guarantees the integrity of data owned by the host program.
158
159
160 <p>
161 The type <em>thread</em> represents independent threads of execution
162 and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
163 Do not confuse Lua threads with operating-system threads.
164 Lua supports coroutines on all systems,
165 even those that do not support threads.
166
167
168 <p>
169 The type <em>table</em> implements associative arrays,
170 that is, arrays that can be indexed not only with numbers,
171 but with any Lua value except <b>nil</b> and NaN
172 (<em>Not a Number</em>, a special numeric value used to represent
173 undefined or unrepresentable results, such as <code>0/0</code>).
174 Tables can be <em>heterogeneous</em>;
175 that is, they can contain values of all types (except <b>nil</b>).
176 Any key with value <b>nil</b> is not considered part of the table.
177 Conversely, any key that is not part of a table has
178 an associated value <b>nil</b>.
179
180
181 <p>
182 Tables are the sole data structuring mechanism in Lua;
183 they can be used to represent ordinary arrays, sequences,
184 symbol tables, sets, records, graphs, trees, etc.
185 To represent records, Lua uses the field name as an index.
186 The language supports this representation by
187 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
188 There are several convenient ways to create tables in Lua
189 (see <a href="#3.4.8">&sect;3.4.8</a>).
190
191
192 <p>
193 We use the term <em>sequence</em> to denote a table where
194 the set of all positive numeric keys is equal to <em>{1..n}</em>
195 for some integer <em>n</em>,
196 which is called the length of the sequence (see <a href="#3.4.6">&sect;3.4.6</a>).
197
198
199 <p>
200 Like indices,
201 the values of table fields can be of any type.
202 In particular,
203 because functions are first-class values,
204 table fields can contain functions.
205 Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">&sect;3.4.10</a>).
206
207
208 <p>
209 The indexing of tables follows
210 the definition of raw equality in the language.
211 The expressions <code>a[i]</code> and <code>a[j]</code>
212 denote the same table element
213 if and only if <code>i</code> and <code>j</code> are raw equal
214 (that is, equal without metamethods).
215
216
217 <p>
218 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
219 variables do not actually <em>contain</em> these values,
220 only <em>references</em> to them.
221 Assignment, parameter passing, and function returns
222 always manipulate references to such values;
223 these operations do not imply any kind of copy.
224
225
226 <p>
227 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
228 of a given value (see <a href="#6.1">&sect;6.1</a>).
229
230
231
232
233
234 <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
235
236 <p>
237 As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
238 any reference to a global name <code>var</code> is syntactically translated
239 to <code>_ENV.var</code>.
240 Moreover, every chunk is compiled in the scope of
241 an external local variable called <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
242 so <code>_ENV</code> itself is never a global name in a chunk.
243
244
245 <p>
246 Despite the existence of this external <code>_ENV</code> variable and
247 the translation of global names,
248 <code>_ENV</code> is a completely regular name.
249 In particular,
250 you can define new variables and parameters with that name.
251 Each reference to a global name uses the <code>_ENV</code> that is
252 visible at that point in the program,
253 following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
254
255
256 <p>
257 Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
258
259
260 <p>
261 Lua keeps a distinguished environment called the <em>global environment</em>.
262 This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
263 In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
264
265
266 <p>
267 When Lua compiles a chunk,
268 it initializes the value of its <code>_ENV</code> upvalue
269 with the global environment (see <a href="#pdf-load"><code>load</code></a>).
270 Therefore, by default,
271 global variables in Lua code refer to entries in the global environment.
272 Moreover, all standard libraries are loaded in the global environment
273 and several functions there operate on that environment.
274 You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
275 to load a chunk with a different environment.
276 (In C, you have to load the chunk and then change the value
277 of its first upvalue.)
278
279
280 <p>
281 If you change the global environment in the registry
282 (through C code or the debug library),
283 all chunks loaded after the change will get the new environment.
284 Previously loaded chunks are not affected, however,
285 as each has its own reference to the environment in its <code>_ENV</code> variable.
286 Moreover, the variable <a href="#pdf-_G"><code>_G</code></a>
287 (which is stored in the original global environment)
288 is never updated by Lua.
289
290
291
292
293
294 <h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
295
296 <p>
297 Because Lua is an embedded extension language,
298 all Lua actions start from C&nbsp;code in the host program
299 calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
300 Whenever an error occurs during
301 the compilation or execution of a Lua chunk,
302 control returns to the host,
303 which can take appropriate measures
304 (such as printing an error message).
305
306
307 <p>
308 Lua code can explicitly generate an error by calling the
309 <a href="#pdf-error"><code>error</code></a> function.
310 If you need to catch errors in Lua,
311 you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
312 to call a given function in <em>protected mode</em>.
313
314
315 <p>
316 Whenever there is an error,
317 an <em>error object</em> (also called an <em>error message</em>)
318 is propagated with information about the error.
319 Lua itself only generates errors where the error object is a string,
320 but programs may generate errors with
321 any value for the error object.
322
323
324 <p>
325 When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
326 you may give a <em>message handler</em>
327 to be called in case of errors.
328 This function is called with the original error message
329 and returns a new error message.
330 It is called before the error unwinds the stack,
331 so that it can gather more information about the error,
332 for instance by inspecting the stack and creating a stack traceback.
333 This message handler is still protected by the protected call;
334 so, an error inside the message handler
335 will call the message handler again.
336 If this loop goes on, Lua breaks it and returns an appropriate message.
337
338
339
340
341
342 <h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
343
344 <p>
345 Every value in Lua can have a <em>metatable</em>.
346 This <em>metatable</em> is an ordinary Lua table
347 that defines the behavior of the original value
348 under certain special operations.
349 You can change several aspects of the behavior
350 of operations over a value by setting specific fields in its metatable.
351 For instance, when a non-numeric value is the operand of an addition,
352 Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
353 If it finds one,
354 Lua calls this function to perform the addition.
355
356
357 <p>
358 The keys in a metatable are derived from the <em>event</em> names;
359 the corresponding values are called <em>metamethods</em>.
360 In the previous example, the event is <code>"add"</code>
361 and the metamethod is the function that performs the addition.
362
363
364 <p>
365 You can query the metatable of any value
366 using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
367
368
369 <p>
370 You can replace the metatable of tables
371 using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
372 You cannot change the metatable of other types from Lua
373 (except by using the debug library);
374 you must use the C&nbsp;API for that.
375
376
377 <p>
378 Tables and full userdata have individual metatables
379 (although multiple tables and userdata can share their metatables).
380 Values of all other types share one single metatable per type;
381 that is, there is one single metatable for all numbers,
382 one for all strings, etc.
383 By default, a value has no metatable,
384 but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
385
386
387 <p>
388 A metatable controls how an object behaves in arithmetic operations,
389 order comparisons, concatenation, length operation, and indexing.
390 A metatable also can define a function to be called
391 when a userdata or a table is garbage collected.
392 When Lua performs one of these operations over a value,
393 it checks whether this value has a metatable with the corresponding event.
394 If so, the value associated with that key (the metamethod)
395 controls how Lua will perform the operation.
396
397
398 <p>
399 Metatables control the operations listed next.
400 Each operation is identified by its corresponding name.
401 The key for each operation is a string with its name prefixed by
402 two underscores, '<code>__</code>';
403 for instance, the key for operation "add" is the
404 string "<code>__add</code>".
405
406
407 <p>
408 The semantics of these operations is better explained by a Lua function
409 describing how the interpreter executes the operation.
410 The code shown here in Lua is only illustrative;
411 the real behavior is hard coded in the interpreter
412 and it is much more efficient than this simulation.
413 All functions used in these descriptions
414 (<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
415 are described in <a href="#6.1">&sect;6.1</a>.
416 In particular, to retrieve the metamethod of a given object,
417 we use the expression
418
419 <pre>
420 metatable(obj)[event]
421 </pre><p>
422 This should be read as
423
424 <pre>
425 rawget(getmetatable(obj) or {}, event)
426 </pre><p>
427 This means that the access to a metamethod does not invoke other metamethods,
428 and access to objects with no metatables does not fail
429 (it simply results in <b>nil</b>).
430
431
432 <p>
433 For the unary <code>-</code> and <code>#</code> operators,
434 the metamethod is called with a dummy second argument.
435 This extra argument is only to simplify Lua's internals;
436 it may be removed in future versions and therefore it is not present
437 in the following code.
438 (For most uses this extra argument is irrelevant.)
439
440
441
442 <ul>
443
444 <li><b>"add": </b>
445 the <code>+</code> operation.
446
447
448
449 <p>
450 The function <code>getbinhandler</code> below defines how Lua chooses a handler
451 for a binary operation.
452 First, Lua tries the first operand.
453 If its type does not define a handler for the operation,
454 then Lua tries the second operand.
455
456 <pre>
457 function getbinhandler (op1, op2, event)
458 return metatable(op1)[event] or metatable(op2)[event]
459 end
460 </pre><p>
461 By using this function,
462 the behavior of the <code>op1 + op2</code> is
463
464 <pre>
465 function add_event (op1, op2)
466 local o1, o2 = tonumber(op1), tonumber(op2)
467 if o1 and o2 then -- both operands are numeric?
468 return o1 + o2 -- '+' here is the primitive 'add'
469 else -- at least one of the operands is not numeric
470 local h = getbinhandler(op1, op2, "__add")
471 if h then
472 -- call the handler with both operands
473 return (h(op1, op2))
474 else -- no handler available: default behavior
475 error(&middot;&middot;&middot;)
476 end
477 end
478 end
479 </pre><p>
480 </li>
481
482 <li><b>"sub": </b>
483 the <code>-</code> operation.
484
485 Behavior similar to the "add" operation.
486 </li>
487
488 <li><b>"mul": </b>
489 the <code>*</code> operation.
490
491 Behavior similar to the "add" operation.
492 </li>
493
494 <li><b>"div": </b>
495 the <code>/</code> operation.
496
497 Behavior similar to the "add" operation.
498 </li>
499
500 <li><b>"mod": </b>
501 the <code>%</code> operation.
502
503 Behavior similar to the "add" operation,
504 with the operation
505 <code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
506 </li>
507
508 <li><b>"pow": </b>
509 the <code>^</code> (exponentiation) operation.
510
511 Behavior similar to the "add" operation,
512 with the function <code>pow</code> (from the C&nbsp;math library)
513 as the primitive operation.
514 </li>
515
516 <li><b>"unm": </b>
517 the unary <code>-</code> operation.
518
519
520 <pre>
521 function unm_event (op)
522 local o = tonumber(op)
523 if o then -- operand is numeric?
524 return -o -- '-' here is the primitive 'unm'
525 else -- the operand is not numeric.
526 -- Try to get a handler from the operand
527 local h = metatable(op).__unm
528 if h then
529 -- call the handler with the operand
530 return (h(op))
531 else -- no handler available: default behavior
532 error(&middot;&middot;&middot;)
533 end
534 end
535 end
536 </pre><p>
537 </li>
538
539 <li><b>"concat": </b>
540 the <code>..</code> (concatenation) operation.
541
542
543 <pre>
544 function concat_event (op1, op2)
545 if (type(op1) == "string" or type(op1) == "number") and
546 (type(op2) == "string" or type(op2) == "number") then
547 return op1 .. op2 -- primitive string concatenation
548 else
549 local h = getbinhandler(op1, op2, "__concat")
550 if h then
551 return (h(op1, op2))
552 else
553 error(&middot;&middot;&middot;)
554 end
555 end
556 end
557 </pre><p>
558 </li>
559
560 <li><b>"len": </b>
561 the <code>#</code> operation.
562
563
564 <pre>
565 function len_event (op)
566 if type(op) == "string" then
567 return strlen(op) -- primitive string length
568 else
569 local h = metatable(op).__len
570 if h then
571 return (h(op)) -- call handler with the operand
572 elseif type(op) == "table" then
573 return #op -- primitive table length
574 else -- no handler available: error
575 error(&middot;&middot;&middot;)
576 end
577 end
578 end
579 </pre><p>
580 See <a href="#3.4.6">&sect;3.4.6</a> for a description of the length of a table.
581 </li>
582
583 <li><b>"eq": </b>
584 the <code>==</code> operation.
585
586 The function <code>getequalhandler</code> defines how Lua chooses a metamethod
587 for equality.
588 A metamethod is selected only when both values
589 being compared have the same type
590 and the same metamethod for the selected operation,
591 and the values are either tables or full userdata.
592
593 <pre>
594 function getequalhandler (op1, op2)
595 if type(op1) ~= type(op2) or
596 (type(op1) ~= "table" and type(op1) ~= "userdata") then
597 return nil -- different values
598 end
599 local mm1 = metatable(op1).__eq
600 local mm2 = metatable(op2).__eq
601 if mm1 == mm2 then return mm1 else return nil end
602 end
603 </pre><p>
604 The "eq" event is defined as follows:
605
606 <pre>
607 function eq_event (op1, op2)
608 if op1 == op2 then -- primitive equal?
609 return true -- values are equal
610 end
611 -- try metamethod
612 local h = getequalhandler(op1, op2)
613 if h then
614 return not not h(op1, op2)
615 else
616 return false
617 end
618 end
619 </pre><p>
620 Note that the result is always a boolean.
621 </li>
622
623 <li><b>"lt": </b>
624 the <code>&lt;</code> operation.
625
626
627 <pre>
628 function lt_event (op1, op2)
629 if type(op1) == "number" and type(op2) == "number" then
630 return op1 &lt; op2 -- numeric comparison
631 elseif type(op1) == "string" and type(op2) == "string" then
632 return op1 &lt; op2 -- lexicographic comparison
633 else
634 local h = getbinhandler(op1, op2, "__lt")
635 if h then
636 return not not h(op1, op2)
637 else
638 error(&middot;&middot;&middot;)
639 end
640 end
641 end
642 </pre><p>
643 Note that the result is always a boolean.
644 </li>
645
646 <li><b>"le": </b>
647 the <code>&lt;=</code> operation.
648
649
650 <pre>
651 function le_event (op1, op2)
652 if type(op1) == "number" and type(op2) == "number" then
653 return op1 &lt;= op2 -- numeric comparison
654 elseif type(op1) == "string" and type(op2) == "string" then
655 return op1 &lt;= op2 -- lexicographic comparison
656 else
657 local h = getbinhandler(op1, op2, "__le")
658 if h then
659 return not not h(op1, op2)
660 else
661 h = getbinhandler(op1, op2, "__lt")
662 if h then
663 return not h(op2, op1)
664 else
665 error(&middot;&middot;&middot;)
666 end
667 end
668 end
669 end
670 </pre><p>
671 Note that, in the absence of a "le" metamethod,
672 Lua tries the "lt", assuming that <code>a &lt;= b</code> is
673 equivalent to <code>not (b &lt; a)</code>.
674
675
676 <p>
677 As with the other comparison operators,
678 the result is always a boolean.
679 </li>
680
681 <li><b>"index": </b>
682 The indexing access <code>table[key]</code>.
683 Note that the metamethod is tried only
684 when <code>key</code> is not present in <code>table</code>.
685 (When <code>table</code> is not a table,
686 no key is ever present,
687 so the metamethod is always tried.)
688
689
690 <pre>
691 function gettable_event (table, key)
692 local h
693 if type(table) == "table" then
694 local v = rawget(table, key)
695 -- if key is present, return raw value
696 if v ~= nil then return v end
697 h = metatable(table).__index
698 if h == nil then return nil end
699 else
700 h = metatable(table).__index
701 if h == nil then
702 error(&middot;&middot;&middot;)
703 end
704 end
705 if type(h) == "function" then
706 return (h(table, key)) -- call the handler
707 else return h[key] -- or repeat operation on it
708 end
709 end
710 </pre><p>
711 </li>
712
713 <li><b>"newindex": </b>
714 The indexing assignment <code>table[key] = value</code>.
715 Note that the metamethod is tried only
716 when <code>key</code> is not present in <code>table</code>.
717
718
719 <pre>
720 function settable_event (table, key, value)
721 local h
722 if type(table) == "table" then
723 local v = rawget(table, key)
724 -- if key is present, do raw assignment
725 if v ~= nil then rawset(table, key, value); return end
726 h = metatable(table).__newindex
727 if h == nil then rawset(table, key, value); return end
728 else
729 h = metatable(table).__newindex
730 if h == nil then
731 error(&middot;&middot;&middot;)
732 end
733 end
734 if type(h) == "function" then
735 h(table, key,value) -- call the handler
736 else h[key] = value -- or repeat operation on it
737 end
738 end
739 </pre><p>
740 </li>
741
742 <li><b>"call": </b>
743 called when Lua calls a value.
744
745
746 <pre>
747 function function_event (func, ...)
748 if type(func) == "function" then
749 return func(...) -- primitive call
750 else
751 local h = metatable(func).__call
752 if h then
753 return h(func, ...)
754 else
755 error(&middot;&middot;&middot;)
756 end
757 end
758 end
759 </pre><p>
760 </li>
761
762 </ul>
763
764
765
766
767 <h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
768
769 <p>
770 Lua performs automatic memory management.
771 This means that
772 you have to worry neither about allocating memory for new objects
773 nor about freeing it when the objects are no longer needed.
774 Lua manages memory automatically by running
775 a <em>garbage collector</em> to collect all <em>dead objects</em>
776 (that is, objects that are no longer accessible from Lua).
777 All memory used by Lua is subject to automatic management:
778 strings, tables, userdata, functions, threads, internal structures, etc.
779
780
781 <p>
782 Lua implements an incremental mark-and-sweep collector.
783 It uses two numbers to control its garbage-collection cycles:
784 the <em>garbage-collector pause</em> and
785 the <em>garbage-collector step multiplier</em>.
786 Both use percentage points as units
787 (e.g., a value of 100 means an internal value of 1).
788
789
790 <p>
791 The garbage-collector pause
792 controls how long the collector waits before starting a new cycle.
793 Larger values make the collector less aggressive.
794 Values smaller than 100 mean the collector will not wait to
795 start a new cycle.
796 A value of 200 means that the collector waits for the total memory in use
797 to double before starting a new cycle.
798
799
800 <p>
801 The garbage-collector step multiplier
802 controls the relative speed of the collector relative to
803 memory allocation.
804 Larger values make the collector more aggressive but also increase
805 the size of each incremental step.
806 Values smaller than 100 make the collector too slow and
807 can result in the collector never finishing a cycle.
808 The default is 200,
809 which means that the collector runs at "twice"
810 the speed of memory allocation.
811
812
813 <p>
814 If you set the step multiplier to a very large number
815 (larger than 10% of the maximum number of
816 bytes that the program may use),
817 the collector behaves like a stop-the-world collector.
818 If you then set the pause to 200,
819 the collector behaves as in old Lua versions,
820 doing a complete collection every time Lua doubles its
821 memory usage.
822
823
824 <p>
825 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
826 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
827 You can also use these functions to control
828 the collector directly (e.g., stop and restart it).
829
830
831 <p>
832 As an experimental feature in Lua 5.2,
833 you can change the collector's operation mode
834 from incremental to <em>generational</em>.
835 A <em>generational collector</em> assumes that most objects die young,
836 and therefore it traverses only young (recently created) objects.
837 This behavior can reduce the time used by the collector,
838 but also increases memory usage (as old dead objects may accumulate).
839 To mitigate this second problem,
840 from time to time the generational collector performs a full collection.
841 Remember that this is an experimental feature;
842 you are welcome to try it,
843 but check your gains.
844
845
846
847 <h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
848
849 <p>
850 You can set garbage-collector metamethods for tables
851 and, using the C&nbsp;API,
852 for full userdata (see <a href="#2.4">&sect;2.4</a>).
853 These metamethods are also called <em>finalizers</em>.
854 Finalizers allow you to coordinate Lua's garbage collection
855 with external resource management
856 (such as closing files, network or database connections,
857 or freeing your own memory).
858
859
860 <p>
861 For an object (table or userdata) to be finalized when collected,
862 you must <em>mark</em> it for finalization.
863
864 You mark an object for finalization when you set its metatable
865 and the metatable has a field indexed by the string "<code>__gc</code>".
866 Note that if you set a metatable without a <code>__gc</code> field
867 and later create that field in the metatable,
868 the object will not be marked for finalization.
869 However, after an object is marked,
870 you can freely change the <code>__gc</code> field of its metatable.
871
872
873 <p>
874 When a marked object becomes garbage,
875 it is not collected immediately by the garbage collector.
876 Instead, Lua puts it in a list.
877 After the collection,
878 Lua does the equivalent of the following function
879 for each object in that list:
880
881 <pre>
882 function gc_event (obj)
883 local h = metatable(obj).__gc
884 if type(h) == "function" then
885 h(obj)
886 end
887 end
888 </pre>
889
890 <p>
891 At the end of each garbage-collection cycle,
892 the finalizers for objects are called in
893 the reverse order that they were marked for collection,
894 among those collected in that cycle;
895 that is, the first finalizer to be called is the one associated
896 with the object marked last in the program.
897 The execution of each finalizer may occur at any point during
898 the execution of the regular code.
899
900
901 <p>
902 Because the object being collected must still be used by the finalizer,
903 it (and other objects accessible only through it)
904 must be <em>resurrected</em> by Lua.
905 Usually, this resurrection is transient,
906 and the object memory is freed in the next garbage-collection cycle.
907 However, if the finalizer stores the object in some global place
908 (e.g., a global variable),
909 then there is a permanent resurrection.
910 In any case,
911 the object memory is freed only when it becomes completely inaccessible;
912 its finalizer will never be called twice.
913
914
915 <p>
916 When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
917 Lua calls the finalizers of all objects marked for finalization,
918 following the reverse order that they were marked.
919 If any finalizer marks new objects for collection during that phase,
920 these new objects will not be finalized.
921
922
923
924
925
926 <h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3>
927
928 <p>
929 A <em>weak table</em> is a table whose elements are
930 <em>weak references</em>.
931 A weak reference is ignored by the garbage collector.
932 In other words,
933 if the only references to an object are weak references,
934 then the garbage collector will collect that object.
935
936
937 <p>
938 A weak table can have weak keys, weak values, or both.
939 A table with weak keys allows the collection of its keys,
940 but prevents the collection of its values.
941 A table with both weak keys and weak values allows the collection of
942 both keys and values.
943 In any case, if either the key or the value is collected,
944 the whole pair is removed from the table.
945 The weakness of a table is controlled by the
946 <code>__mode</code> field of its metatable.
947 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
948 the keys in the table are weak.
949 If <code>__mode</code> contains '<code>v</code>',
950 the values in the table are weak.
951
952
953 <p>
954 A table with weak keys and strong values
955 is also called an <em>ephemeron table</em>.
956 In an ephemeron table,
957 a value is considered reachable only if its key is reachable.
958 In particular,
959 if the only reference to a key comes through its value,
960 the pair is removed.
961
962
963 <p>
964 Any change in the weakness of a table may take effect only
965 at the next collect cycle.
966 In particular, if you change the weakness to a stronger mode,
967 Lua may still collect some items from that table
968 before the change takes effect.
969
970
971 <p>
972 Only objects that have an explicit construction
973 are removed from weak tables.
974 Values, such as numbers and light C functions,
975 are not subject to garbage collection,
976 and therefore are not removed from weak tables
977 (unless its associated value is collected).
978 Although strings are subject to garbage collection,
979 they do not have an explicit construction,
980 and therefore are not removed from weak tables.
981
982
983 <p>
984 Resurrected objects
985 (that is, objects being finalized
986 and objects accessible only through objects being finalized)
987 have a special behavior in weak tables.
988 They are removed from weak values before running their finalizers,
989 but are removed from weak keys only in the next collection
990 after running their finalizers, when such objects are actually freed.
991 This behavior allows the finalizer to access properties
992 associated with the object through weak tables.
993
994
995 <p>
996 If a weak table is among the resurrected objects in a collection cycle,
997 it may not be properly cleared until the next cycle.
998
999
1000
1001
1002
1003
1004
1005 <h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1006
1007 <p>
1008 Lua supports coroutines,
1009 also called <em>collaborative multithreading</em>.
1010 A coroutine in Lua represents an independent thread of execution.
1011 Unlike threads in multithread systems, however,
1012 a coroutine only suspends its execution by explicitly calling
1013 a yield function.
1014
1015
1016 <p>
1017 You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1018 Its sole argument is a function
1019 that is the main function of the coroutine.
1020 The <code>create</code> function only creates a new coroutine and
1021 returns a handle to it (an object of type <em>thread</em>);
1022 it does not start the coroutine.
1023
1024
1025 <p>
1026 You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1027 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1028 passing as its first argument
1029 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1030 the coroutine starts its execution,
1031 at the first line of its main function.
1032 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
1033 to the coroutine main function.
1034 After the coroutine starts running,
1035 it runs until it terminates or <em>yields</em>.
1036
1037
1038 <p>
1039 A coroutine can terminate its execution in two ways:
1040 normally, when its main function returns
1041 (explicitly or implicitly, after the last instruction);
1042 and abnormally, if there is an unprotected error.
1043 In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1044 plus any values returned by the coroutine main function.
1045 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1046 plus an error message.
1047
1048
1049 <p>
1050 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1051 When a coroutine yields,
1052 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1053 even if the yield happens inside nested function calls
1054 (that is, not in the main function,
1055 but in a function directly or indirectly called by the main function).
1056 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1057 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1058 The next time you resume the same coroutine,
1059 it continues its execution from the point where it yielded,
1060 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1061 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1062
1063
1064 <p>
1065 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1066 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1067 but instead of returning the coroutine itself,
1068 it returns a function that, when called, resumes the coroutine.
1069 Any arguments passed to this function
1070 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1071 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1072 except the first one (the boolean error code).
1073 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1074 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
1075 any error is propagated to the caller.
1076
1077
1078 <p>
1079 As an example of how coroutines work,
1080 consider the following code:
1081
1082 <pre>
1083 function foo (a)
1084 print("foo", a)
1085 return coroutine.yield(2*a)
1086 end
1087
1088 co = coroutine.create(function (a,b)
1089 print("co-body", a, b)
1090 local r = foo(a+1)
1091 print("co-body", r)
1092 local r, s = coroutine.yield(a+b, a-b)
1093 print("co-body", r, s)
1094 return b, "end"
1095 end)
1096
1097 print("main", coroutine.resume(co, 1, 10))
1098 print("main", coroutine.resume(co, "r"))
1099 print("main", coroutine.resume(co, "x", "y"))
1100 print("main", coroutine.resume(co, "x", "y"))
1101 </pre><p>
1102 When you run it, it produces the following output:
1103
1104 <pre>
1105 co-body 1 10
1106 foo 2
1107 main true 4
1108 co-body r
1109 main true 11 -9
1110 co-body x y
1111 main true 10 end
1112 main false cannot resume dead coroutine
1113 </pre>
1114
1115 <p>
1116 You can also create and manipulate coroutines through the C API:
1117 see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1118 and <a href="#lua_yield"><code>lua_yield</code></a>.
1119
1120
1121
1122
1123
1124 <h1>3 &ndash; <a name="3">The Language</a></h1>
1125
1126 <p>
1127 This section describes the lexis, the syntax, and the semantics of Lua.
1128 In other words,
1129 this section describes
1130 which tokens are valid,
1131 how they can be combined,
1132 and what their combinations mean.
1133
1134
1135 <p>
1136 Language constructs will be explained using the usual extended BNF notation,
1137 in which
1138 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1139 [<em>a</em>]&nbsp;means an optional <em>a</em>.
1140 Non-terminals are shown like non-terminal,
1141 keywords are shown like <b>kword</b>,
1142 and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1143 The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1144 at the end of this manual.
1145
1146
1147
1148 <h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1149
1150 <p>
1151 Lua is a free-form language.
1152 It ignores spaces (including new lines) and comments
1153 between lexical elements (tokens),
1154 except as delimiters between names and keywords.
1155
1156
1157 <p>
1158 <em>Names</em>
1159 (also called <em>identifiers</em>)
1160 in Lua can be any string of letters,
1161 digits, and underscores,
1162 not beginning with a digit.
1163 Identifiers are used to name variables, table fields, and labels.
1164
1165
1166 <p>
1167 The following <em>keywords</em> are reserved
1168 and cannot be used as names:
1169
1170
1171 <pre>
1172 and break do else elseif end
1173 false for function goto if in
1174 local nil not or repeat return
1175 then true until while
1176 </pre>
1177
1178 <p>
1179 Lua is a case-sensitive language:
1180 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1181 are two different, valid names.
1182 As a convention, names starting with an underscore followed by
1183 uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
1184 are reserved for variables used by Lua.
1185
1186
1187 <p>
1188 The following strings denote other tokens:
1189
1190 <pre>
1191 + - * / % ^ #
1192 == ~= &lt;= &gt;= &lt; &gt; =
1193 ( ) { } [ ] ::
1194 ; : , . .. ...
1195 </pre>
1196
1197 <p>
1198 <em>Literal strings</em>
1199 can be delimited by matching single or double quotes,
1200 and can contain the following C-like escape sequences:
1201 '<code>\a</code>' (bell),
1202 '<code>\b</code>' (backspace),
1203 '<code>\f</code>' (form feed),
1204 '<code>\n</code>' (newline),
1205 '<code>\r</code>' (carriage return),
1206 '<code>\t</code>' (horizontal tab),
1207 '<code>\v</code>' (vertical tab),
1208 '<code>\\</code>' (backslash),
1209 '<code>\"</code>' (quotation mark [double quote]),
1210 and '<code>\'</code>' (apostrophe [single quote]).
1211 A backslash followed by a real newline
1212 results in a newline in the string.
1213 The escape sequence '<code>\z</code>' skips the following span
1214 of white-space characters,
1215 including line breaks;
1216 it is particularly useful to break and indent a long literal string
1217 into multiple lines without adding the newlines and spaces
1218 into the string contents.
1219
1220
1221 <p>
1222 A byte in a literal string can also be specified by its numerical value.
1223 This can be done with the escape sequence <code>\x<em>XX</em></code>,
1224 where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1225 or with the escape sequence <code>\<em>ddd</em></code>,
1226 where <em>ddd</em> is a sequence of up to three decimal digits.
1227 (Note that if a decimal escape is to be followed by a digit,
1228 it must be expressed using exactly three digits.)
1229 Strings in Lua can contain any 8-bit value, including embedded zeros,
1230 which can be specified as '<code>\0</code>'.
1231
1232
1233 <p>
1234 Literal strings can also be defined using a long format
1235 enclosed by <em>long brackets</em>.
1236 We define an <em>opening long bracket of level <em>n</em></em> as an opening
1237 square bracket followed by <em>n</em> equal signs followed by another
1238 opening square bracket.
1239 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1240 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1241 and so on.
1242 A <em>closing long bracket</em> is defined similarly;
1243 for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
1244 A <em>long literal</em> starts with an opening long bracket of any level and
1245 ends at the first closing long bracket of the same level.
1246 It can contain any text except a closing bracket of the proper level.
1247 Literals in this bracketed form can run for several lines,
1248 do not interpret any escape sequences,
1249 and ignore long brackets of any other level.
1250 Any kind of end-of-line sequence
1251 (carriage return, newline, carriage return followed by newline,
1252 or newline followed by carriage return)
1253 is converted to a simple newline.
1254
1255
1256 <p>
1257 Any byte in a literal string not
1258 explicitly affected by the previous rules represents itself.
1259 However, Lua opens files for parsing in text mode,
1260 and the system file functions may have problems with
1261 some control characters.
1262 So, it is safer to represent
1263 non-text data as a quoted literal with
1264 explicit escape sequences for non-text characters.
1265
1266
1267 <p>
1268 For convenience,
1269 when the opening long bracket is immediately followed by a newline,
1270 the newline is not included in the string.
1271 As an example, in a system using ASCII
1272 (in which '<code>a</code>' is coded as&nbsp;97,
1273 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1274 the five literal strings below denote the same string:
1275
1276 <pre>
1277 a = 'alo\n123"'
1278 a = "alo\n123\""
1279 a = '\97lo\10\04923"'
1280 a = [[alo
1281 123"]]
1282 a = [==[
1283 alo
1284 123"]==]
1285 </pre>
1286
1287 <p>
1288 A <em>numerical constant</em> can be written with an optional fractional part
1289 and an optional decimal exponent,
1290 marked by a letter '<code>e</code>' or '<code>E</code>'.
1291 Lua also accepts hexadecimal constants,
1292 which start with <code>0x</code> or <code>0X</code>.
1293 Hexadecimal constants also accept an optional fractional part
1294 plus an optional binary exponent,
1295 marked by a letter '<code>p</code>' or '<code>P</code>'.
1296 Examples of valid numerical constants are
1297
1298 <pre>
1299 3 3.0 3.1416 314.16e-2 0.31416E1
1300 0xff 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1301 </pre>
1302
1303 <p>
1304 A <em>comment</em> starts with a double hyphen (<code>--</code>)
1305 anywhere outside a string.
1306 If the text immediately after <code>--</code> is not an opening long bracket,
1307 the comment is a <em>short comment</em>,
1308 which runs until the end of the line.
1309 Otherwise, it is a <em>long comment</em>,
1310 which runs until the corresponding closing long bracket.
1311 Long comments are frequently used to disable code temporarily.
1312
1313
1314
1315
1316
1317 <h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1318
1319 <p>
1320 Variables are places that store values.
1321 There are three kinds of variables in Lua:
1322 global variables, local variables, and table fields.
1323
1324
1325 <p>
1326 A single name can denote a global variable or a local variable
1327 (or a function's formal parameter,
1328 which is a particular kind of local variable):
1329
1330 <pre>
1331 var ::= Name
1332 </pre><p>
1333 Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>.
1334
1335
1336 <p>
1337 Any variable name is assumed to be global unless explicitly declared
1338 as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1339 Local variables are <em>lexically scoped</em>:
1340 local variables can be freely accessed by functions
1341 defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1342
1343
1344 <p>
1345 Before the first assignment to a variable, its value is <b>nil</b>.
1346
1347
1348 <p>
1349 Square brackets are used to index a table:
1350
1351 <pre>
1352 var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1353 </pre><p>
1354 The meaning of accesses to table fields can be changed via metatables.
1355 An access to an indexed variable <code>t[i]</code> is equivalent to
1356 a call <code>gettable_event(t,i)</code>.
1357 (See <a href="#2.4">&sect;2.4</a> for a complete description of the
1358 <code>gettable_event</code> function.
1359 This function is not defined or callable in Lua.
1360 We use it here only for explanatory purposes.)
1361
1362
1363 <p>
1364 The syntax <code>var.Name</code> is just syntactic sugar for
1365 <code>var["Name"]</code>:
1366
1367 <pre>
1368 var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1369 </pre>
1370
1371 <p>
1372 An access to a global variable <code>x</code>
1373 is equivalent to <code>_ENV.x</code>.
1374 Due to the way that chunks are compiled,
1375 <code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>).
1376
1377
1378
1379
1380
1381 <h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1382
1383 <p>
1384 Lua supports an almost conventional set of statements,
1385 similar to those in Pascal or C.
1386 This set includes
1387 assignments, control structures, function calls,
1388 and variable declarations.
1389
1390
1391
1392 <h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1393
1394 <p>
1395 A block is a list of statements,
1396 which are executed sequentially:
1397
1398 <pre>
1399 block ::= {stat}
1400 </pre><p>
1401 Lua has <em>empty statements</em>
1402 that allow you to separate statements with semicolons,
1403 start a block with a semicolon
1404 or write two semicolons in sequence:
1405
1406 <pre>
1407 stat ::= &lsquo;<b>;</b>&rsquo;
1408 </pre>
1409
1410 <p>
1411 Function calls and assignments
1412 can start with an open parenthesis.
1413 This possibility leads to an ambiguity in Lua's grammar.
1414 Consider the following fragment:
1415
1416 <pre>
1417 a = b + c
1418 (print or io.write)('done')
1419 </pre><p>
1420 The grammar could see it in two ways:
1421
1422 <pre>
1423 a = b + c(print or io.write)('done')
1424
1425 a = b + c; (print or io.write)('done')
1426 </pre><p>
1427 The current parser always sees such constructions
1428 in the first way,
1429 interpreting the open parenthesis
1430 as the start of the arguments to a call.
1431 To avoid this ambiguity,
1432 it is a good practice to always precede with a semicolon
1433 statements that start with a parenthesis:
1434
1435 <pre>
1436 ;(print or io.write)('done')
1437 </pre>
1438
1439 <p>
1440 A block can be explicitly delimited to produce a single statement:
1441
1442 <pre>
1443 stat ::= <b>do</b> block <b>end</b>
1444 </pre><p>
1445 Explicit blocks are useful
1446 to control the scope of variable declarations.
1447 Explicit blocks are also sometimes used to
1448 add a <b>return</b> statement in the middle
1449 of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1450
1451
1452
1453
1454
1455 <h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1456
1457 <p>
1458 The unit of compilation of Lua is called a <em>chunk</em>.
1459 Syntactically,
1460 a chunk is simply a block:
1461
1462 <pre>
1463 chunk ::= block
1464 </pre>
1465
1466 <p>
1467 Lua handles a chunk as the body of an anonymous function
1468 with a variable number of arguments
1469 (see <a href="#3.4.10">&sect;3.4.10</a>).
1470 As such, chunks can define local variables,
1471 receive arguments, and return values.
1472 Moreover, such anonymous function is compiled as in the
1473 scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1474 The resulting function always has <code>_ENV</code> as its only upvalue,
1475 even if it does not use that variable.
1476
1477
1478 <p>
1479 A chunk can be stored in a file or in a string inside the host program.
1480 To execute a chunk,
1481 Lua first precompiles the chunk into instructions for a virtual machine,
1482 and then it executes the compiled code
1483 with an interpreter for the virtual machine.
1484
1485
1486 <p>
1487 Chunks can also be precompiled into binary form;
1488 see program <code>luac</code> for details.
1489 Programs in source and compiled forms are interchangeable;
1490 Lua automatically detects the file type and acts accordingly.
1491
1492
1493
1494
1495
1496
1497 <h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1498
1499 <p>
1500 Lua allows multiple assignments.
1501 Therefore, the syntax for assignment
1502 defines a list of variables on the left side
1503 and a list of expressions on the right side.
1504 The elements in both lists are separated by commas:
1505
1506 <pre>
1507 stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1508 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1509 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1510 </pre><p>
1511 Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1512
1513
1514 <p>
1515 Before the assignment,
1516 the list of values is <em>adjusted</em> to the length of
1517 the list of variables.
1518 If there are more values than needed,
1519 the excess values are thrown away.
1520 If there are fewer values than needed,
1521 the list is extended with as many <b>nil</b>'s as needed.
1522 If the list of expressions ends with a function call,
1523 then all values returned by that call enter the list of values,
1524 before the adjustment
1525 (except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1526
1527
1528 <p>
1529 The assignment statement first evaluates all its expressions
1530 and only then are the assignments performed.
1531 Thus the code
1532
1533 <pre>
1534 i = 3
1535 i, a[i] = i+1, 20
1536 </pre><p>
1537 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1538 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1539 before it is assigned&nbsp;4.
1540 Similarly, the line
1541
1542 <pre>
1543 x, y = y, x
1544 </pre><p>
1545 exchanges the values of <code>x</code> and <code>y</code>,
1546 and
1547
1548 <pre>
1549 x, y, z = y, z, x
1550 </pre><p>
1551 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1552
1553
1554 <p>
1555 The meaning of assignments to global variables
1556 and table fields can be changed via metatables.
1557 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
1558 <code>settable_event(t,i,val)</code>.
1559 (See <a href="#2.4">&sect;2.4</a> for a complete description of the
1560 <code>settable_event</code> function.
1561 This function is not defined or callable in Lua.
1562 We use it here only for explanatory purposes.)
1563
1564
1565 <p>
1566 An assignment to a global variable <code>x = val</code>
1567 is equivalent to the assignment
1568 <code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1569
1570
1571
1572
1573
1574 <h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1575 The control structures
1576 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1577 familiar syntax:
1578
1579
1580
1581
1582 <pre>
1583 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1584 stat ::= <b>repeat</b> block <b>until</b> exp
1585 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1586 </pre><p>
1587 Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1588
1589
1590 <p>
1591 The condition expression of a
1592 control structure can return any value.
1593 Both <b>false</b> and <b>nil</b> are considered false.
1594 All values different from <b>nil</b> and <b>false</b> are considered true
1595 (in particular, the number 0 and the empty string are also true).
1596
1597
1598 <p>
1599 In the <b>repeat</b>&ndash;<b>until</b> loop,
1600 the inner block does not end at the <b>until</b> keyword,
1601 but only after the condition.
1602 So, the condition can refer to local variables
1603 declared inside the loop block.
1604
1605
1606 <p>
1607 The <b>goto</b> statement transfers the program control to a label.
1608 For syntactical reasons,
1609 labels in Lua are considered statements too:
1610
1611
1612
1613 <pre>
1614 stat ::= <b>goto</b> Name
1615 stat ::= label
1616 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1617 </pre>
1618
1619 <p>
1620 A label is visible in the entire block where it is defined,
1621 except
1622 inside nested blocks where a label with the same name is defined and
1623 inside nested functions.
1624 A goto may jump to any visible label as long as it does not
1625 enter into the scope of a local variable.
1626
1627
1628 <p>
1629 Labels and empty statements are called <em>void statements</em>,
1630 as they perform no actions.
1631
1632
1633 <p>
1634 The <b>break</b> statement terminates the execution of a
1635 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1636 skipping to the next statement after the loop:
1637
1638
1639 <pre>
1640 stat ::= <b>break</b>
1641 </pre><p>
1642 A <b>break</b> ends the innermost enclosing loop.
1643
1644
1645 <p>
1646 The <b>return</b> statement is used to return values
1647 from a function or a chunk (which is a function in disguise).
1648
1649 Functions can return more than one value,
1650 so the syntax for the <b>return</b> statement is
1651
1652 <pre>
1653 stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1654 </pre>
1655
1656 <p>
1657 The <b>return</b> statement can only be written
1658 as the last statement of a block.
1659 If it is really necessary to <b>return</b> in the middle of a block,
1660 then an explicit inner block can be used,
1661 as in the idiom <code>do return end</code>,
1662 because now <b>return</b> is the last statement in its (inner) block.
1663
1664
1665
1666
1667
1668 <h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1669
1670 <p>
1671
1672 The <b>for</b> statement has two forms:
1673 one numeric and one generic.
1674
1675
1676 <p>
1677 The numeric <b>for</b> loop repeats a block of code while a
1678 control variable runs through an arithmetic progression.
1679 It has the following syntax:
1680
1681 <pre>
1682 stat ::= <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b>
1683 </pre><p>
1684 The <em>block</em> is repeated for <em>name</em> starting at the value of
1685 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1686 third <em>exp</em>.
1687 More precisely, a <b>for</b> statement like
1688
1689 <pre>
1690 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1691 </pre><p>
1692 is equivalent to the code:
1693
1694 <pre>
1695 do
1696 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
1697 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1698 while (<em>step</em> &gt; 0 and <em>var</em> &lt;= <em>limit</em>) or (<em>step</em> &lt;= 0 and <em>var</em> &gt;= <em>limit</em>) do
1699 local v = <em>var</em>
1700 <em>block</em>
1701 <em>var</em> = <em>var</em> + <em>step</em>
1702 end
1703 end
1704 </pre><p>
1705 Note the following:
1706
1707 <ul>
1708
1709 <li>
1710 All three control expressions are evaluated only once,
1711 before the loop starts.
1712 They must all result in numbers.
1713 </li>
1714
1715 <li>
1716 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1717 The names shown here are for explanatory purposes only.
1718 </li>
1719
1720 <li>
1721 If the third expression (the step) is absent,
1722 then a step of&nbsp;1 is used.
1723 </li>
1724
1725 <li>
1726 You can use <b>break</b> to exit a <b>for</b> loop.
1727 </li>
1728
1729 <li>
1730 The loop variable <code>v</code> is local to the loop;
1731 you cannot use its value after the <b>for</b> ends or is broken.
1732 If you need this value,
1733 assign it to another variable before breaking or exiting the loop.
1734 </li>
1735
1736 </ul>
1737
1738 <p>
1739 The generic <b>for</b> statement works over functions,
1740 called <em>iterators</em>.
1741 On each iteration, the iterator function is called to produce a new value,
1742 stopping when this new value is <b>nil</b>.
1743 The generic <b>for</b> loop has the following syntax:
1744
1745 <pre>
1746 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1747 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1748 </pre><p>
1749 A <b>for</b> statement like
1750
1751 <pre>
1752 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1753 </pre><p>
1754 is equivalent to the code:
1755
1756 <pre>
1757 do
1758 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1759 while true do
1760 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
1761 if <em>var_1</em> == nil then break end
1762 <em>var</em> = <em>var_1</em>
1763 <em>block</em>
1764 end
1765 end
1766 </pre><p>
1767 Note the following:
1768
1769 <ul>
1770
1771 <li>
1772 <code><em>explist</em></code> is evaluated only once.
1773 Its results are an <em>iterator</em> function,
1774 a <em>state</em>,
1775 and an initial value for the first <em>iterator variable</em>.
1776 </li>
1777
1778 <li>
1779 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1780 The names are here for explanatory purposes only.
1781 </li>
1782
1783 <li>
1784 You can use <b>break</b> to exit a <b>for</b> loop.
1785 </li>
1786
1787 <li>
1788 The loop variables <code><em>var_i</em></code> are local to the loop;
1789 you cannot use their values after the <b>for</b> ends.
1790 If you need these values,
1791 then assign them to other variables before breaking or exiting the loop.
1792 </li>
1793
1794 </ul>
1795
1796
1797
1798
1799 <h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1800 To allow possible side-effects,
1801 function calls can be executed as statements:
1802
1803 <pre>
1804 stat ::= functioncall
1805 </pre><p>
1806 In this case, all returned values are thrown away.
1807 Function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1808
1809
1810
1811
1812
1813 <h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1814 Local variables can be declared anywhere inside a block.
1815 The declaration can include an initial assignment:
1816
1817 <pre>
1818 stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
1819 </pre><p>
1820 If present, an initial assignment has the same semantics
1821 of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1822 Otherwise, all variables are initialized with <b>nil</b>.
1823
1824
1825 <p>
1826 A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1827 and so local variables can be declared in a chunk outside any explicit block.
1828
1829
1830 <p>
1831 The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1832
1833
1834
1835
1836
1837
1838
1839 <h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
1840
1841 <p>
1842 The basic expressions in Lua are the following:
1843
1844 <pre>
1845 exp ::= prefixexp
1846 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1847 exp ::= Number
1848 exp ::= String
1849 exp ::= functiondef
1850 exp ::= tableconstructor
1851 exp ::= &lsquo;<b>...</b>&rsquo;
1852 exp ::= exp binop exp
1853 exp ::= unop exp
1854 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1855 </pre>
1856
1857 <p>
1858 Numbers and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1859 variables are explained in <a href="#3.2">&sect;3.2</a>;
1860 function definitions are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1861 function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>;
1862 table constructors are explained in <a href="#3.4.8">&sect;3.4.8</a>.
1863 Vararg expressions,
1864 denoted by three dots ('<code>...</code>'), can only be used when
1865 directly inside a vararg function;
1866 they are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1867
1868
1869 <p>
1870 Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1871 relational operators (see <a href="#3.4.3">&sect;3.4.3</a>), logical operators (see <a href="#3.4.4">&sect;3.4.4</a>),
1872 and the concatenation operator (see <a href="#3.4.5">&sect;3.4.5</a>).
1873 Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1874 the unary <b>not</b> (see <a href="#3.4.4">&sect;3.4.4</a>),
1875 and the unary <em>length operator</em> (see <a href="#3.4.6">&sect;3.4.6</a>).
1876
1877
1878 <p>
1879 Both function calls and vararg expressions can result in multiple values.
1880 If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
1881 then its return list is adjusted to zero elements,
1882 thus discarding all returned values.
1883 If an expression is used as the last (or the only) element
1884 of a list of expressions,
1885 then no adjustment is made
1886 (unless the expression is enclosed in parentheses).
1887 In all other contexts,
1888 Lua adjusts the result list to one element,
1889 either discarding all values except the first one
1890 or adding a single <b>nil</b> if there are no values.
1891
1892
1893 <p>
1894 Here are some examples:
1895
1896 <pre>
1897 f() -- adjusted to 0 results
1898 g(f(), x) -- f() is adjusted to 1 result
1899 g(x, f()) -- g gets x plus all results from f()
1900 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
1901 a,b = ... -- a gets the first vararg parameter, b gets
1902 -- the second (both a and b can get nil if there
1903 -- is no corresponding vararg parameter)
1904
1905 a,b,c = x, f() -- f() is adjusted to 2 results
1906 a,b,c = f() -- f() is adjusted to 3 results
1907 return f() -- returns all results from f()
1908 return ... -- returns all received vararg parameters
1909 return x,y,f() -- returns x, y, and all results from f()
1910 {f()} -- creates a list with all results from f()
1911 {...} -- creates a list with all vararg parameters
1912 {f(), nil} -- f() is adjusted to 1 result
1913 </pre>
1914
1915 <p>
1916 Any expression enclosed in parentheses always results in only one value.
1917 Thus,
1918 <code>(f(x,y,z))</code> is always a single value,
1919 even if <code>f</code> returns several values.
1920 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
1921 or <b>nil</b> if <code>f</code> does not return any values.)
1922
1923
1924
1925 <h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1926 Lua supports the usual arithmetic operators:
1927 the binary <code>+</code> (addition),
1928 <code>-</code> (subtraction), <code>*</code> (multiplication),
1929 <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
1930 and unary <code>-</code> (mathematical negation).
1931 If the operands are numbers, or strings that can be converted to
1932 numbers (see <a href="#3.4.2">&sect;3.4.2</a>),
1933 then all operations have the usual meaning.
1934 Exponentiation works for any exponent.
1935 For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
1936 Modulo is defined as
1937
1938 <pre>
1939 a % b == a - math.floor(a/b)*b
1940 </pre><p>
1941 That is, it is the remainder of a division that rounds
1942 the quotient towards minus infinity.
1943
1944
1945
1946
1947
1948 <h3>3.4.2 &ndash; <a name="3.4.2">Coercion</a></h3>
1949
1950 <p>
1951 Lua provides automatic conversion between
1952 string and number values at run time.
1953 Any arithmetic operation applied to a string tries to convert
1954 this string to a number, following the rules of the Lua lexer.
1955 (The string may have leading and trailing spaces and a sign.)
1956 Conversely, whenever a number is used where a string is expected,
1957 the number is converted to a string, in a reasonable format.
1958 For complete control over how numbers are converted to strings,
1959 use the <code>format</code> function from the string library
1960 (see <a href="#pdf-string.format"><code>string.format</code></a>).
1961
1962
1963
1964
1965
1966 <h3>3.4.3 &ndash; <a name="3.4.3">Relational Operators</a></h3><p>
1967 The relational operators in Lua are
1968
1969 <pre>
1970 == ~= &lt; &gt; &lt;= &gt;=
1971 </pre><p>
1972 These operators always result in <b>false</b> or <b>true</b>.
1973
1974
1975 <p>
1976 Equality (<code>==</code>) first compares the type of its operands.
1977 If the types are different, then the result is <b>false</b>.
1978 Otherwise, the values of the operands are compared.
1979 Numbers and strings are compared in the usual way.
1980 Tables, userdata, and threads
1981 are compared by reference:
1982 two objects are considered equal only if they are the same object.
1983 Every time you create a new object
1984 (a table, userdata, or thread),
1985 this new object is different from any previously existing object.
1986 Closures with the same reference are always equal.
1987 Closures with any detectable difference
1988 (different behavior, different definition) are always different.
1989
1990
1991 <p>
1992 You can change the way that Lua compares tables and userdata
1993 by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>).
1994
1995
1996 <p>
1997 The conversion rules of <a href="#3.4.2">&sect;3.4.2</a>
1998 do not apply to equality comparisons.
1999 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2000 and <code>t[0]</code> and <code>t["0"]</code> denote different
2001 entries in a table.
2002
2003
2004 <p>
2005 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2006
2007
2008 <p>
2009 The order operators work as follows.
2010 If both arguments are numbers, then they are compared as such.
2011 Otherwise, if both arguments are strings,
2012 then their values are compared according to the current locale.
2013 Otherwise, Lua tries to call the "lt" or the "le"
2014 metamethod (see <a href="#2.4">&sect;2.4</a>).
2015 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2016 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2017
2018
2019
2020
2021
2022 <h3>3.4.4 &ndash; <a name="3.4.4">Logical Operators</a></h3><p>
2023 The logical operators in Lua are
2024 <b>and</b>, <b>or</b>, and <b>not</b>.
2025 Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2026 all logical operators consider both <b>false</b> and <b>nil</b> as false
2027 and anything else as true.
2028
2029
2030 <p>
2031 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2032 The conjunction operator <b>and</b> returns its first argument
2033 if this value is <b>false</b> or <b>nil</b>;
2034 otherwise, <b>and</b> returns its second argument.
2035 The disjunction operator <b>or</b> returns its first argument
2036 if this value is different from <b>nil</b> and <b>false</b>;
2037 otherwise, <b>or</b> returns its second argument.
2038 Both <b>and</b> and <b>or</b> use short-cut evaluation;
2039 that is,
2040 the second operand is evaluated only if necessary.
2041 Here are some examples:
2042
2043 <pre>
2044 10 or 20 --&gt; 10
2045 10 or error() --&gt; 10
2046 nil or "a" --&gt; "a"
2047 nil and 10 --&gt; nil
2048 false and error() --&gt; false
2049 false and nil --&gt; false
2050 false or nil --&gt; nil
2051 10 and 20 --&gt; 20
2052 </pre><p>
2053 (In this manual,
2054 <code>--&gt;</code> indicates the result of the preceding expression.)
2055
2056
2057
2058
2059
2060 <h3>3.4.5 &ndash; <a name="3.4.5">Concatenation</a></h3><p>
2061 The string concatenation operator in Lua is
2062 denoted by two dots ('<code>..</code>').
2063 If both operands are strings or numbers, then they are converted to
2064 strings according to the rules mentioned in <a href="#3.4.2">&sect;3.4.2</a>.
2065 Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2066
2067
2068
2069
2070
2071 <h3>3.4.6 &ndash; <a name="3.4.6">The Length Operator</a></h3>
2072
2073 <p>
2074 The length operator is denoted by the unary prefix operator <code>#</code>.
2075 The length of a string is its number of bytes
2076 (that is, the usual meaning of string length when each
2077 character is one byte).
2078
2079
2080 <p>
2081 A program can modify the behavior of the length operator for
2082 any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2083
2084
2085 <p>
2086 Unless a <code>__len</code> metamethod is given,
2087 the length of a table <code>t</code> is only defined if the
2088 table is a <em>sequence</em>,
2089 that is,
2090 the set of its positive numeric keys is equal to <em>{1..n}</em>
2091 for some integer <em>n</em>.
2092 In that case, <em>n</em> is its length.
2093 Note that a table like
2094
2095 <pre>
2096 {10, 20, nil, 40}
2097 </pre><p>
2098 is not a sequence, because it has the key <code>4</code>
2099 but does not have the key <code>3</code>.
2100 (So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal
2101 to the set of positive numeric keys of that table.)
2102 Note, however, that non-numeric keys do not interfere
2103 with whether a table is a sequence.
2104
2105
2106
2107
2108
2109 <h3>3.4.7 &ndash; <a name="3.4.7">Precedence</a></h3><p>
2110 Operator precedence in Lua follows the table below,
2111 from lower to higher priority:
2112
2113 <pre>
2114 or
2115 and
2116 &lt; &gt; &lt;= &gt;= ~= ==
2117 ..
2118 + -
2119 * / %
2120 not # - (unary)
2121 ^
2122 </pre><p>
2123 As usual,
2124 you can use parentheses to change the precedences of an expression.
2125 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2126 operators are right associative.
2127 All other binary operators are left associative.
2128
2129
2130
2131
2132
2133 <h3>3.4.8 &ndash; <a name="3.4.8">Table Constructors</a></h3><p>
2134 Table constructors are expressions that create tables.
2135 Every time a constructor is evaluated, a new table is created.
2136 A constructor can be used to create an empty table
2137 or to create a table and initialize some of its fields.
2138 The general syntax for constructors is
2139
2140 <pre>
2141 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2142 fieldlist ::= field {fieldsep field} [fieldsep]
2143 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2144 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2145 </pre>
2146
2147 <p>
2148 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2149 with key <code>exp1</code> and value <code>exp2</code>.
2150 A field of the form <code>name = exp</code> is equivalent to
2151 <code>["name"] = exp</code>.
2152 Finally, fields of the form <code>exp</code> are equivalent to
2153 <code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
2154 starting with 1.
2155 Fields in the other formats do not affect this counting.
2156 For example,
2157
2158 <pre>
2159 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2160 </pre><p>
2161 is equivalent to
2162
2163 <pre>
2164 do
2165 local t = {}
2166 t[f(1)] = g
2167 t[1] = "x" -- 1st exp
2168 t[2] = "y" -- 2nd exp
2169 t.x = 1 -- t["x"] = 1
2170 t[3] = f(x) -- 3rd exp
2171 t[30] = 23
2172 t[4] = 45 -- 4th exp
2173 a = t
2174 end
2175 </pre>
2176
2177 <p>
2178 If the last field in the list has the form <code>exp</code>
2179 and the expression is a function call or a vararg expression,
2180 then all values returned by this expression enter the list consecutively
2181 (see <a href="#3.4.9">&sect;3.4.9</a>).
2182
2183
2184 <p>
2185 The field list can have an optional trailing separator,
2186 as a convenience for machine-generated code.
2187
2188
2189
2190
2191
2192 <h3>3.4.9 &ndash; <a name="3.4.9">Function Calls</a></h3><p>
2193 A function call in Lua has the following syntax:
2194
2195 <pre>
2196 functioncall ::= prefixexp args
2197 </pre><p>
2198 In a function call,
2199 first prefixexp and args are evaluated.
2200 If the value of prefixexp has type <em>function</em>,
2201 then this function is called
2202 with the given arguments.
2203 Otherwise, the prefixexp "call" metamethod is called,
2204 having as first parameter the value of prefixexp,
2205 followed by the original call arguments
2206 (see <a href="#2.4">&sect;2.4</a>).
2207
2208
2209 <p>
2210 The form
2211
2212 <pre>
2213 functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2214 </pre><p>
2215 can be used to call "methods".
2216 A call <code>v:name(<em>args</em>)</code>
2217 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2218 except that <code>v</code> is evaluated only once.
2219
2220
2221 <p>
2222 Arguments have the following syntax:
2223
2224 <pre>
2225 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2226 args ::= tableconstructor
2227 args ::= String
2228 </pre><p>
2229 All argument expressions are evaluated before the call.
2230 A call of the form <code>f{<em>fields</em>}</code> is
2231 syntactic sugar for <code>f({<em>fields</em>})</code>;
2232 that is, the argument list is a single new table.
2233 A call of the form <code>f'<em>string</em>'</code>
2234 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2235 is syntactic sugar for <code>f('<em>string</em>')</code>;
2236 that is, the argument list is a single literal string.
2237
2238
2239 <p>
2240 A call of the form <code>return <em>functioncall</em></code> is called
2241 a <em>tail call</em>.
2242 Lua implements <em>proper tail calls</em>
2243 (or <em>proper tail recursion</em>):
2244 in a tail call,
2245 the called function reuses the stack entry of the calling function.
2246 Therefore, there is no limit on the number of nested tail calls that
2247 a program can execute.
2248 However, a tail call erases any debug information about the
2249 calling function.
2250 Note that a tail call only happens with a particular syntax,
2251 where the <b>return</b> has one single function call as argument;
2252 this syntax makes the calling function return exactly
2253 the returns of the called function.
2254 So, none of the following examples are tail calls:
2255
2256 <pre>
2257 return (f(x)) -- results adjusted to 1
2258 return 2 * f(x)
2259 return x, f(x) -- additional results
2260 f(x); return -- results discarded
2261 return x or f(x) -- results adjusted to 1
2262 </pre>
2263
2264
2265
2266
2267 <h3>3.4.10 &ndash; <a name="3.4.10">Function Definitions</a></h3>
2268
2269 <p>
2270 The syntax for function definition is
2271
2272 <pre>
2273 functiondef ::= <b>function</b> funcbody
2274 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2275 </pre>
2276
2277 <p>
2278 The following syntactic sugar simplifies function definitions:
2279
2280 <pre>
2281 stat ::= <b>function</b> funcname funcbody
2282 stat ::= <b>local</b> <b>function</b> Name funcbody
2283 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2284 </pre><p>
2285 The statement
2286
2287 <pre>
2288 function f () <em>body</em> end
2289 </pre><p>
2290 translates to
2291
2292 <pre>
2293 f = function () <em>body</em> end
2294 </pre><p>
2295 The statement
2296
2297 <pre>
2298 function t.a.b.c.f () <em>body</em> end
2299 </pre><p>
2300 translates to
2301
2302 <pre>
2303 t.a.b.c.f = function () <em>body</em> end
2304 </pre><p>
2305 The statement
2306
2307 <pre>
2308 local function f () <em>body</em> end
2309 </pre><p>
2310 translates to
2311
2312 <pre>
2313 local f; f = function () <em>body</em> end
2314 </pre><p>
2315 not to
2316
2317 <pre>
2318 local f = function () <em>body</em> end
2319 </pre><p>
2320 (This only makes a difference when the body of the function
2321 contains references to <code>f</code>.)
2322
2323
2324 <p>
2325 A function definition is an executable expression,
2326 whose value has type <em>function</em>.
2327 When Lua precompiles a chunk,
2328 all its function bodies are precompiled too.
2329 Then, whenever Lua executes the function definition,
2330 the function is <em>instantiated</em> (or <em>closed</em>).
2331 This function instance (or <em>closure</em>)
2332 is the final value of the expression.
2333
2334
2335 <p>
2336 Parameters act as local variables that are
2337 initialized with the argument values:
2338
2339 <pre>
2340 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2341 </pre><p>
2342 When a function is called,
2343 the list of arguments is adjusted to
2344 the length of the list of parameters,
2345 unless the function is a <em>vararg function</em>,
2346 which is indicated by three dots ('<code>...</code>')
2347 at the end of its parameter list.
2348 A vararg function does not adjust its argument list;
2349 instead, it collects all extra arguments and supplies them
2350 to the function through a <em>vararg expression</em>,
2351 which is also written as three dots.
2352 The value of this expression is a list of all actual extra arguments,
2353 similar to a function with multiple results.
2354 If a vararg expression is used inside another expression
2355 or in the middle of a list of expressions,
2356 then its return list is adjusted to one element.
2357 If the expression is used as the last element of a list of expressions,
2358 then no adjustment is made
2359 (unless that last expression is enclosed in parentheses).
2360
2361
2362 <p>
2363 As an example, consider the following definitions:
2364
2365 <pre>
2366 function f(a, b) end
2367 function g(a, b, ...) end
2368 function r() return 1,2,3 end
2369 </pre><p>
2370 Then, we have the following mapping from arguments to parameters and
2371 to the vararg expression:
2372
2373 <pre>
2374 CALL PARAMETERS
2375
2376 f(3) a=3, b=nil
2377 f(3, 4) a=3, b=4
2378 f(3, 4, 5) a=3, b=4
2379 f(r(), 10) a=1, b=10
2380 f(r()) a=1, b=2
2381
2382 g(3) a=3, b=nil, ... --&gt; (nothing)
2383 g(3, 4) a=3, b=4, ... --&gt; (nothing)
2384 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
2385 g(5, r()) a=5, b=1, ... --&gt; 2 3
2386 </pre>
2387
2388 <p>
2389 Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2390 If control reaches the end of a function
2391 without encountering a <b>return</b> statement,
2392 then the function returns with no results.
2393
2394
2395 <p>
2396
2397 There is a system-dependent limit on the number of values
2398 that a function may return.
2399 This limit is guaranteed to be larger than 1000.
2400
2401
2402 <p>
2403 The <em>colon</em> syntax
2404 is used for defining <em>methods</em>,
2405 that is, functions that have an implicit extra parameter <code>self</code>.
2406 Thus, the statement
2407
2408 <pre>
2409 function t.a.b.c:f (<em>params</em>) <em>body</em> end
2410 </pre><p>
2411 is syntactic sugar for
2412
2413 <pre>
2414 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2415 </pre>
2416
2417
2418
2419
2420
2421
2422 <h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2423
2424 <p>
2425
2426 Lua is a lexically scoped language.
2427 The scope of a local variable begins at the first statement after
2428 its declaration and lasts until the last non-void statement
2429 of the innermost block that includes the declaration.
2430 Consider the following example:
2431
2432 <pre>
2433 x = 10 -- global variable
2434 do -- new block
2435 local x = x -- new 'x', with value 10
2436 print(x) --&gt; 10
2437 x = x+1
2438 do -- another block
2439 local x = x+1 -- another 'x'
2440 print(x) --&gt; 12
2441 end
2442 print(x) --&gt; 11
2443 end
2444 print(x) --&gt; 10 (the global one)
2445 </pre>
2446
2447 <p>
2448 Notice that, in a declaration like <code>local x = x</code>,
2449 the new <code>x</code> being declared is not in scope yet,
2450 and so the second <code>x</code> refers to the outside variable.
2451
2452
2453 <p>
2454 Because of the lexical scoping rules,
2455 local variables can be freely accessed by functions
2456 defined inside their scope.
2457 A local variable used by an inner function is called
2458 an <em>upvalue</em>, or <em>external local variable</em>,
2459 inside the inner function.
2460
2461
2462 <p>
2463 Notice that each execution of a <b>local</b> statement
2464 defines new local variables.
2465 Consider the following example:
2466
2467 <pre>
2468 a = {}
2469 local x = 20
2470 for i=1,10 do
2471 local y = 0
2472 a[i] = function () y=y+1; return x+y end
2473 end
2474 </pre><p>
2475 The loop creates ten closures
2476 (that is, ten instances of the anonymous function).
2477 Each of these closures uses a different <code>y</code> variable,
2478 while all of them share the same <code>x</code>.
2479
2480
2481
2482
2483
2484 <h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2485
2486 <p>
2487
2488 This section describes the C&nbsp;API for Lua, that is,
2489 the set of C&nbsp;functions available to the host program to communicate
2490 with Lua.
2491 All API functions and related types and constants
2492 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2493
2494
2495 <p>
2496 Even when we use the term "function",
2497 any facility in the API may be provided as a macro instead.
2498 Except where stated otherwise,
2499 all such macros use each of their arguments exactly once
2500 (except for the first argument, which is always a Lua state),
2501 and so do not generate any hidden side-effects.
2502
2503
2504 <p>
2505 As in most C&nbsp;libraries,
2506 the Lua API functions do not check their arguments for validity or consistency.
2507 However, you can change this behavior by compiling Lua
2508 with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2509
2510
2511
2512 <h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2513
2514 <p>
2515 Lua uses a <em>virtual stack</em> to pass values to and from C.
2516 Each element in this stack represents a Lua value
2517 (<b>nil</b>, number, string, etc.).
2518
2519
2520 <p>
2521 Whenever Lua calls C, the called function gets a new stack,
2522 which is independent of previous stacks and of stacks of
2523 C&nbsp;functions that are still active.
2524 This stack initially contains any arguments to the C&nbsp;function
2525 and it is where the C&nbsp;function pushes its results
2526 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2527
2528
2529 <p>
2530 For convenience,
2531 most query operations in the API do not follow a strict stack discipline.
2532 Instead, they can refer to any element in the stack
2533 by using an <em>index</em>:
2534 A positive index represents an absolute stack position
2535 (starting at&nbsp;1);
2536 a negative index represents an offset relative to the top of the stack.
2537 More specifically, if the stack has <em>n</em> elements,
2538 then index&nbsp;1 represents the first element
2539 (that is, the element that was pushed onto the stack first)
2540 and
2541 index&nbsp;<em>n</em> represents the last element;
2542 index&nbsp;-1 also represents the last element
2543 (that is, the element at the&nbsp;top)
2544 and index <em>-n</em> represents the first element.
2545
2546
2547
2548
2549
2550 <h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2>
2551
2552 <p>
2553 When you interact with the Lua API,
2554 you are responsible for ensuring consistency.
2555 In particular,
2556 <em>you are responsible for controlling stack overflow</em>.
2557 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2558 to ensure that the stack has extra slots when pushing new elements.
2559
2560
2561 <p>
2562 Whenever Lua calls C,
2563 it ensures that the stack has at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2564 <code>LUA_MINSTACK</code> is defined as 20,
2565 so that usually you do not have to worry about stack space
2566 unless your code has loops pushing elements onto the stack.
2567
2568
2569 <p>
2570 When you call a Lua function
2571 without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2572 Lua ensures that the stack has enough size for all results,
2573 but it does not ensure any extra space.
2574 So, before pushing anything in the stack after such a call
2575 you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2576
2577
2578
2579
2580
2581 <h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2>
2582
2583 <p>
2584 Any function in the API that receives stack indices
2585 works only with <em>valid indices</em> or <em>acceptable indices</em>.
2586
2587
2588 <p>
2589 A <em>valid index</em> is an index that refers to a
2590 real position within the stack, that is,
2591 its position lies between&nbsp;1 and the stack top
2592 (<code>1 &le; abs(index) &le; top</code>).
2593
2594 Usually, functions that can modify the value at an index
2595 require valid indices.
2596
2597
2598 <p>
2599 Unless otherwise noted,
2600 any function that accepts valid indices also accepts <em>pseudo-indices</em>,
2601 which represent some Lua values that are accessible to C&nbsp;code
2602 but which are not in the stack.
2603 Pseudo-indices are used to access the registry
2604 and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>).
2605
2606
2607 <p>
2608 Functions that do not need a specific stack position,
2609 but only a value in the stack (e.g., query functions),
2610 can be called with acceptable indices.
2611 An <em>acceptable index</em> can be any valid index,
2612 including the pseudo-indices,
2613 but it also can be any positive index after the stack top
2614 within the space allocated for the stack,
2615 that is, indices up to the stack size.
2616 (Note that 0 is never an acceptable index.)
2617 Except when noted otherwise,
2618 functions in the API work with acceptable indices.
2619
2620
2621 <p>
2622 Acceptable indices serve to avoid extra tests
2623 against the stack top when querying the stack.
2624 For instance, a C&nbsp;function can query its third argument
2625 without the need to first check whether there is a third argument,
2626 that is, without the need to check whether 3 is a valid index.
2627
2628
2629 <p>
2630 For functions that can be called with acceptable indices,
2631 any non-valid index is treated as if it
2632 contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2633 which behaves like a nil value.
2634
2635
2636
2637
2638
2639 <h2>4.4 &ndash; <a name="4.4">C Closures</a></h2>
2640
2641 <p>
2642 When a C&nbsp;function is created,
2643 it is possible to associate some values with it,
2644 thus creating a <em>C&nbsp;closure</em>
2645 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2646 these values are called <em>upvalues</em> and are
2647 accessible to the function whenever it is called.
2648
2649
2650 <p>
2651 Whenever a C&nbsp;function is called,
2652 its upvalues are located at specific pseudo-indices.
2653 These pseudo-indices are produced by the macro
2654 <a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2655 The first value associated with a function is at position
2656 <code>lua_upvalueindex(1)</code>, and so on.
2657 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2658 where <em>n</em> is greater than the number of upvalues of the
2659 current function (but not greater than 256),
2660 produces an acceptable but invalid index.
2661
2662
2663
2664
2665
2666 <h2>4.5 &ndash; <a name="4.5">Registry</a></h2>
2667
2668 <p>
2669 Lua provides a <em>registry</em>,
2670 a predefined table that can be used by any C&nbsp;code to
2671 store whatever Lua values it needs to store.
2672 The registry table is always located at pseudo-index
2673 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
2674 which is a valid index.
2675 Any C&nbsp;library can store data into this table,
2676 but it should take care to choose keys
2677 that are different from those used
2678 by other libraries, to avoid collisions.
2679 Typically, you should use as key a string containing your library name,
2680 or a light userdata with the address of a C&nbsp;object in your code,
2681 or any Lua object created by your code.
2682 As with global names,
2683 string keys starting with an underscore followed by
2684 uppercase letters are reserved for Lua.
2685
2686
2687 <p>
2688 The integer keys in the registry are used by the reference mechanism,
2689 implemented by the auxiliary library,
2690 and by some predefined values.
2691 Therefore, integer keys should not be used for other purposes.
2692
2693
2694 <p>
2695 When you create a new Lua state,
2696 its registry comes with some predefined values.
2697 These predefined values are indexed with integer keys
2698 defined as constants in <code>lua.h</code>.
2699 The following constants are defined:
2700
2701 <ul>
2702 <li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2703 the main thread of the state.
2704 (The main thread is the one created together with the state.)
2705 </li>
2706
2707 <li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2708 the global environment.
2709 </li>
2710 </ul>
2711
2712
2713
2714
2715 <h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2>
2716
2717 <p>
2718 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2719 (You can also choose to use exceptions if you compile Lua as C++;
2720 search for <code>LUAI_THROW</code> in the source code.)
2721 When Lua faces any error
2722 (such as a memory allocation error, type errors, syntax errors,
2723 and runtime errors)
2724 it <em>raises</em> an error;
2725 that is, it does a long jump.
2726 A <em>protected environment</em> uses <code>setjmp</code>
2727 to set a recovery point;
2728 any error jumps to the most recent active recovery point.
2729
2730
2731 <p>
2732 If an error happens outside any protected environment,
2733 Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2734 and then calls <code>abort</code>,
2735 thus exiting the host application.
2736 Your panic function can avoid this exit by
2737 never returning
2738 (e.g., doing a long jump to your own recovery point outside Lua).
2739
2740
2741 <p>
2742 The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
2743 in particular, the error message is at the top of the stack.
2744 However, there is no guarantees about stack space.
2745 To push anything on the stack,
2746 the panic function should first check the available space (see <a href="#4.2">&sect;4.2</a>).
2747
2748
2749 <p>
2750 Most functions in the API can throw an error,
2751 for instance due to a memory allocation error.
2752 The documentation for each function indicates whether
2753 it can throw errors.
2754
2755
2756 <p>
2757 Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2758
2759
2760
2761
2762
2763 <h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2>
2764
2765 <p>
2766 Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2767 Therefore, if a function <code>foo</code> calls an API function
2768 and this API function yields
2769 (directly or indirectly by calling another function that yields),
2770 Lua cannot return to <code>foo</code> any more,
2771 because the <code>longjmp</code> removes its frame from the C stack.
2772
2773
2774 <p>
2775 To avoid this kind of problem,
2776 Lua raises an error whenever it tries to yield across an API call,
2777 except for three functions:
2778 <a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
2779 All those functions receive a <em>continuation function</em>
2780 (as a parameter called <code>k</code>) to continue execution after a yield.
2781
2782
2783 <p>
2784 We need to set some terminology to explain continuations.
2785 We have a C function called from Lua which we will call
2786 the <em>original function</em>.
2787 This original function then calls one of those three functions in the C API,
2788 which we will call the <em>callee function</em>,
2789 that then yields the current thread.
2790 (This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2791 or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a>
2792 and the function called by them yields.)
2793
2794
2795 <p>
2796 Suppose the running thread yields while executing the callee function.
2797 After the thread resumes,
2798 it eventually will finish running the callee function.
2799 However,
2800 the callee function cannot return to the original function,
2801 because its frame in the C stack was destroyed by the yield.
2802 Instead, Lua calls a <em>continuation function</em>,
2803 which was given as an argument to the callee function.
2804 As the name implies,
2805 the continuation function should continue the task
2806 of the original function.
2807
2808
2809 <p>
2810 Lua treats the continuation function as if it were the original function.
2811 The continuation function receives the same Lua stack
2812 from the original function,
2813 in the same state it would be if the callee function had returned.
2814 (For instance,
2815 after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
2816 removed from the stack and replaced by the results from the call.)
2817 It also has the same upvalues.
2818 Whatever it returns is handled by Lua as if it were the return
2819 of the original function.
2820
2821
2822 <p>
2823 The only difference in the Lua state between the original function
2824 and its continuation is the result of a call to <a href="#lua_getctx"><code>lua_getctx</code></a>.
2825
2826
2827
2828
2829
2830 <h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
2831
2832 <p>
2833 Here we list all functions and types from the C&nbsp;API in
2834 alphabetical order.
2835 Each function has an indicator like this:
2836 <span class="apii">[-o, +p, <em>x</em>]</span>
2837
2838
2839 <p>
2840 The first field, <code>o</code>,
2841 is how many elements the function pops from the stack.
2842 The second field, <code>p</code>,
2843 is how many elements the function pushes onto the stack.
2844 (Any function always pushes its results after popping its arguments.)
2845 A field in the form <code>x|y</code> means the function can push (or pop)
2846 <code>x</code> or <code>y</code> elements,
2847 depending on the situation;
2848 an interrogation mark '<code>?</code>' means that
2849 we cannot know how many elements the function pops/pushes
2850 by looking only at its arguments
2851 (e.g., they may depend on what is on the stack).
2852 The third field, <code>x</code>,
2853 tells whether the function may throw errors:
2854 '<code>-</code>' means the function never throws any error;
2855 '<code>e</code>' means the function may throw errors;
2856 '<code>v</code>' means the function may throw an error on purpose.
2857
2858
2859
2860 <hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
2861 <span class="apii">[-0, +0, &ndash;]</span>
2862 <pre>int lua_absindex (lua_State *L, int idx);</pre>
2863
2864 <p>
2865 Converts the acceptable index <code>idx</code> into an absolute index
2866 (that is, one that does not depend on the stack top).
2867
2868
2869
2870
2871
2872 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2873 <pre>typedef void * (*lua_Alloc) (void *ud,
2874 void *ptr,
2875 size_t osize,
2876 size_t nsize);</pre>
2877
2878 <p>
2879 The type of the memory-allocation function used by Lua states.
2880 The allocator function must provide a
2881 functionality similar to <code>realloc</code>,
2882 but not exactly the same.
2883 Its arguments are
2884 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2885 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2886 <code>osize</code>, the original size of the block or some code about what
2887 is being allocated;
2888 <code>nsize</code>, the new size of the block.
2889
2890
2891 <p>
2892 When <code>ptr</code> is not <code>NULL</code>,
2893 <code>osize</code> is the size of the block pointed by <code>ptr</code>,
2894 that is, the size given when it was allocated or reallocated.
2895
2896
2897 <p>
2898 When <code>ptr</code> is <code>NULL</code>,
2899 <code>osize</code> encodes the kind of object that Lua is allocating.
2900 <code>osize</code> is any of
2901 <a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
2902 <a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when)
2903 Lua is creating a new object of that type.
2904 When <code>osize</code> is some other value,
2905 Lua is allocating memory for something else.
2906
2907
2908 <p>
2909 Lua assumes the following behavior from the allocator function:
2910
2911
2912 <p>
2913 When <code>nsize</code> is zero,
2914 the allocator should behave like <code>free</code>
2915 and return <code>NULL</code>.
2916
2917
2918 <p>
2919 When <code>nsize</code> is not zero,
2920 the allocator should behave like <code>realloc</code>.
2921 The allocator returns <code>NULL</code>
2922 if and only if it cannot fulfill the request.
2923 Lua assumes that the allocator never fails when
2924 <code>osize &gt;= nsize</code>.
2925
2926
2927 <p>
2928 Here is a simple implementation for the allocator function.
2929 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2930
2931 <pre>
2932 static void *l_alloc (void *ud, void *ptr, size_t osize,
2933 size_t nsize) {
2934 (void)ud; (void)osize; /* not used */
2935 if (nsize == 0) {
2936 free(ptr);
2937 return NULL;
2938 }
2939 else
2940 return realloc(ptr, nsize);
2941 }
2942 </pre><p>
2943 Note that Standard&nbsp;C ensures
2944 that <code>free(NULL)</code> has no effect and that
2945 <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2946 This code assumes that <code>realloc</code> does not fail when shrinking a block.
2947 (Although Standard&nbsp;C does not ensure this behavior,
2948 it seems to be a safe assumption.)
2949
2950
2951
2952
2953
2954 <hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
2955 <span class="apii">[-(2|1), +1, <em>e</em>]</span>
2956 <pre>void lua_arith (lua_State *L, int op);</pre>
2957
2958 <p>
2959 Performs an arithmetic operation over the two values
2960 (or one, in the case of negation)
2961 at the top of the stack,
2962 with the value at the top being the second operand,
2963 pops these values, and pushes the result of the operation.
2964 The function follows the semantics of the corresponding Lua operator
2965 (that is, it may call metamethods).
2966
2967
2968 <p>
2969 The value of <code>op</code> must be one of the following constants:
2970
2971 <ul>
2972
2973 <li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
2974 <li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
2975 <li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
2976 <li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs division (<code>/</code>)</li>
2977 <li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
2978 <li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
2979 <li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
2980
2981 </ul>
2982
2983
2984
2985
2986 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2987 <span class="apii">[-0, +0, &ndash;]</span>
2988 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2989
2990 <p>
2991 Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>).
2992
2993
2994
2995
2996
2997 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
2998 <span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
2999 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3000
3001 <p>
3002 Calls a function.
3003
3004
3005 <p>
3006 To call a function you must use the following protocol:
3007 first, the function to be called is pushed onto the stack;
3008 then, the arguments to the function are pushed
3009 in direct order;
3010 that is, the first argument is pushed first.
3011 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3012 <code>nargs</code> is the number of arguments that you pushed onto the stack.
3013 All arguments and the function value are popped from the stack
3014 when the function is called.
3015 The function results are pushed onto the stack when the function returns.
3016 The number of results is adjusted to <code>nresults</code>,
3017 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3018 In this case, all results from the function are pushed.
3019 Lua takes care that the returned values fit into the stack space.
3020 The function results are pushed onto the stack in direct order
3021 (the first result is pushed first),
3022 so that after the call the last result is on the top of the stack.
3023
3024
3025 <p>
3026 Any error inside the called function is propagated upwards
3027 (with a <code>longjmp</code>).
3028
3029
3030 <p>
3031 The following example shows how the host program can do the
3032 equivalent to this Lua code:
3033
3034 <pre>
3035 a = f("how", t.x, 14)
3036 </pre><p>
3037 Here it is in&nbsp;C:
3038
3039 <pre>
3040 lua_getglobal(L, "f"); /* function to be called */
3041 lua_pushstring(L, "how"); /* 1st argument */
3042 lua_getglobal(L, "t"); /* table to be indexed */
3043 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
3044 lua_remove(L, -2); /* remove 't' from the stack */
3045 lua_pushinteger(L, 14); /* 3rd argument */
3046 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
3047 lua_setglobal(L, "a"); /* set global 'a' */
3048 </pre><p>
3049 Note that the code above is "balanced":
3050 at its end, the stack is back to its original configuration.
3051 This is considered good programming practice.
3052
3053
3054
3055
3056
3057 <hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3058 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3059 <pre>void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
3060 lua_CFunction k);</pre>
3061
3062 <p>
3063 This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3064 but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3065
3066
3067
3068
3069
3070 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3071 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3072
3073 <p>
3074 Type for C&nbsp;functions.
3075
3076
3077 <p>
3078 In order to communicate properly with Lua,
3079 a C&nbsp;function must use the following protocol,
3080 which defines the way parameters and results are passed:
3081 a C&nbsp;function receives its arguments from Lua in its stack
3082 in direct order (the first argument is pushed first).
3083 So, when the function starts,
3084 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
3085 The first argument (if any) is at index 1
3086 and its last argument is at index <code>lua_gettop(L)</code>.
3087 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3088 in direct order (the first result is pushed first),
3089 and returns the number of results.
3090 Any other value in the stack below the results will be properly
3091 discarded by Lua.
3092 Like a Lua function, a C&nbsp;function called by Lua can also return
3093 many results.
3094
3095
3096 <p>
3097 As an example, the following function receives a variable number
3098 of numerical arguments and returns their average and sum:
3099
3100 <pre>
3101 static int foo (lua_State *L) {
3102 int n = lua_gettop(L); /* number of arguments */
3103 lua_Number sum = 0;
3104 int i;
3105 for (i = 1; i &lt;= n; i++) {
3106 if (!lua_isnumber(L, i)) {
3107 lua_pushstring(L, "incorrect argument");
3108 lua_error(L);
3109 }
3110 sum += lua_tonumber(L, i);
3111 }
3112 lua_pushnumber(L, sum/n); /* first result */
3113 lua_pushnumber(L, sum); /* second result */
3114 return 2; /* number of results */
3115 }
3116 </pre>
3117
3118
3119
3120
3121 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3122 <span class="apii">[-0, +0, &ndash;]</span>
3123 <pre>int lua_checkstack (lua_State *L, int extra);</pre>
3124
3125 <p>
3126 Ensures that there are at least <code>extra</code> free stack slots in the stack.
3127 It returns false if it cannot fulfill the request,
3128 because it would cause the stack to be larger than a fixed maximum size
3129 (typically at least a few thousand elements) or
3130 because it cannot allocate memory for the new stack size.
3131 This function never shrinks the stack;
3132 if the stack is already larger than the new size,
3133 it is left unchanged.
3134
3135
3136
3137
3138
3139 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3140 <span class="apii">[-0, +0, &ndash;]</span>
3141 <pre>void lua_close (lua_State *L);</pre>
3142
3143 <p>
3144 Destroys all objects in the given Lua state
3145 (calling the corresponding garbage-collection metamethods, if any)
3146 and frees all dynamic memory used by this state.
3147 On several platforms, you may not need to call this function,
3148 because all resources are naturally released when the host program ends.
3149 On the other hand, long-running programs that create multiple states,
3150 such as daemons or web servers,
3151 might need to close states as soon as they are not needed.
3152
3153
3154
3155
3156
3157 <hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3158 <span class="apii">[-0, +0, <em>e</em>]</span>
3159 <pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3160
3161 <p>
3162 Compares two Lua values.
3163 Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3164 when compared with the value at index <code>index2</code>,
3165 following the semantics of the corresponding Lua operator
3166 (that is, it may call metamethods).
3167 Otherwise returns&nbsp;0.
3168 Also returns&nbsp;0 if any of the indices is non valid.
3169
3170
3171 <p>
3172 The value of <code>op</code> must be one of the following constants:
3173
3174 <ul>
3175
3176 <li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3177 <li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3178 <li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3179
3180 </ul>
3181
3182
3183
3184
3185 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3186 <span class="apii">[-n, +1, <em>e</em>]</span>
3187 <pre>void lua_concat (lua_State *L, int n);</pre>
3188
3189 <p>
3190 Concatenates the <code>n</code> values at the top of the stack,
3191 pops them, and leaves the result at the top.
3192 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3193 (that is, the function does nothing);
3194 if <code>n</code> is 0, the result is the empty string.
3195 Concatenation is performed following the usual semantics of Lua
3196 (see <a href="#3.4.5">&sect;3.4.5</a>).
3197
3198
3199
3200
3201
3202 <hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3203 <span class="apii">[-0, +0, &ndash;]</span>
3204 <pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3205
3206 <p>
3207 Moves the element at index <code>fromidx</code>
3208 into the valid index <code>toidx</code>
3209 without shifting any element
3210 (therefore replacing the value at that position).
3211
3212
3213
3214
3215
3216 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3217 <span class="apii">[-0, +1, <em>e</em>]</span>
3218 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3219
3220 <p>
3221 Creates a new empty table and pushes it onto the stack.
3222 Parameter <code>narr</code> is a hint for how many elements the table
3223 will have as a sequence;
3224 parameter <code>nrec</code> is a hint for how many other elements
3225 the table will have.
3226 Lua may use these hints to preallocate memory for the new table.
3227 This pre-allocation is useful for performance when you know in advance
3228 how many elements the table will have.
3229 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3230
3231
3232
3233
3234
3235 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3236 <span class="apii">[-0, +0, <em>e</em>]</span>
3237 <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
3238
3239 <p>
3240 Dumps a function as a binary chunk.
3241 Receives a Lua function on the top of the stack
3242 and produces a binary chunk that,
3243 if loaded again,
3244 results in a function equivalent to the one dumped.
3245 As it produces parts of the chunk,
3246 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3247 with the given <code>data</code>
3248 to write them.
3249
3250
3251 <p>
3252 The value returned is the error code returned by the last
3253 call to the writer;
3254 0&nbsp;means no errors.
3255
3256
3257 <p>
3258 This function does not pop the Lua function from the stack.
3259
3260
3261
3262
3263
3264 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3265 <span class="apii">[-1, +0, <em>v</em>]</span>
3266 <pre>int lua_error (lua_State *L);</pre>
3267
3268 <p>
3269 Generates a Lua error.
3270 The error message (which can actually be a Lua value of any type)
3271 must be on the stack top.
3272 This function does a long jump,
3273 and therefore never returns
3274 (see <a href="#luaL_error"><code>luaL_error</code></a>).
3275
3276
3277
3278
3279
3280 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3281 <span class="apii">[-0, +0, <em>e</em>]</span>
3282 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
3283
3284 <p>
3285 Controls the garbage collector.
3286
3287
3288 <p>
3289 This function performs several tasks,
3290 according to the value of the parameter <code>what</code>:
3291
3292 <ul>
3293
3294 <li><b><code>LUA_GCSTOP</code>: </b>
3295 stops the garbage collector.
3296 </li>
3297
3298 <li><b><code>LUA_GCRESTART</code>: </b>
3299 restarts the garbage collector.
3300 </li>
3301
3302 <li><b><code>LUA_GCCOLLECT</code>: </b>
3303 performs a full garbage-collection cycle.
3304 </li>
3305
3306 <li><b><code>LUA_GCCOUNT</code>: </b>
3307 returns the current amount of memory (in Kbytes) in use by Lua.
3308 </li>
3309
3310 <li><b><code>LUA_GCCOUNTB</code>: </b>
3311 returns the remainder of dividing the current amount of bytes of
3312 memory in use by Lua by 1024.
3313 </li>
3314
3315 <li><b><code>LUA_GCSTEP</code>: </b>
3316 performs an incremental step of garbage collection.
3317 The step "size" is controlled by <code>data</code>
3318 (larger values mean more steps) in a non-specified way.
3319 If you want to control the step size
3320 you must experimentally tune the value of <code>data</code>.
3321 The function returns 1 if the step finished a
3322 garbage-collection cycle.
3323 </li>
3324
3325 <li><b><code>LUA_GCSETPAUSE</code>: </b>
3326 sets <code>data</code> as the new value
3327 for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>).
3328 The function returns the previous value of the pause.
3329 </li>
3330
3331 <li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3332 sets <code>data</code> as the new value for the <em>step multiplier</em> of
3333 the collector (see <a href="#2.5">&sect;2.5</a>).
3334 The function returns the previous value of the step multiplier.
3335 </li>
3336
3337 <li><b><code>LUA_GCISRUNNING</code>: </b>
3338 returns a boolean that tells whether the collector is running
3339 (i.e., not stopped).
3340 </li>
3341
3342 <li><b><code>LUA_GCGEN</code>: </b>
3343 changes the collector to generational mode
3344 (see <a href="#2.5">&sect;2.5</a>).
3345 </li>
3346
3347 <li><b><code>LUA_GCINC</code>: </b>
3348 changes the collector to incremental mode.
3349 This is the default mode.
3350 </li>
3351
3352 </ul>
3353
3354 <p>
3355 For more details about these options,
3356 see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3357
3358
3359
3360
3361
3362 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3363 <span class="apii">[-0, +0, &ndash;]</span>
3364 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3365
3366 <p>
3367 Returns the memory-allocation function of a given state.
3368 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3369 opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
3370
3371
3372
3373
3374
3375 <hr><h3><a name="lua_getctx"><code>lua_getctx</code></a></h3><p>
3376 <span class="apii">[-0, +0, &ndash;]</span>
3377 <pre>int lua_getctx (lua_State *L, int *ctx);</pre>
3378
3379 <p>
3380 This function is called by a continuation function (see <a href="#4.7">&sect;4.7</a>)
3381 to retrieve the status of the thread and a context information.
3382
3383
3384 <p>
3385 When called in the original function,
3386 <a href="#lua_getctx"><code>lua_getctx</code></a> always returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
3387 and does not change the value of its argument <code>ctx</code>.
3388 When called inside a continuation function,
3389 <a href="#lua_getctx"><code>lua_getctx</code></a> returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> and sets
3390 the value of <code>ctx</code> to be the context information
3391 (the value passed as the <code>ctx</code> argument
3392 to the callee together with the continuation function).
3393
3394
3395 <p>
3396 When the callee is <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3397 Lua may also call its continuation function
3398 to handle errors during the call.
3399 That is, upon an error in the function called by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3400 Lua may not return to the original function
3401 but instead may call the continuation function.
3402 In that case, a call to <a href="#lua_getctx"><code>lua_getctx</code></a> will return the error code
3403 (the value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>);
3404 the value of <code>ctx</code> will be set to the context information,
3405 as in the case of a yield.
3406
3407
3408
3409
3410
3411 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3412 <span class="apii">[-0, +1, <em>e</em>]</span>
3413 <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
3414
3415 <p>
3416 Pushes onto the stack the value <code>t[k]</code>,
3417 where <code>t</code> is the value at the given index.
3418 As in Lua, this function may trigger a metamethod
3419 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3420
3421
3422
3423
3424
3425 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3426 <span class="apii">[-0, +1, <em>e</em>]</span>
3427 <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
3428
3429 <p>
3430 Pushes onto the stack the value of the global <code>name</code>.
3431
3432
3433
3434
3435
3436 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3437 <span class="apii">[-0, +(0|1), &ndash;]</span>
3438 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
3439
3440 <p>
3441 Pushes onto the stack the metatable of the value at the given index.
3442 If the value does not have a metatable,
3443 the function returns&nbsp;0 and pushes nothing on the stack.
3444
3445
3446
3447
3448
3449 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
3450 <span class="apii">[-1, +1, <em>e</em>]</span>
3451 <pre>void lua_gettable (lua_State *L, int index);</pre>
3452
3453 <p>
3454 Pushes onto the stack the value <code>t[k]</code>,
3455 where <code>t</code> is the value at the given index
3456 and <code>k</code> is the value at the top of the stack.
3457
3458
3459 <p>
3460 This function pops the key from the stack
3461 (putting the resulting value in its place).
3462 As in Lua, this function may trigger a metamethod
3463 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3464
3465
3466
3467
3468
3469 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3470 <span class="apii">[-0, +0, &ndash;]</span>
3471 <pre>int lua_gettop (lua_State *L);</pre>
3472
3473 <p>
3474 Returns the index of the top element in the stack.
3475 Because indices start at&nbsp;1,