summaryrefslogtreecommitdiff
path: root/manual/manual.of
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-12-17 14:46:37 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-12-17 14:46:37 -0200
commit063d4e4543088e7a21965bda8ee5a0f952a9029e (patch)
tree6c3f2f8e98c26f071a94a32f9f2754396a66a9de /manual/manual.of
parente354c6355e7f48e087678ec49e340ca0696725b1 (diff)
downloadlua-5.3.5.tar.gz
lua-5.3.5.tar.bz2
lua-5.3.5.zip
Lua 5.3.5 ported to gitv5.3.5
This is the first commit for the branch Lua 5.3. All source files were copied from the official distribution of 5.3.5 in the Lua site. The test files are the same of 5.3.4. The manual came from the previous RCS repository, revision 1.167.1.2.
Diffstat (limited to 'manual/manual.of')
-rw-r--r--manual/manual.of8630
1 files changed, 8630 insertions, 0 deletions
diff --git a/manual/manual.of b/manual/manual.of
new file mode 100644
index 00000000..5b2abbe7
--- /dev/null
+++ b/manual/manual.of
@@ -0,0 +1,8630 @@
1@Ci{$Id: manual.of,v 1.167.1.2 2018/06/26 15:49:07 roberto Exp $}
2@C{[(-------------------------------------------------------------------------}
3@manual{
4
5@sect1{@title{Introduction}
6
7Lua is a powerful, efficient, lightweight, embeddable scripting language.
8It supports procedural programming,
9object-oriented programming, functional programming,
10data-driven programming, and data description.
11
12Lua combines simple procedural syntax with powerful data description
13constructs based on associative arrays and extensible semantics.
14Lua is dynamically typed,
15runs by interpreting bytecode with a register-based
16virtual machine,
17and has automatic memory management with
18incremental garbage collection,
19making it ideal for configuration, scripting,
20and rapid prototyping.
21
22Lua is implemented as a library, written in @emphx{clean C},
23the common subset of @N{Standard C} and C++.
24The Lua distribution includes a host program called @id{lua},
25which uses the Lua library to offer a complete,
26standalone Lua interpreter,
27for interactive or batch use.
28Lua is intended to be used both as a powerful, lightweight,
29embeddable scripting language for any program that needs one,
30and as a powerful but lightweight and efficient stand-alone language.
31
32As an extension language, Lua has no notion of a @Q{main} program:
33it works @emph{embedded} in a host client,
34called the @emph{embedding program} or simply the @emphx{host}.
35(Frequently, this host is the stand-alone @id{lua} program.)
36The host program can invoke functions to execute a piece of Lua code,
37can write and read Lua variables,
38and can register @N{C functions} to be called by Lua code.
39Through the use of @N{C functions}, Lua can be augmented to cope with
40a wide range of different domains,
41thus creating customized programming languages sharing a syntactical framework.
42
43Lua is free software,
44and is provided as usual with no guarantees,
45as stated in its license.
46The implementation described in this manual is available
47at Lua's official web site, @id{www.lua.org}.
48
49Like any other reference manual,
50this document is dry in places.
51For a discussion of the decisions behind the design of Lua,
52see the technical papers available at Lua's web site.
53For a detailed introduction to programming in Lua,
54see Roberto's book, @emphx{Programming in Lua}.
55
56}
57
58
59@C{-------------------------------------------------------------------------}
60@sect1{basic| @title{Basic Concepts}
61
62This section describes the basic concepts of the language.
63
64@sect2{TypesSec| @title{Values and Types}
65
66Lua is a @emph{dynamically typed language}.
67This means that
68variables do not have types; only values do.
69There are no type definitions in the language.
70All values carry their own type.
71
72All values in Lua are @emph{first-class values}.
73This means that all values can be stored in variables,
74passed as arguments to other functions, and returned as results.
75
76There are eight @x{basic types} in Lua:
77@def{nil}, @def{boolean}, @def{number},
78@def{string}, @def{function}, @def{userdata},
79@def{thread}, and @def{table}.
80The type @emph{nil} has one single value, @nil,
81whose main property is to be different from any other value;
82it usually represents the absence of a useful value.
83The type @emph{boolean} has two values, @false and @true.
84Both @nil and @false make a condition false;
85any other value makes it true.
86The type @emph{number} represents both
87integer numbers and real (floating-point) numbers.
88The type @emph{string} represents immutable sequences of bytes.
89@index{eight-bit clean}
90Lua is 8-bit clean:
91strings can contain any 8-bit value,
92including @x{embedded zeros} (@Char{\0}).
93Lua is also encoding-agnostic;
94it makes no assumptions about the contents of a string.
95
96The type @emph{number} uses two internal representations,
97or two @x{subtypes},
98one called @def{integer} and the other called @def{float}.
99Lua has explicit rules about when each representation is used,
100but it also converts between them automatically as needed @see{coercion}.
101Therefore,
102the programmer may choose to mostly ignore the difference
103between integers and floats
104or to assume complete control over the representation of each number.
105Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
106but you can also compile Lua so that it
107uses 32-bit integers and/or single-precision (32-bit) floats.
108The option with 32 bits for both integers and floats
109is particularly attractive
110for small machines and embedded systems.
111(See macro @id{LUA_32BITS} in file @id{luaconf.h}.)
112
113Lua can call (and manipulate) functions written in Lua and
114functions written in C @see{functioncall}.
115Both are represented by the type @emph{function}.
116
117The type @emph{userdata} is provided to allow arbitrary @N{C data} to
118be stored in Lua variables.
119A userdata value represents a block of raw memory.
120There are two kinds of userdata:
121@emphx{full userdata},
122which is an object with a block of memory managed by Lua,
123and @emphx{light userdata},
124which is simply a @N{C pointer} value.
125Userdata has no predefined operations in Lua,
126except assignment and identity test.
127By using @emph{metatables},
128the programmer can define operations for full userdata values
129@see{metatable}.
130Userdata values cannot be created or modified in Lua,
131only through the @N{C API}.
132This guarantees the integrity of data owned by the host program.
133
134The type @def{thread} represents independent threads of execution
135and it is used to implement coroutines @see{coroutine}.
136Lua threads are not related to operating-system threads.
137Lua supports coroutines on all systems,
138even those that do not support threads natively.
139
140The type @emph{table} implements @x{associative arrays},
141that is, @x{arrays} that can have as indices not only numbers,
142but any Lua value except @nil and @x{NaN}.
143(@emphx{Not a Number} is a special value used to represent
144undefined or unrepresentable numerical results, such as @T{0/0}.)
145Tables can be @emph{heterogeneous};
146that is, they can contain values of all types (except @nil).
147Any key with value @nil is not considered part of the table.
148Conversely, any key that is not part of a table has
149an associated value @nil.
150
151Tables are the sole data-structuring mechanism in Lua;
152they can be used to represent ordinary arrays, lists,
153symbol tables, sets, records, graphs, trees, etc.
154To represent @x{records}, Lua uses the field name as an index.
155The language supports this representation by
156providing @id{a.name} as syntactic sugar for @T{a["name"]}.
157There are several convenient ways to create tables in Lua
158@see{tableconstructor}.
159
160Like indices,
161the values of table fields can be of any type.
162In particular,
163because functions are first-class values,
164table fields can contain functions.
165Thus tables can also carry @emph{methods} @see{func-def}.
166
167The indexing of tables follows
168the definition of raw equality in the language.
169The expressions @T{a[i]} and @T{a[j]}
170denote the same table element
171if and only if @id{i} and @id{j} are raw equal
172(that is, equal without metamethods).
173In particular, floats with integral values
174are equal to their respective integers
175(e.g., @T{1.0 == 1}).
176To avoid ambiguities,
177any float with integral value used as a key
178is converted to its respective integer.
179For instance, if you write @T{a[2.0] = true},
180the actual key inserted into the table will be the
181integer @T{2}.
182(On the other hand,
1832 and @St{2} are different Lua values and therefore
184denote different table entries.)
185
186
187Tables, functions, threads, and (full) userdata values are @emph{objects}:
188variables do not actually @emph{contain} these values,
189only @emph{references} to them.
190Assignment, parameter passing, and function returns
191always manipulate references to such values;
192these operations do not imply any kind of copy.
193
194The library function @Lid{type} returns a string describing the type
195of a given value @see{predefined}.
196
197}
198
199@sect2{globalenv| @title{Environments and the Global Environment}
200
201As will be discussed in @refsec{variables} and @refsec{assignment},
202any reference to a free name
203(that is, a name not bound to any declaration) @id{var}
204is syntactically translated to @T{_ENV.var}.
205Moreover, every chunk is compiled in the scope of
206an external local variable named @id{_ENV} @see{chunks},
207so @id{_ENV} itself is never a free name in a chunk.
208
209Despite the existence of this external @id{_ENV} variable and
210the translation of free names,
211@id{_ENV} is a completely regular name.
212In particular,
213you can define new variables and parameters with that name.
214Each reference to a free name uses the @id{_ENV} that is
215visible at that point in the program,
216following the usual visibility rules of Lua @see{visibility}.
217
218Any table used as the value of @id{_ENV} is called an @def{environment}.
219
220Lua keeps a distinguished environment called the @def{global environment}.
221This value is kept at a special index in the C registry @see{registry}.
222In Lua, the global variable @Lid{_G} is initialized with this same value.
223(@Lid{_G} is never used internally.)
224
225When Lua loads a chunk,
226the default value for its @id{_ENV} upvalue
227is the global environment @seeF{load}.
228Therefore, by default,
229free names in Lua code refer to entries in the global environment
230(and, therefore, they are also called @def{global variables}).
231Moreover, all standard libraries are loaded in the global environment
232and some functions there operate on that environment.
233You can use @Lid{load} (or @Lid{loadfile})
234to load a chunk with a different environment.
235(In C, you have to load the chunk and then change the value
236of its first upvalue.)
237
238}
239
240@sect2{error| @title{Error Handling}
241
242Because Lua is an embedded extension language,
243all Lua actions start from @N{C code} in the host program
244calling a function from the Lua library.
245(When you use Lua standalone,
246the @id{lua} application is the host program.)
247Whenever an error occurs during
248the compilation or execution of a Lua chunk,
249control returns to the host,
250which can take appropriate measures
251(such as printing an error message).
252
253Lua code can explicitly generate an error by calling the
254@Lid{error} function.
255If you need to catch errors in Lua,
256you can use @Lid{pcall} or @Lid{xpcall}
257to call a given function in @emphx{protected mode}.
258
259Whenever there is an error,
260an @def{error object} (also called an @def{error message})
261is propagated with information about the error.
262Lua itself only generates errors whose error object is a string,
263but programs may generate errors with
264any value as the error object.
265It is up to the Lua program or its host to handle such error objects.
266
267
268When you use @Lid{xpcall} or @Lid{lua_pcall},
269you may give a @def{message handler}
270to be called in case of errors.
271This function is called with the original error object
272and returns a new error object.
273It is called before the error unwinds the stack,
274so that it can gather more information about the error,
275for instance by inspecting the stack and creating a stack traceback.
276This message handler is still protected by the protected call;
277so, an error inside the message handler
278will call the message handler again.
279If this loop goes on for too long,
280Lua breaks it and returns an appropriate message.
281(The message handler is called only for regular runtime errors.
282It is not called for memory-allocation errors
283nor for errors while running finalizers.)
284
285}
286
287@sect2{metatable| @title{Metatables and Metamethods}
288
289Every value in Lua can have a @emph{metatable}.
290This @def{metatable} is an ordinary Lua table
291that defines the behavior of the original value
292under certain special operations.
293You can change several aspects of the behavior
294of operations over a value by setting specific fields in its metatable.
295For instance, when a non-numeric value is the operand of an addition,
296Lua checks for a function in the field @St{__add} of the value's metatable.
297If it finds one,
298Lua calls this function to perform the addition.
299
300The key for each event in a metatable is a string
301with the event name prefixed by two underscores;
302the corresponding values are called @def{metamethods}.
303In the previous example, the key is @St{__add}
304and the metamethod is the function that performs the addition.
305Unless stated otherwise,
306metamethods should be function values.
307
308You can query the metatable of any value
309using the @Lid{getmetatable} function.
310Lua queries metamethods in metatables using a raw access @seeF{rawget}.
311So, to retrieve the metamethod for event @id{ev} in object @id{o},
312Lua does the equivalent to the following code:
313@verbatim{
314rawget(getmetatable(@rep{o}) or {}, "__@rep{ev}")
315}
316
317You can replace the metatable of tables
318using the @Lid{setmetatable} function.
319You cannot change the metatable of other types from Lua code
320(except by using the @link{debuglib|debug library});
321you should use the @N{C API} for that.
322
323Tables and full userdata have individual metatables
324(although multiple tables and userdata can share their metatables).
325Values of all other types share one single metatable per type;
326that is, there is one single metatable for all numbers,
327one for all strings, etc.
328By default, a value has no metatable,
329but the string library sets a metatable for the string type @see{strlib}.
330
331A metatable controls how an object behaves in
332arithmetic operations, bitwise operations,
333order comparisons, concatenation, length operation, calls, and indexing.
334A metatable also can define a function to be called
335when a userdata or a table is @link{GC|garbage collected}.
336
337For the unary operators (negation, length, and bitwise NOT),
338the metamethod is computed and called with a dummy second operand,
339equal to the first one.
340This extra operand is only to simplify Lua's internals
341(by making these operators behave like a binary operation)
342and may be removed in future versions.
343(For most uses this extra operand is irrelevant.)
344
345A detailed list of events controlled by metatables is given next.
346Each operation is identified by its corresponding key.
347
348@description{
349
350@item{@idx{__add}|
351the addition (@T{+}) operation.
352If any operand for an addition is not a number
353(nor a string coercible to a number),
354Lua will try to call a metamethod.
355First, Lua will check the first operand (even if it is valid).
356If that operand does not define a metamethod for @idx{__add},
357then Lua will check the second operand.
358If Lua can find a metamethod,
359it calls the metamethod with the two operands as arguments,
360and the result of the call
361(adjusted to one value)
362is the result of the operation.
363Otherwise,
364it raises an error.
365}
366
367@item{@idx{__sub}|
368the subtraction (@T{-}) operation.
369Behavior similar to the addition operation.
370}
371
372@item{@idx{__mul}|
373the multiplication (@T{*}) operation.
374Behavior similar to the addition operation.
375}
376
377@item{@idx{__div}|
378the division (@T{/}) operation.
379Behavior similar to the addition operation.
380}
381
382@item{@idx{__mod}|
383the modulo (@T{%}) operation.
384Behavior similar to the addition operation.
385}
386
387@item{@idx{__pow}|
388the exponentiation (@T{^}) operation.
389Behavior similar to the addition operation.
390}
391
392@item{@idx{__unm}|
393the negation (unary @T{-}) operation.
394Behavior similar to the addition operation.
395}
396
397@item{@idx{__idiv}|
398the floor division (@T{//}) operation.
399Behavior similar to the addition operation.
400}
401
402@item{@idx{__band}|
403the bitwise AND (@T{&}) operation.
404Behavior similar to the addition operation,
405except that Lua will try a metamethod
406if any operand is neither an integer
407nor a value coercible to an integer @see{coercion}.
408}
409
410@item{@idx{__bor}|
411the bitwise OR (@T{|}) operation.
412Behavior similar to the bitwise AND operation.
413}
414
415@item{@idx{__bxor}|
416the bitwise exclusive OR (binary @T{~}) operation.
417Behavior similar to the bitwise AND operation.
418}
419
420@item{@idx{__bnot}|
421the bitwise NOT (unary @T{~}) operation.
422Behavior similar to the bitwise AND operation.
423}
424
425@item{@idx{__shl}|
426the bitwise left shift (@T{<<}) operation.
427Behavior similar to the bitwise AND operation.
428}
429
430@item{@idx{__shr}|
431the bitwise right shift (@T{>>}) operation.
432Behavior similar to the bitwise AND operation.
433}
434
435@item{@idx{__concat}|
436the concatenation (@T{..}) operation.
437Behavior similar to the addition operation,
438except that Lua will try a metamethod
439if any operand is neither a string nor a number
440(which is always coercible to a string).
441}
442
443@item{@idx{__len}|
444the length (@T{#}) operation.
445If the object is not a string,
446Lua will try its metamethod.
447If there is a metamethod,
448Lua calls it with the object as argument,
449and the result of the call
450(always adjusted to one value)
451is the result of the operation.
452If there is no metamethod but the object is a table,
453then Lua uses the table length operation @see{len-op}.
454Otherwise, Lua raises an error.
455}
456
457@item{@idx{__eq}|
458the equal (@T{==}) operation.
459Behavior similar to the addition operation,
460except that Lua will try a metamethod only when the values
461being compared are either both tables or both full userdata
462and they are not primitively equal.
463The result of the call is always converted to a boolean.
464}
465
466@item{@idx{__lt}|
467the less than (@T{<}) operation.
468Behavior similar to the addition operation,
469except that Lua will try a metamethod only when the values
470being compared are neither both numbers nor both strings.
471The result of the call is always converted to a boolean.
472}
473
474@item{@idx{__le}|
475the less equal (@T{<=}) operation.
476Unlike other operations,
477the less-equal operation can use two different events.
478First, Lua looks for the @idx{__le} metamethod in both operands,
479like in the less than operation.
480If it cannot find such a metamethod,
481then it will try the @idx{__lt} metamethod,
482assuming that @T{a <= b} is equivalent to @T{not (b < a)}.
483As with the other comparison operators,
484the result is always a boolean.
485(This use of the @idx{__lt} event can be removed in future versions;
486it is also slower than a real @idx{__le} metamethod.)
487}
488
489@item{@idx{__index}|
490The indexing access operation @T{table[key]}.
491This event happens when @id{table} is not a table or
492when @id{key} is not present in @id{table}.
493The metamethod is looked up in @id{table}.
494
495Despite the name,
496the metamethod for this event can be either a function or a table.
497If it is a function,
498it is called with @id{table} and @id{key} as arguments,
499and the result of the call
500(adjusted to one value)
501is the result of the operation.
502If it is a table,
503the final result is the result of indexing this table with @id{key}.
504(This indexing is regular, not raw,
505and therefore can trigger another metamethod.)
506}
507
508@item{@idx{__newindex}|
509The indexing assignment @T{table[key] = value}.
510Like the index event,
511this event happens when @id{table} is not a table or
512when @id{key} is not present in @id{table}.
513The metamethod is looked up in @id{table}.
514
515Like with indexing,
516the metamethod for this event can be either a function or a table.
517If it is a function,
518it is called with @id{table}, @id{key}, and @id{value} as arguments.
519If it is a table,
520Lua does an indexing assignment to this table with the same key and value.
521(This assignment is regular, not raw,
522and therefore can trigger another metamethod.)
523
524Whenever there is a @idx{__newindex} metamethod,
525Lua does not perform the primitive assignment.
526(If necessary,
527the metamethod itself can call @Lid{rawset}
528to do the assignment.)
529}
530
531@item{@idx{__call}|
532The call operation @T{func(args)}.
533This event happens when Lua tries to call a non-function value
534(that is, @id{func} is not a function).
535The metamethod is looked up in @id{func}.
536If present,
537the metamethod is called with @id{func} as its first argument,
538followed by the arguments of the original call (@id{args}).
539All results of the call
540are the result of the operation.
541(This is the only metamethod that allows multiple results.)
542}
543
544}
545
546It is a good practice to add all needed metamethods to a table
547before setting it as a metatable of some object.
548In particular, the @idx{__gc} metamethod works only when this order
549is followed @see{finalizers}.
550
551Because metatables are regular tables,
552they can contain arbitrary fields,
553not only the event names defined above.
554Some functions in the standard library
555(e.g., @Lid{tostring})
556use other fields in metatables for their own purposes.
557
558}
559
560@sect2{GC| @title{Garbage Collection}
561
562Lua performs automatic memory management.
563This means that
564you do not have to worry about allocating memory for new objects
565or freeing it when the objects are no longer needed.
566Lua manages memory automatically by running
567a @def{garbage collector} to collect all @emph{dead objects}
568(that is, objects that are no longer accessible from Lua).
569All memory used by Lua is subject to automatic management:
570strings, tables, userdata, functions, threads, internal structures, etc.
571
572Lua implements an incremental mark-and-sweep collector.
573It uses two numbers to control its garbage-collection cycles:
574the @def{garbage-collector pause} and
575the @def{garbage-collector step multiplier}.
576Both use percentage points as units
577(e.g., a value of 100 means an internal value of 1).
578
579The garbage-collector pause
580controls how long the collector waits before starting a new cycle.
581Larger values make the collector less aggressive.
582Values smaller than 100 mean the collector will not wait to
583start a new cycle.
584A value of 200 means that the collector waits for the total memory in use
585to double before starting a new cycle.
586
587The garbage-collector step multiplier
588controls the relative speed of the collector relative to
589memory allocation.
590Larger values make the collector more aggressive but also increase
591the size of each incremental step.
592You should not use values smaller than 100,
593because they make the collector too slow and
594can result in the collector never finishing a cycle.
595The default is 200,
596which means that the collector runs at @Q{twice}
597the speed of memory allocation.
598
599If you set the step multiplier to a very large number
600(larger than 10% of the maximum number of
601bytes that the program may use),
602the collector behaves like a stop-the-world collector.
603If you then set the pause to 200,
604the collector behaves as in old Lua versions,
605doing a complete collection every time Lua doubles its
606memory usage.
607
608You can change these numbers by calling @Lid{lua_gc} in C
609or @Lid{collectgarbage} in Lua.
610You can also use these functions to control
611the collector directly (e.g., stop and restart it).
612
613
614@sect3{finalizers| @title{Garbage-Collection Metamethods}
615
616You can set garbage-collector metamethods for tables
617and, using the @N{C API},
618for full userdata @see{metatable}.
619These metamethods are also called @def{finalizers}.
620Finalizers allow you to coordinate Lua's garbage collection
621with external resource management
622(such as closing files, network or database connections,
623or freeing your own memory).
624
625For an object (table or userdata) to be finalized when collected,
626you must @emph{mark} it for finalization.
627@index{mark (for finalization)}
628You mark an object for finalization when you set its metatable
629and the metatable has a field indexed by the string @St{__gc}.
630Note that if you set a metatable without a @idx{__gc} field
631and later create that field in the metatable,
632the object will not be marked for finalization.
633
634When a marked object becomes garbage,
635it is not collected immediately by the garbage collector.
636Instead, Lua puts it in a list.
637After the collection,
638Lua goes through that list.
639For each object in the list,
640it checks the object's @idx{__gc} metamethod:
641If it is a function,
642Lua calls it with the object as its single argument;
643if the metamethod is not a function,
644Lua simply ignores it.
645
646At the end of each garbage-collection cycle,
647the finalizers for objects are called in
648the reverse order that the objects were marked for finalization,
649among those collected in that cycle;
650that is, the first finalizer to be called is the one associated
651with the object marked last in the program.
652The execution of each finalizer may occur at any point during
653the execution of the regular code.
654
655Because the object being collected must still be used by the finalizer,
656that object (and other objects accessible only through it)
657must be @emph{resurrected} by Lua.@index{resurrection}
658Usually, this resurrection is transient,
659and the object memory is freed in the next garbage-collection cycle.
660However, if the finalizer stores the object in some global place
661(e.g., a global variable),
662then the resurrection is permanent.
663Moreover, if the finalizer marks a finalizing object for finalization again,
664its finalizer will be called again in the next cycle where the
665object is unreachable.
666In any case,
667the object memory is freed only in a GC cycle where
668the object is unreachable and not marked for finalization.
669
670When you close a state @seeF{lua_close},
671Lua calls the finalizers of all objects marked for finalization,
672following the reverse order that they were marked.
673If any finalizer marks objects for collection during that phase,
674these marks have no effect.
675
676}
677
678@sect3{weak-table| @title{Weak Tables}
679
680A @def{weak table} is a table whose elements are
681@def{weak references}.
682A weak reference is ignored by the garbage collector.
683In other words,
684if the only references to an object are weak references,
685then the garbage collector will collect that object.
686
687A weak table can have weak keys, weak values, or both.
688A table with weak values allows the collection of its values,
689but prevents the collection of its keys.
690A table with both weak keys and weak values allows the collection of
691both keys and values.
692In any case, if either the key or the value is collected,
693the whole pair is removed from the table.
694The weakness of a table is controlled by the
695@idx{__mode} field of its metatable.
696If the @idx{__mode} field is a string containing the @N{character @Char{k}},
697the keys in the table are weak.
698If @idx{__mode} contains @Char{v},
699the values in the table are weak.
700
701A table with weak keys and strong values
702is also called an @def{ephemeron table}.
703In an ephemeron table,
704a value is considered reachable only if its key is reachable.
705In particular,
706if the only reference to a key comes through its value,
707the pair is removed.
708
709Any change in the weakness of a table may take effect only
710at the next collect cycle.
711In particular, if you change the weakness to a stronger mode,
712Lua may still collect some items from that table
713before the change takes effect.
714
715Only objects that have an explicit construction
716are removed from weak tables.
717Values, such as numbers and @x{light @N{C functions}},
718are not subject to garbage collection,
719and therefore are not removed from weak tables
720(unless their associated values are collected).
721Although strings are subject to garbage collection,
722they do not have an explicit construction,
723and therefore are not removed from weak tables.
724
725Resurrected objects
726(that is, objects being finalized
727and objects accessible only through objects being finalized)
728have a special behavior in weak tables.
729They are removed from weak values before running their finalizers,
730but are removed from weak keys only in the next collection
731after running their finalizers, when such objects are actually freed.
732This behavior allows the finalizer to access properties
733associated with the object through weak tables.
734
735If a weak table is among the resurrected objects in a collection cycle,
736it may not be properly cleared until the next cycle.
737
738}
739
740}
741
742@sect2{coroutine| @title{Coroutines}
743
744Lua supports coroutines,
745also called @emphx{collaborative multithreading}.
746A coroutine in Lua represents an independent thread of execution.
747Unlike threads in multithread systems, however,
748a coroutine only suspends its execution by explicitly calling
749a yield function.
750
751You create a coroutine by calling @Lid{coroutine.create}.
752Its sole argument is a function
753that is the main function of the coroutine.
754The @id{create} function only creates a new coroutine and
755returns a handle to it (an object of type @emph{thread});
756it does not start the coroutine.
757
758You execute a coroutine by calling @Lid{coroutine.resume}.
759When you first call @Lid{coroutine.resume},
760passing as its first argument
761a thread returned by @Lid{coroutine.create},
762the coroutine starts its execution by
763calling its main function.
764Extra arguments passed to @Lid{coroutine.resume} are passed
765as arguments to that function.
766After the coroutine starts running,
767it runs until it terminates or @emph{yields}.
768
769A coroutine can terminate its execution in two ways:
770normally, when its main function returns
771(explicitly or implicitly, after the last instruction);
772and abnormally, if there is an unprotected error.
773In case of normal termination,
774@Lid{coroutine.resume} returns @true,
775plus any values returned by the coroutine main function.
776In case of errors, @Lid{coroutine.resume} returns @false
777plus an error object.
778
779A coroutine yields by calling @Lid{coroutine.yield}.
780When a coroutine yields,
781the corresponding @Lid{coroutine.resume} returns immediately,
782even if the yield happens inside nested function calls
783(that is, not in the main function,
784but in a function directly or indirectly called by the main function).
785In the case of a yield, @Lid{coroutine.resume} also returns @true,
786plus any values passed to @Lid{coroutine.yield}.
787The next time you resume the same coroutine,
788it continues its execution from the point where it yielded,
789with the call to @Lid{coroutine.yield} returning any extra
790arguments passed to @Lid{coroutine.resume}.
791
792Like @Lid{coroutine.create},
793the @Lid{coroutine.wrap} function also creates a coroutine,
794but instead of returning the coroutine itself,
795it returns a function that, when called, resumes the coroutine.
796Any arguments passed to this function
797go as extra arguments to @Lid{coroutine.resume}.
798@Lid{coroutine.wrap} returns all the values returned by @Lid{coroutine.resume},
799except the first one (the boolean error code).
800Unlike @Lid{coroutine.resume},
801@Lid{coroutine.wrap} does not catch errors;
802any error is propagated to the caller.
803
804As an example of how coroutines work,
805consider the following code:
806@verbatim{
807function foo (a)
808 print("foo", a)
809 return coroutine.yield(2*a)
810end
811
812co = coroutine.create(function (a,b)
813 print("co-body", a, b)
814 local r = foo(a+1)
815 print("co-body", r)
816 local r, s = coroutine.yield(a+b, a-b)
817 print("co-body", r, s)
818 return b, "end"
819end)
820
821print("main", coroutine.resume(co, 1, 10))
822print("main", coroutine.resume(co, "r"))
823print("main", coroutine.resume(co, "x", "y"))
824print("main", coroutine.resume(co, "x", "y"))
825}
826When you run it, it produces the following output:
827@verbatim{
828co-body 1 10
829foo 2
830main true 4
831co-body r
832main true 11 -9
833co-body x y
834main true 10 end
835main false cannot resume dead coroutine
836}
837
838You can also create and manipulate coroutines through the C API:
839see functions @Lid{lua_newthread}, @Lid{lua_resume},
840and @Lid{lua_yield}.
841
842}
843
844}
845
846
847@C{-------------------------------------------------------------------------}
848@sect1{language| @title{The Language}
849
850This section describes the lexis, the syntax, and the semantics of Lua.
851In other words,
852this section describes
853which tokens are valid,
854how they can be combined,
855and what their combinations mean.
856
857Language constructs will be explained using the usual extended BNF notation,
858in which
859@N{@bnfrep{@rep{a}} means 0} or more @rep{a}'s, and
860@N{@bnfopt{@rep{a}} means} an optional @rep{a}.
861Non-terminals are shown like @bnfNter{non-terminal},
862keywords are shown like @rw{kword},
863and other terminal symbols are shown like @bnfter{=}.
864The complete syntax of Lua can be found in @refsec{BNF}
865at the end of this manual.
866
867@sect2{lexical| @title{Lexical Conventions}
868
869Lua is a @x{free-form} language.
870It ignores spaces (including new lines) and comments
871between lexical elements (@x{tokens}),
872except as delimiters between @x{names} and @x{keywords}.
873
874@def{Names}
875(also called @def{identifiers})
876in Lua can be any string of letters,
877digits, and underscores,
878not beginning with a digit and
879not being a reserved word.
880Identifiers are used to name variables, table fields, and labels.
881
882The following @def{keywords} are reserved
883and cannot be used as names:
884@index{reserved words}
885@verbatim{
886and break do else elseif end
887false for function goto if in
888local nil not or repeat return
889then true until while
890}
891
892Lua is a case-sensitive language:
893@id{and} is a reserved word, but @id{And} and @id{AND}
894are two different, valid names.
895As a convention,
896programs should avoid creating
897names that start with an underscore followed by
898one or more uppercase letters (such as @Lid{_VERSION}).
899
900The following strings denote other @x{tokens}:
901@verbatim{
902+ - * / % ^ #
903& ~ | << >> //
904== ~= <= >= < > =
905( ) { } [ ] ::
906; : , . .. ...
907}
908
909A @def{short literal string}
910can be delimited by matching single or double quotes,
911and can contain the following C-like escape sequences:
912@Char{\a} (bell),
913@Char{\b} (backspace),
914@Char{\f} (form feed),
915@Char{\n} (newline),
916@Char{\r} (carriage return),
917@Char{\t} (horizontal tab),
918@Char{\v} (vertical tab),
919@Char{\\} (backslash),
920@Char{\"} (quotation mark [double quote]),
921and @Char{\'} (apostrophe [single quote]).
922A backslash followed by a line break
923results in a newline in the string.
924The escape sequence @Char{\z} skips the following span
925of white-space characters,
926including line breaks;
927it is particularly useful to break and indent a long literal string
928into multiple lines without adding the newlines and spaces
929into the string contents.
930A short literal string cannot contain unescaped line breaks
931nor escapes not forming a valid escape sequence.
932
933We can specify any byte in a short literal string by its numeric value
934(including @x{embedded zeros}).
935This can be done
936with the escape sequence @T{\x@rep{XX}},
937where @rep{XX} is a sequence of exactly two hexadecimal digits,
938or with the escape sequence @T{\@rep{ddd}},
939where @rep{ddd} is a sequence of up to three decimal digits.
940(Note that if a decimal escape sequence is to be followed by a digit,
941it must be expressed using exactly three digits.)
942
943The @x{UTF-8} encoding of a @x{Unicode} character
944can be inserted in a literal string with
945the escape sequence @T{\u{@rep{XXX}}}
946(note the mandatory enclosing brackets),
947where @rep{XXX} is a sequence of one or more hexadecimal digits
948representing the character code point.
949
950Literal strings can also be defined using a long format
951enclosed by @def{long brackets}.
952We define an @def{opening long bracket of level @rep{n}} as an opening
953square bracket followed by @rep{n} equal signs followed by another
954opening square bracket.
955So, an opening long bracket of @N{level 0} is written as @T{[[}, @C{]]}
956an opening long bracket of @N{level 1} is written as @T{[=[}, @C{]]}
957and so on.
958A @emph{closing long bracket} is defined similarly;
959for instance,
960a closing long bracket of @N{level 4} is written as @C{[[} @T{]====]}.
961A @def{long literal} starts with an opening long bracket of any level and
962ends at the first closing long bracket of the same level.
963It can contain any text except a closing bracket of the same level.
964Literals in this bracketed form can run for several lines,
965do not interpret any escape sequences,
966and ignore long brackets of any other level.
967Any kind of end-of-line sequence
968(carriage return, newline, carriage return followed by newline,
969or newline followed by carriage return)
970is converted to a simple newline.
971
972For convenience,
973when the opening long bracket is immediately followed by a newline,
974the newline is not included in the string.
975As an example, in a system using ASCII
976(in which @Char{a} is coded @N{as 97},
977newline is coded @N{as 10}, and @Char{1} is coded @N{as 49}),
978the five literal strings below denote the same string:
979@verbatim{
980a = 'alo\n123"'
981a = "alo\n123\""
982a = '\97lo\10\04923"'
983a = [[alo
984123"]]
985a = [==[
986alo
987123"]==]
988}
989
990Any byte in a literal string not
991explicitly affected by the previous rules represents itself.
992However, Lua opens files for parsing in text mode,
993and the system file functions may have problems with
994some control characters.
995So, it is safer to represent
996non-text data as a quoted literal with
997explicit escape sequences for the non-text characters.
998
999A @def{numeric constant} (or @def{numeral})
1000can be written with an optional fractional part
1001and an optional decimal exponent,
1002marked by a letter @Char{e} or @Char{E}.
1003Lua also accepts @x{hexadecimal constants},
1004which start with @T{0x} or @T{0X}.
1005Hexadecimal constants also accept an optional fractional part
1006plus an optional binary exponent,
1007marked by a letter @Char{p} or @Char{P}.
1008A numeric constant with a radix point or an exponent
1009denotes a float;
1010otherwise,
1011if its value fits in an integer,
1012it denotes an integer.
1013Examples of valid integer constants are
1014@verbatim{
10153 345 0xff 0xBEBADA
1016}
1017Examples of valid float constants are
1018@verbatim{
10193.0 3.1416 314.16e-2 0.31416E1 34e1
10200x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1021}
1022
1023A @def{comment} starts with a double hyphen (@T{--})
1024anywhere outside a string.
1025If the text immediately after @T{--} is not an opening long bracket,
1026the comment is a @def{short comment},
1027which runs until the end of the line.
1028Otherwise, it is a @def{long comment},
1029which runs until the corresponding closing long bracket.
1030Long comments are frequently used to disable code temporarily.
1031
1032}
1033
1034@sect2{variables| @title{Variables}
1035
1036Variables are places that store values.
1037There are three kinds of variables in Lua:
1038global variables, local variables, and table fields.
1039
1040A single name can denote a global variable or a local variable
1041(or a function's formal parameter,
1042which is a particular kind of local variable):
1043@Produc{
1044@producname{var}@producbody{@bnfNter{Name}}
1045}
1046@bnfNter{Name} denotes identifiers, as defined in @See{lexical}.
1047
1048Any variable name is assumed to be global unless explicitly declared
1049as a local @see{localvar}.
1050@x{Local variables} are @emph{lexically scoped}:
1051local variables can be freely accessed by functions
1052defined inside their scope @see{visibility}.
1053
1054Before the first assignment to a variable, its value is @nil.
1055
1056Square brackets are used to index a table:
1057@Produc{
1058@producname{var}@producbody{prefixexp @bnfter{[} exp @bnfter{]}}
1059}
1060The meaning of accesses to table fields can be changed via metatables
1061@see{metatable}.
1062
1063The syntax @id{var.Name} is just syntactic sugar for
1064@T{var["Name"]}:
1065@Produc{
1066@producname{var}@producbody{prefixexp @bnfter{.} @bnfNter{Name}}
1067}
1068
1069An access to a global variable @id{x}
1070is equivalent to @id{_ENV.x}.
1071Due to the way that chunks are compiled,
1072@id{_ENV} is never a global name @see{globalenv}.
1073
1074}
1075
1076@sect2{stats| @title{Statements}
1077
1078Lua supports an almost conventional set of @x{statements},
1079similar to those in Pascal or C.
1080This set includes
1081assignments, control structures, function calls,
1082and variable declarations.
1083
1084@sect3{@title{Blocks}
1085
1086A @x{block} is a list of statements,
1087which are executed sequentially:
1088@Produc{
1089@producname{block}@producbody{@bnfrep{stat}}
1090}
1091Lua has @def{empty statements}
1092that allow you to separate statements with semicolons,
1093start a block with a semicolon
1094or write two semicolons in sequence:
1095@Produc{
1096@producname{stat}@producbody{@bnfter{;}}
1097}
1098
1099Function calls and assignments
1100can start with an open parenthesis.
1101This possibility leads to an ambiguity in Lua's grammar.
1102Consider the following fragment:
1103@verbatim{
1104a = b + c
1105(print or io.write)('done')
1106}
1107The grammar could see it in two ways:
1108@verbatim{
1109a = b + c(print or io.write)('done')
1110
1111a = b + c; (print or io.write)('done')
1112}
1113The current parser always sees such constructions
1114in the first way,
1115interpreting the open parenthesis
1116as the start of the arguments to a call.
1117To avoid this ambiguity,
1118it is a good practice to always precede with a semicolon
1119statements that start with a parenthesis:
1120@verbatim{
1121;(print or io.write)('done')
1122}
1123
1124A block can be explicitly delimited to produce a single statement:
1125@Produc{
1126@producname{stat}@producbody{@Rw{do} block @Rw{end}}
1127}
1128Explicit blocks are useful
1129to control the scope of variable declarations.
1130Explicit blocks are also sometimes used to
1131add a @Rw{return} statement in the middle
1132of another block @see{control}.
1133
1134}
1135
1136@sect3{chunks| @title{Chunks}
1137
1138The unit of compilation of Lua is called a @def{chunk}.
1139Syntactically,
1140a chunk is simply a block:
1141@Produc{
1142@producname{chunk}@producbody{block}
1143}
1144
1145Lua handles a chunk as the body of an anonymous function
1146with a variable number of arguments
1147@see{func-def}.
1148As such, chunks can define local variables,
1149receive arguments, and return values.
1150Moreover, such anonymous function is compiled as in the
1151scope of an external local variable called @id{_ENV} @see{globalenv}.
1152The resulting function always has @id{_ENV} as its only upvalue,
1153even if it does not use that variable.
1154
1155A chunk can be stored in a file or in a string inside the host program.
1156To execute a chunk,
1157Lua first @emph{loads} it,
1158precompiling the chunk's code into instructions for a virtual machine,
1159and then Lua executes the compiled code
1160with an interpreter for the virtual machine.
1161
1162Chunks can also be precompiled into binary form;
1163see program @idx{luac} and function @Lid{string.dump} for details.
1164Programs in source and compiled forms are interchangeable;
1165Lua automatically detects the file type and acts accordingly @seeF{load}.
1166
1167}
1168
1169@sect3{assignment| @title{Assignment}
1170
1171Lua allows @x{multiple assignments}.
1172Therefore, the syntax for assignment
1173defines a list of variables on the left side
1174and a list of expressions on the right side.
1175The elements in both lists are separated by commas:
1176@Produc{
1177@producname{stat}@producbody{varlist @bnfter{=} explist}
1178@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
1179@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
1180}
1181Expressions are discussed in @See{expressions}.
1182
1183Before the assignment,
1184the list of values is @emph{adjusted} to the length of
1185the list of variables.@index{adjustment}
1186If there are more values than needed,
1187the excess values are thrown away.
1188If there are fewer values than needed,
1189the list is extended with as many @nil's as needed.
1190If the list of expressions ends with a function call,
1191then all values returned by that call enter the list of values,
1192before the adjustment
1193(except when the call is enclosed in parentheses; see @See{expressions}).
1194
1195The assignment statement first evaluates all its expressions
1196and only then the assignments are performed.
1197Thus the code
1198@verbatim{
1199i = 3
1200i, a[i] = i+1, 20
1201}
1202sets @T{a[3]} to 20, without affecting @T{a[4]}
1203because the @id{i} in @T{a[i]} is evaluated (to 3)
1204before it is @N{assigned 4}.
1205Similarly, the line
1206@verbatim{
1207x, y = y, x
1208}
1209exchanges the values of @id{x} and @id{y},
1210and
1211@verbatim{
1212x, y, z = y, z, x
1213}
1214cyclically permutes the values of @id{x}, @id{y}, and @id{z}.
1215
1216An assignment to a global name @T{x = val}
1217is equivalent to the assignment
1218@T{_ENV.x = val} @see{globalenv}.
1219
1220The meaning of assignments to table fields and
1221global variables (which are actually table fields, too)
1222can be changed via metatables @see{metatable}.
1223
1224}
1225
1226@sect3{control| @title{Control Structures}
1227The control structures
1228@Rw{if}, @Rw{while}, and @Rw{repeat} have the usual meaning and
1229familiar syntax:
1230@index{while-do statement}
1231@index{repeat-until statement}
1232@index{if-then-else statement}
1233@Produc{
1234@producname{stat}@producbody{@Rw{while} exp @Rw{do} block @Rw{end}}
1235@producname{stat}@producbody{@Rw{repeat} block @Rw{until} exp}
1236@producname{stat}@producbody{@Rw{if} exp @Rw{then} block
1237 @bnfrep{@Rw{elseif} exp @Rw{then} block}
1238 @bnfopt{@Rw{else} block} @Rw{end}}
1239}
1240Lua also has a @Rw{for} statement, in two flavors @see{for}.
1241
1242The @x{condition expression} of a
1243control structure can return any value.
1244Both @false and @nil are considered false.
1245All values different from @nil and @false are considered true
1246(in particular, the number 0 and the empty string are also true).
1247
1248In the @Rw{repeat}@En@Rw{until} loop,
1249the inner block does not end at the @Rw{until} keyword,
1250but only after the condition.
1251So, the condition can refer to local variables
1252declared inside the loop block.
1253
1254The @Rw{goto} statement transfers the program control to a label.
1255For syntactical reasons,
1256labels in Lua are considered statements too:
1257@index{goto statement}
1258@index{label}
1259@Produc{
1260@producname{stat}@producbody{@Rw{goto} Name}
1261@producname{stat}@producbody{label}
1262@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
1263}
1264
1265A label is visible in the entire block where it is defined,
1266except
1267inside nested blocks where a label with the same name is defined and
1268inside nested functions.
1269A goto may jump to any visible label as long as it does not
1270enter into the scope of a local variable.
1271
1272Labels and empty statements are called @def{void statements},
1273as they perform no actions.
1274
1275The @Rw{break} statement terminates the execution of a
1276@Rw{while}, @Rw{repeat}, or @Rw{for} loop,
1277skipping to the next statement after the loop:
1278@index{break statement}
1279@Produc{
1280@producname{stat}@producbody{@Rw{break}}
1281}
1282A @Rw{break} ends the innermost enclosing loop.
1283
1284The @Rw{return} statement is used to return values
1285from a function or a chunk
1286(which is an anonymous function).
1287@index{return statement}
1288Functions can return more than one value,
1289so the syntax for the @Rw{return} statement is
1290@Produc{
1291@producname{stat}@producbody{@Rw{return} @bnfopt{explist} @bnfopt{@bnfter{;}}}
1292}
1293
1294The @Rw{return} statement can only be written
1295as the last statement of a block.
1296If it is really necessary to @Rw{return} in the middle of a block,
1297then an explicit inner block can be used,
1298as in the idiom @T{do return end},
1299because now @Rw{return} is the last statement in its (inner) block.
1300
1301}
1302
1303@sect3{for| @title{For Statement}
1304
1305@index{for statement}
1306The @Rw{for} statement has two forms:
1307one numerical and one generic.
1308
1309The numerical @Rw{for} loop repeats a block of code while a
1310control variable runs through an arithmetic progression.
1311It has the following syntax:
1312@Produc{
1313@producname{stat}@producbody{@Rw{for} @bnfNter{Name} @bnfter{=}
1314 exp @bnfter{,} exp @bnfopt{@bnfter{,} exp} @Rw{do} block @Rw{end}}
1315}
1316The @emph{block} is repeated for @emph{name} starting at the value of
1317the first @emph{exp}, until it passes the second @emph{exp} by steps of the
1318third @emph{exp}.
1319More precisely, a @Rw{for} statement like
1320@verbatim{
1321for v = @rep{e1}, @rep{e2}, @rep{e3} do @rep{block} end
1322}
1323is equivalent to the code:
1324@verbatim{
1325do
1326 local @rep{var}, @rep{limit}, @rep{step} = tonumber(@rep{e1}), tonumber(@rep{e2}), tonumber(@rep{e3})
1327 if not (@rep{var} and @rep{limit} and @rep{step}) then error() end
1328 @rep{var} = @rep{var} - @rep{step}
1329 while true do
1330 @rep{var} = @rep{var} + @rep{step}
1331 if (@rep{step} >= 0 and @rep{var} > @rep{limit}) or (@rep{step} < 0 and @rep{var} < @rep{limit}) then
1332 break
1333 end
1334 local v = @rep{var}
1335 @rep{block}
1336 end
1337end
1338}
1339
1340Note the following:
1341@itemize{
1342
1343@item{
1344All three control expressions are evaluated only once,
1345before the loop starts.
1346They must all result in numbers.
1347}
1348
1349@item{
1350@T{@rep{var}}, @T{@rep{limit}}, and @T{@rep{step}} are invisible variables.
1351The names shown here are for explanatory purposes only.
1352}
1353
1354@item{
1355If the third expression (the step) is absent,
1356then a step @N{of 1} is used.
1357}
1358
1359@item{
1360You can use @Rw{break} and @Rw{goto} to exit a @Rw{for} loop.
1361}
1362
1363@item{
1364The loop variable @T{v} is local to the loop body.
1365If you need its value after the loop,
1366assign it to another variable before exiting the loop.
1367}
1368
1369}
1370
1371The generic @Rw{for} statement works over functions,
1372called @def{iterators}.
1373On each iteration, the iterator function is called to produce a new value,
1374stopping when this new value is @nil.
1375The generic @Rw{for} loop has the following syntax:
1376@Produc{
1377@producname{stat}@producbody{@Rw{for} namelist @Rw{in} explist
1378 @Rw{do} block @Rw{end}}
1379@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
1380}
1381A @Rw{for} statement like
1382@verbatim{
1383for @rep{var_1}, @Cdots, @rep{var_n} in @rep{explist} do @rep{block} end
1384}
1385is equivalent to the code:
1386@verbatim{
1387do
1388 local @rep{f}, @rep{s}, @rep{var} = @rep{explist}
1389 while true do
1390 local @rep{var_1}, @Cdots, @rep{var_n} = @rep{f}(@rep{s}, @rep{var})
1391 if @rep{var_1} == nil then break end
1392 @rep{var} = @rep{var_1}
1393 @rep{block}
1394 end
1395end
1396}
1397Note the following:
1398@itemize{
1399
1400@item{
1401@T{@rep{explist}} is evaluated only once.
1402Its results are an @emph{iterator} function,
1403a @emph{state},
1404and an initial value for the first @emph{iterator variable}.
1405}
1406
1407@item{
1408@T{@rep{f}}, @T{@rep{s}}, and @T{@rep{var}} are invisible variables.
1409The names are here for explanatory purposes only.
1410}
1411
1412@item{
1413You can use @Rw{break} to exit a @Rw{for} loop.
1414}
1415
1416@item{
1417The loop variables @T{@rep{var_i}} are local to the loop;
1418you cannot use their values after the @Rw{for} ends.
1419If you need these values,
1420then assign them to other variables before breaking or exiting the loop.
1421}
1422
1423}
1424
1425}
1426
1427@sect3{funcstat| @title{Function Calls as Statements}
1428To allow possible side-effects,
1429function calls can be executed as statements:
1430@Produc{
1431@producname{stat}@producbody{functioncall}
1432}
1433In this case, all returned values are thrown away.
1434Function calls are explained in @See{functioncall}.
1435
1436}
1437
1438@sect3{localvar| @title{Local Declarations}
1439@x{Local variables} can be declared anywhere inside a block.
1440The declaration can include an initial assignment:
1441@Produc{
1442@producname{stat}@producbody{@Rw{local} namelist @bnfopt{@bnfter{=} explist}}
1443}
1444If present, an initial assignment has the same semantics
1445of a multiple assignment @see{assignment}.
1446Otherwise, all variables are initialized with @nil.
1447
1448A chunk is also a block @see{chunks},
1449and so local variables can be declared in a chunk outside any explicit block.
1450
1451The visibility rules for local variables are explained in @See{visibility}.
1452
1453}
1454
1455}
1456
1457@sect2{expressions| @title{Expressions}
1458
1459The basic expressions in Lua are the following:
1460@Produc{
1461@producname{exp}@producbody{prefixexp}
1462@producname{exp}@producbody{@Rw{nil} @Or @Rw{false} @Or @Rw{true}}
1463@producname{exp}@producbody{@bnfNter{Numeral}}
1464@producname{exp}@producbody{@bnfNter{LiteralString}}
1465@producname{exp}@producbody{functiondef}
1466@producname{exp}@producbody{tableconstructor}
1467@producname{exp}@producbody{@bnfter{...}}
1468@producname{exp}@producbody{exp binop exp}
1469@producname{exp}@producbody{unop exp}
1470@producname{prefixexp}@producbody{var @Or functioncall @Or
1471 @bnfter{(} exp @bnfter{)}}
1472}
1473
1474Numerals and literal strings are explained in @See{lexical};
1475variables are explained in @See{variables};
1476function definitions are explained in @See{func-def};
1477function calls are explained in @See{functioncall};
1478table constructors are explained in @See{tableconstructor}.
1479Vararg expressions,
1480denoted by three dots (@Char{...}), can only be used when
1481directly inside a vararg function;
1482they are explained in @See{func-def}.
1483
1484Binary operators comprise arithmetic operators @see{arith},
1485bitwise operators @see{bitwise},
1486relational operators @see{rel-ops}, logical operators @see{logic},
1487and the concatenation operator @see{concat}.
1488Unary operators comprise the unary minus @see{arith},
1489the unary bitwise NOT @see{bitwise},
1490the unary logical @Rw{not} @see{logic},
1491and the unary @def{length operator} @see{len-op}.
1492
1493Both function calls and vararg expressions can result in multiple values.
1494If a function call is used as a statement @see{funcstat},
1495then its return list is adjusted to zero elements,
1496thus discarding all returned values.
1497If an expression is used as the last (or the only) element
1498of a list of expressions,
1499then no adjustment is made
1500(unless the expression is enclosed in parentheses).
1501In all other contexts,
1502Lua adjusts the result list to one element,
1503either discarding all values except the first one
1504or adding a single @nil if there are no values.
1505
1506Here are some examples:
1507@verbatim{
1508f() -- adjusted to 0 results
1509g(f(), x) -- f() is adjusted to 1 result
1510g(x, f()) -- g gets x plus all results from f()
1511a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
1512a,b = ... -- a gets the first vararg argument, b gets
1513 -- the second (both a and b can get nil if there
1514 -- is no corresponding vararg argument)
1515
1516a,b,c = x, f() -- f() is adjusted to 2 results
1517a,b,c = f() -- f() is adjusted to 3 results
1518return f() -- returns all results from f()
1519return ... -- returns all received vararg arguments
1520return x,y,f() -- returns x, y, and all results from f()
1521{f()} -- creates a list with all results from f()
1522{...} -- creates a list with all vararg arguments
1523{f(), nil} -- f() is adjusted to 1 result
1524}
1525
1526Any expression enclosed in parentheses always results in only one value.
1527Thus,
1528@T{(f(x,y,z))} is always a single value,
1529even if @id{f} returns several values.
1530(The value of @T{(f(x,y,z))} is the first value returned by @id{f}
1531or @nil if @id{f} does not return any values.)
1532
1533
1534
1535@sect3{arith| @title{Arithmetic Operators}
1536Lua supports the following @x{arithmetic operators}:
1537@description{
1538@item{@T{+}|addition}
1539@item{@T{-}|subtraction}
1540@item{@T{*}|multiplication}
1541@item{@T{/}|float division}
1542@item{@T{//}|floor division}
1543@item{@T{%}|modulo}
1544@item{@T{^}|exponentiation}
1545@item{@T{-}|unary minus}
1546}
1547
1548With the exception of exponentiation and float division,
1549the arithmetic operators work as follows:
1550If both operands are integers,
1551the operation is performed over integers and the result is an integer.
1552Otherwise, if both operands are numbers
1553or strings that can be converted to
1554numbers @see{coercion},
1555then they are converted to floats,
1556the operation is performed following the usual rules
1557for floating-point arithmetic
1558(usually the @x{IEEE 754} standard),
1559and the result is a float.
1560
1561Exponentiation and float division (@T{/})
1562always convert their operands to floats
1563and the result is always a float.
1564Exponentiation uses the @ANSI{pow},
1565so that it works for non-integer exponents too.
1566
1567Floor division (@T{//}) is a division
1568that rounds the quotient towards minus infinity,
1569that is, the floor of the division of its operands.
1570
1571Modulo is defined as the remainder of a division
1572that rounds the quotient towards minus infinity (floor division).
1573
1574In case of overflows in integer arithmetic,
1575all operations @emphx{wrap around},
1576according to the usual rules of two-complement arithmetic.
1577(In other words,
1578they return the unique representable integer
1579that is equal modulo @M{2@sp{64}} to the mathematical result.)
1580}
1581
1582@sect3{bitwise| @title{Bitwise Operators}
1583Lua supports the following @x{bitwise operators}:
1584@description{
1585@item{@T{&}|bitwise AND}
1586@item{@T{@VerBar}|bitwise OR}
1587@item{@T{~}|bitwise exclusive OR}
1588@item{@T{>>}|right shift}
1589@item{@T{<<}|left shift}
1590@item{@T{~}|unary bitwise NOT}
1591}
1592
1593All bitwise operations convert its operands to integers
1594@see{coercion},
1595operate on all bits of those integers,
1596and result in an integer.
1597
1598Both right and left shifts fill the vacant bits with zeros.
1599Negative displacements shift to the other direction;
1600displacements with absolute values equal to or higher than
1601the number of bits in an integer
1602result in zero (as all bits are shifted out).
1603
1604}
1605
1606@sect3{coercion| @title{Coercions and Conversions}
1607Lua provides some automatic conversions between some
1608types and representations at run time.
1609Bitwise operators always convert float operands to integers.
1610Exponentiation and float division
1611always convert integer operands to floats.
1612All other arithmetic operations applied to mixed numbers
1613(integers and floats) convert the integer operand to a float;
1614this is called the @def{usual rule}.
1615The C API also converts both integers to floats and
1616floats to integers, as needed.
1617Moreover, string concatenation accepts numbers as arguments,
1618besides strings.
1619
1620Lua also converts strings to numbers,
1621whenever a number is expected.
1622
1623In a conversion from integer to float,
1624if the integer value has an exact representation as a float,
1625that is the result.
1626Otherwise,
1627the conversion gets the nearest higher or
1628the nearest lower representable value.
1629This kind of conversion never fails.
1630
1631The conversion from float to integer
1632checks whether the float has an exact representation as an integer
1633(that is, the float has an integral value and
1634it is in the range of integer representation).
1635If it does, that representation is the result.
1636Otherwise, the conversion fails.
1637
1638The conversion from strings to numbers goes as follows:
1639First, the string is converted to an integer or a float,
1640following its syntax and the rules of the Lua lexer.
1641(The string may have also leading and trailing spaces and a sign.)
1642Then, the resulting number (float or integer)
1643is converted to the type (float or integer) required by the context
1644(e.g., the operation that forced the conversion).
1645
1646All conversions from strings to numbers
1647accept both a dot and the current locale mark
1648as the radix character.
1649(The Lua lexer, however, accepts only a dot.)
1650
1651The conversion from numbers to strings uses a
1652non-specified human-readable format.
1653For complete control over how numbers are converted to strings,
1654use the @id{format} function from the string library
1655@seeF{string.format}.
1656
1657}
1658
1659@sect3{rel-ops| @title{Relational Operators}
1660Lua supports the following @x{relational operators}:
1661@description{
1662@item{@T{==}|equality}
1663@item{@T{~=}|inequality}
1664@item{@T{<}|less than}
1665@item{@T{>}|greater than}
1666@item{@T{<=}|less or equal}
1667@item{@T{>=}|greater or equal}
1668}
1669These operators always result in @false or @true.
1670
1671Equality (@T{==}) first compares the type of its operands.
1672If the types are different, then the result is @false.
1673Otherwise, the values of the operands are compared.
1674Strings are compared in the obvious way.
1675Numbers are equal if they denote the same mathematical value.
1676
1677Tables, userdata, and threads
1678are compared by reference:
1679two objects are considered equal only if they are the same object.
1680Every time you create a new object
1681(a table, userdata, or thread),
1682this new object is different from any previously existing object.
1683A closure is always equal to itself.
1684Closures with any detectable difference
1685(different behavior, different definition) are always different.
1686Closures created at different times but with no detectable differences
1687may be classified as equal or not
1688(depending on internal caching details).
1689
1690You can change the way that Lua compares tables and userdata
1691by using the @Q{eq} metamethod @see{metatable}.
1692
1693Equality comparisons do not convert strings to numbers
1694or vice versa.
1695Thus, @T{"0"==0} evaluates to @false,
1696and @T{t[0]} and @T{t["0"]} denote different
1697entries in a table.
1698
1699The operator @T{~=} is exactly the negation of equality (@T{==}).
1700
1701The order operators work as follows.
1702If both arguments are numbers,
1703then they are compared according to their mathematical values
1704(regardless of their subtypes).
1705Otherwise, if both arguments are strings,
1706then their values are compared according to the current locale.
1707Otherwise, Lua tries to call the @Q{lt} or the @Q{le}
1708metamethod @see{metatable}.
1709A comparison @T{a > b} is translated to @T{b < a}
1710and @T{a >= b} is translated to @T{b <= a}.
1711
1712Following the @x{IEEE 754} standard,
1713@x{NaN} is considered neither smaller than,
1714nor equal to, nor greater than any value (including itself).
1715
1716}
1717
1718@sect3{logic| @title{Logical Operators}
1719The @x{logical operators} in Lua are
1720@Rw{and}, @Rw{or}, and @Rw{not}.
1721Like the control structures @see{control},
1722all logical operators consider both @false and @nil as false
1723and anything else as true.
1724
1725The negation operator @Rw{not} always returns @false or @true.
1726The conjunction operator @Rw{and} returns its first argument
1727if this value is @false or @nil;
1728otherwise, @Rw{and} returns its second argument.
1729The disjunction operator @Rw{or} returns its first argument
1730if this value is different from @nil and @false;
1731otherwise, @Rw{or} returns its second argument.
1732Both @Rw{and} and @Rw{or} use @x{short-circuit evaluation};
1733that is,
1734the second operand is evaluated only if necessary.
1735Here are some examples:
1736@verbatim{
173710 or 20 --> 10
173810 or error() --> 10
1739nil or "a" --> "a"
1740nil and 10 --> nil
1741false and error() --> false
1742false and nil --> false
1743false or nil --> nil
174410 and 20 --> 20
1745}
1746(In this manual,
1747@T{-->} indicates the result of the preceding expression.)
1748
1749}
1750
1751@sect3{concat| @title{Concatenation}
1752The string @x{concatenation} operator in Lua is
1753denoted by two dots (@Char{..}).
1754If both operands are strings or numbers, then they are converted to
1755strings according to the rules described in @See{coercion}.
1756Otherwise, the @idx{__concat} metamethod is called @see{metatable}.
1757
1758}
1759
1760@sect3{len-op| @title{The Length Operator}
1761
1762The length operator is denoted by the unary prefix operator @T{#}.
1763
1764The length of a string is its number of bytes
1765(that is, the usual meaning of string length when each
1766character is one byte).
1767
1768The length operator applied on a table
1769returns a @x{border} in that table.
1770A @def{border} in a table @id{t} is any natural number
1771that satisfies the following condition:
1772@verbatim{
1773(border == 0 or t[border] ~= nil) and t[border + 1] == nil
1774}
1775In words,
1776a border is any (natural) index in a table
1777where a non-nil value is followed by a nil value
1778(or zero, when index 1 is nil).
1779
1780A table with exactly one border is called a @def{sequence}.
1781For instance, the table @T{{10, 20, 30, 40, 50}} is a sequence,
1782as it has only one border (5).
1783The table @T{{10, 20, 30, nil, 50}} has two borders (3 and 5),
1784and therefore it is not a sequence.
1785The table @T{{nil, 20, 30, nil, nil, 60, nil}}
1786has three borders (0, 3, and 6),
1787so it is not a sequence, too.
1788The table @T{{}} is a sequence with border 0.
1789Note that non-natural keys do not interfere
1790with whether a table is a sequence.
1791
1792When @id{t} is a sequence,
1793@T{#t} returns its only border,
1794which corresponds to the intuitive notion of the length of the sequence.
1795When @id{t} is not a sequence,
1796@T{#t} can return any of its borders.
1797(The exact one depends on details of
1798the internal representation of the table,
1799which in turn can depend on how the table was populated and
1800the memory addresses of its non-numeric keys.)
1801
1802The computation of the length of a table
1803has a guaranteed worst time of @M{O(log n)},
1804where @M{n} is the largest natural key in the table.
1805
1806A program can modify the behavior of the length operator for
1807any value but strings through the @idx{__len} metamethod @see{metatable}.
1808
1809}
1810
1811@sect3{prec| @title{Precedence}
1812@x{Operator precedence} in Lua follows the table below,
1813from lower to higher priority:
1814@verbatim{
1815or
1816and
1817< > <= >= ~= ==
1818|
1819~
1820&
1821<< >>
1822..
1823+ -
1824* / // %
1825unary operators (not # - ~)
1826^
1827}
1828As usual,
1829you can use parentheses to change the precedences of an expression.
1830The concatenation (@Char{..}) and exponentiation (@Char{^})
1831operators are right associative.
1832All other binary operators are left associative.
1833
1834}
1835
1836@sect3{tableconstructor| @title{Table Constructors}
1837Table @x{constructors} are expressions that create tables.
1838Every time a constructor is evaluated, a new table is created.
1839A constructor can be used to create an empty table
1840or to create a table and initialize some of its fields.
1841The general syntax for constructors is
1842@Produc{
1843@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
1844@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
1845@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or
1846 @bnfNter{Name} @bnfter{=} exp @Or exp}
1847@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
1848}
1849
1850Each field of the form @T{[exp1] = exp2} adds to the new table an entry
1851with key @id{exp1} and value @id{exp2}.
1852A field of the form @T{name = exp} is equivalent to
1853@T{["name"] = exp}.
1854Finally, fields of the form @id{exp} are equivalent to
1855@T{[i] = exp}, where @id{i} are consecutive integers
1856starting with 1.
1857Fields in the other formats do not affect this counting.
1858For example,
1859@verbatim{
1860a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1861}
1862is equivalent to
1863@verbatim{
1864do
1865 local t = {}
1866 t[f(1)] = g
1867 t[1] = "x" -- 1st exp
1868 t[2] = "y" -- 2nd exp
1869 t.x = 1 -- t["x"] = 1
1870 t[3] = f(x) -- 3rd exp
1871 t[30] = 23
1872 t[4] = 45 -- 4th exp
1873 a = t
1874end
1875}
1876
1877The order of the assignments in a constructor is undefined.
1878(This order would be relevant only when there are repeated keys.)
1879
1880If the last field in the list has the form @id{exp}
1881and the expression is a function call or a vararg expression,
1882then all values returned by this expression enter the list consecutively
1883@see{functioncall}.
1884
1885The field list can have an optional trailing separator,
1886as a convenience for machine-generated code.
1887
1888}
1889
1890@sect3{functioncall| @title{Function Calls}
1891A @x{function call} in Lua has the following syntax:
1892@Produc{
1893@producname{functioncall}@producbody{prefixexp args}
1894}
1895In a function call,
1896first @bnfNter{prefixexp} and @bnfNter{args} are evaluated.
1897If the value of @bnfNter{prefixexp} has type @emph{function},
1898then this function is called
1899with the given arguments.
1900Otherwise, the @bnfNter{prefixexp} @Q{call} metamethod is called,
1901having as first argument the value of @bnfNter{prefixexp},
1902followed by the original call arguments
1903@see{metatable}.
1904
1905The form
1906@Produc{
1907@producname{functioncall}@producbody{prefixexp @bnfter{:} @bnfNter{Name} args}
1908}
1909can be used to call @Q{methods}.
1910A call @T{v:name(@rep{args})}
1911is syntactic sugar for @T{v.name(v,@rep{args})},
1912except that @id{v} is evaluated only once.
1913
1914Arguments have the following syntax:
1915@Produc{
1916@producname{args}@producbody{@bnfter{(} @bnfopt{explist} @bnfter{)}}
1917@producname{args}@producbody{tableconstructor}
1918@producname{args}@producbody{@bnfNter{LiteralString}}
1919}
1920All argument expressions are evaluated before the call.
1921A call of the form @T{f{@rep{fields}}} is
1922syntactic sugar for @T{f({@rep{fields}})};
1923that is, the argument list is a single new table.
1924A call of the form @T{f'@rep{string}'}
1925(or @T{f"@rep{string}"} or @T{f[[@rep{string}]]})
1926is syntactic sugar for @T{f('@rep{string}')};
1927that is, the argument list is a single literal string.
1928
1929A call of the form @T{return @rep{functioncall}} is called
1930a @def{tail call}.
1931Lua implements @def{proper tail calls}
1932(or @emph{proper tail recursion}):
1933in a tail call,
1934the called function reuses the stack entry of the calling function.
1935Therefore, there is no limit on the number of nested tail calls that
1936a program can execute.
1937However, a tail call erases any debug information about the
1938calling function.
1939Note that a tail call only happens with a particular syntax,
1940where the @Rw{return} has one single function call as argument;
1941this syntax makes the calling function return exactly
1942the returns of the called function.
1943So, none of the following examples are tail calls:
1944@verbatim{
1945return (f(x)) -- results adjusted to 1
1946return 2 * f(x)
1947return x, f(x) -- additional results
1948f(x); return -- results discarded
1949return x or f(x) -- results adjusted to 1
1950}
1951
1952}
1953
1954@sect3{func-def| @title{Function Definitions}
1955
1956The syntax for function definition is
1957@Produc{
1958@producname{functiondef}@producbody{@Rw{function} funcbody}
1959@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
1960}
1961
1962The following syntactic sugar simplifies function definitions:
1963@Produc{
1964@producname{stat}@producbody{@Rw{function} funcname funcbody}
1965@producname{stat}@producbody{@Rw{local} @Rw{function} @bnfNter{Name} funcbody}
1966@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}} @bnfopt{@bnfter{:} @bnfNter{Name}}}
1967}
1968The statement
1969@verbatim{
1970function f () @rep{body} end
1971}
1972translates to
1973@verbatim{
1974f = function () @rep{body} end
1975}
1976The statement
1977@verbatim{
1978function t.a.b.c.f () @rep{body} end
1979}
1980translates to
1981@verbatim{
1982t.a.b.c.f = function () @rep{body} end
1983}
1984The statement
1985@verbatim{
1986local function f () @rep{body} end
1987}
1988translates to
1989@verbatim{
1990local f; f = function () @rep{body} end
1991}
1992not to
1993@verbatim{
1994local f = function () @rep{body} end
1995}
1996(This only makes a difference when the body of the function
1997contains references to @id{f}.)
1998
1999A function definition is an executable expression,
2000whose value has type @emph{function}.
2001When Lua precompiles a chunk,
2002all its function bodies are precompiled too.
2003Then, whenever Lua executes the function definition,
2004the function is @emph{instantiated} (or @emph{closed}).
2005This function instance (or @emphx{closure})
2006is the final value of the expression.
2007
2008Parameters act as local variables that are
2009initialized with the argument values:
2010@Produc{
2011@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}} @Or
2012 @bnfter{...}}
2013}
2014When a function is called,
2015the list of @x{arguments} is adjusted to
2016the length of the list of parameters,
2017unless the function is a @def{vararg function},
2018which is indicated by three dots (@Char{...})
2019at the end of its parameter list.
2020A vararg function does not adjust its argument list;
2021instead, it collects all extra arguments and supplies them
2022to the function through a @def{vararg expression},
2023which is also written as three dots.
2024The value of this expression is a list of all actual extra arguments,
2025similar to a function with multiple results.
2026If a vararg expression is used inside another expression
2027or in the middle of a list of expressions,
2028then its return list is adjusted to one element.
2029If the expression is used as the last element of a list of expressions,
2030then no adjustment is made
2031(unless that last expression is enclosed in parentheses).
2032
2033
2034As an example, consider the following definitions:
2035@verbatim{
2036function f(a, b) end
2037function g(a, b, ...) end
2038function r() return 1,2,3 end
2039}
2040Then, we have the following mapping from arguments to parameters and
2041to the vararg expression:
2042@verbatim{
2043CALL PARAMETERS
2044
2045f(3) a=3, b=nil
2046f(3, 4) a=3, b=4
2047f(3, 4, 5) a=3, b=4
2048f(r(), 10) a=1, b=10
2049f(r()) a=1, b=2
2050
2051g(3) a=3, b=nil, ... --> (nothing)
2052g(3, 4) a=3, b=4, ... --> (nothing)
2053g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
2054g(5, r()) a=5, b=1, ... --> 2 3
2055}
2056
2057Results are returned using the @Rw{return} statement @see{control}.
2058If control reaches the end of a function
2059without encountering a @Rw{return} statement,
2060then the function returns with no results.
2061
2062@index{multiple return}
2063There is a system-dependent limit on the number of values
2064that a function may return.
2065This limit is guaranteed to be larger than 1000.
2066
2067The @emphx{colon} syntax
2068is used for defining @def{methods},
2069that is, functions that have an implicit extra parameter @idx{self}.
2070Thus, the statement
2071@verbatim{
2072function t.a.b.c:f (@rep{params}) @rep{body} end
2073}
2074is syntactic sugar for
2075@verbatim{
2076t.a.b.c.f = function (self, @rep{params}) @rep{body} end
2077}
2078
2079}
2080
2081}
2082
2083@sect2{visibility| @title{Visibility Rules}
2084
2085@index{visibility}
2086Lua is a lexically scoped language.
2087The scope of a local variable begins at the first statement after
2088its declaration and lasts until the last non-void statement
2089of the innermost block that includes the declaration.
2090Consider the following example:
2091@verbatim{
2092x = 10 -- global variable
2093do -- new block
2094 local x = x -- new 'x', with value 10
2095 print(x) --> 10
2096 x = x+1
2097 do -- another block
2098 local x = x+1 -- another 'x'
2099 print(x) --> 12
2100 end
2101 print(x) --> 11
2102end
2103print(x) --> 10 (the global one)
2104}
2105
2106Notice that, in a declaration like @T{local x = x},
2107the new @id{x} being declared is not in scope yet,
2108and so the second @id{x} refers to the outside variable.
2109
2110Because of the @x{lexical scoping} rules,
2111local variables can be freely accessed by functions
2112defined inside their scope.
2113A local variable used by an inner function is called
2114an @def{upvalue}, or @emphx{external local variable},
2115inside the inner function.
2116
2117Notice that each execution of a @Rw{local} statement
2118defines new local variables.
2119Consider the following example:
2120@verbatim{
2121a = {}
2122local x = 20
2123for i=1,10 do
2124 local y = 0
2125 a[i] = function () y=y+1; return x+y end
2126end
2127}
2128The loop creates ten closures
2129(that is, ten instances of the anonymous function).
2130Each of these closures uses a different @id{y} variable,
2131while all of them share the same @id{x}.
2132
2133}
2134
2135}
2136
2137
2138@C{-------------------------------------------------------------------------}
2139@sect1{API| @title{The Application Program Interface}
2140
2141@index{C API}
2142This section describes the @N{C API} for Lua, that is,
2143the set of @N{C functions} available to the host program to communicate
2144with Lua.
2145All API functions and related types and constants
2146are declared in the header file @defid{lua.h}.
2147
2148Even when we use the term @Q{function},
2149any facility in the API may be provided as a macro instead.
2150Except where stated otherwise,
2151all such macros use each of their arguments exactly once
2152(except for the first argument, which is always a Lua state),
2153and so do not generate any hidden side-effects.
2154
2155As in most @N{C libraries},
2156the Lua API functions do not check their arguments for validity or consistency.
2157However, you can change this behavior by compiling Lua
2158with the macro @defid{LUA_USE_APICHECK} defined.
2159
2160The Lua library is fully reentrant:
2161it has no global variables.
2162It keeps all information it needs in a dynamic structure,
2163called the @def{Lua state}.
2164
2165Each Lua state has one or more threads,
2166which correspond to independent, cooperative lines of execution.
2167The type @Lid{lua_State} (despite its name) refers to a thread.
2168(Indirectly, through the thread, it also refers to the
2169Lua state associated to the thread.)
2170
2171A pointer to a thread must be passed as the first argument to
2172every function in the library, except to @Lid{lua_newstate},
2173which creates a Lua state from scratch and returns a pointer
2174to the @emph{main thread} in the new state.
2175
2176
2177@sect2{@title{The Stack}
2178
2179Lua uses a @emph{virtual stack} to pass values to and from C.
2180Each element in this stack represents a Lua value
2181(@nil, number, string, etc.).
2182Functions in the API can access this stack through the
2183Lua state parameter that they receive.
2184
2185Whenever Lua calls C, the called function gets a new stack,
2186which is independent of previous stacks and of stacks of
2187@N{C functions} that are still active.
2188This stack initially contains any arguments to the @N{C function}
2189and it is where the @N{C function} can store temporary
2190Lua values and must push its results
2191to be returned to the caller @seeC{lua_CFunction}.
2192
2193For convenience,
2194most query operations in the API do not follow a strict stack discipline.
2195Instead, they can refer to any element in the stack
2196by using an @emph{index}:@index{index (API stack)}
2197A positive index represents an absolute stack position
2198(starting @N{at 1});
2199a negative index represents an offset relative to the top of the stack.
2200More specifically, if the stack has @rep{n} elements,
2201then @N{index 1} represents the first element
2202(that is, the element that was pushed onto the stack first)
2203and
2204@N{index @rep{n}} represents the last element;
2205@N{index @num{-1}} also represents the last element
2206(that is, the element at @N{the top})
2207and index @M{-n} represents the first element.
2208
2209}
2210
2211@sect2{stacksize| @title{Stack Size}
2212
2213When you interact with the Lua API,
2214you are responsible for ensuring consistency.
2215In particular,
2216@emph{you are responsible for controlling stack overflow}.
2217You can use the function @Lid{lua_checkstack}
2218to ensure that the stack has enough space for pushing new elements.
2219
2220Whenever Lua calls C,
2221it ensures that the stack has space for
2222at least @defid{LUA_MINSTACK} extra slots.
2223@id{LUA_MINSTACK} is defined as 20,
2224so that usually you do not have to worry about stack space
2225unless your code has loops pushing elements onto the stack.
2226
2227When you call a Lua function
2228without a fixed number of results @seeF{lua_call},
2229Lua ensures that the stack has enough space for all results,
2230but it does not ensure any extra space.
2231So, before pushing anything in the stack after such a call
2232you should use @Lid{lua_checkstack}.
2233
2234}
2235
2236@sect2{@title{Valid and Acceptable Indices}
2237
2238Any function in the API that receives stack indices
2239works only with @emphx{valid indices} or @emphx{acceptable indices}.
2240
2241A @def{valid index} is an index that refers to a
2242position that stores a modifiable Lua value.
2243It comprises stack indices @N{between 1} and the stack top
2244(@T{1 @leq abs(index) @leq top})
2245@index{stack index}
2246plus @def{pseudo-indices},
2247which represent some positions that are accessible to @N{C code}
2248but that are not in the stack.
2249Pseudo-indices are used to access the registry @see{registry}
2250and the upvalues of a @N{C function} @see{c-closure}.
2251
2252Functions that do not need a specific mutable position,
2253but only a value (e.g., query functions),
2254can be called with acceptable indices.
2255An @def{acceptable index} can be any valid index,
2256but it also can be any positive index after the stack top
2257within the space allocated for the stack,
2258that is, indices up to the stack size.
2259(Note that 0 is never an acceptable index.)
2260Except when noted otherwise,
2261functions in the API work with acceptable indices.
2262
2263Acceptable indices serve to avoid extra tests
2264against the stack top when querying the stack.
2265For instance, a @N{C function} can query its third argument
2266without the need to first check whether there is a third argument,
2267that is, without the need to check whether 3 is a valid index.
2268
2269For functions that can be called with acceptable indices,
2270any non-valid index is treated as if it
2271contains a value of a virtual type @defid{LUA_TNONE},
2272which behaves like a nil value.
2273
2274}
2275
2276@sect2{c-closure| @title{C Closures}
2277
2278When a @N{C function} is created,
2279it is possible to associate some values with it,
2280thus creating a @def{@N{C closure}}
2281@seeC{lua_pushcclosure};
2282these values are called @def{upvalues} and are
2283accessible to the function whenever it is called.
2284
2285Whenever a @N{C function} is called,
2286its upvalues are located at specific pseudo-indices.
2287These pseudo-indices are produced by the macro
2288@Lid{lua_upvalueindex}.
2289The first upvalue associated with a function is at index
2290@T{lua_upvalueindex(1)}, and so on.
2291Any access to @T{lua_upvalueindex(@rep{n})},
2292where @rep{n} is greater than the number of upvalues of the
2293current function
2294(but not greater than 256,
2295which is one plus the maximum number of upvalues in a closure),
2296produces an acceptable but invalid index.
2297
2298}
2299
2300@sect2{registry| @title{Registry}
2301
2302Lua provides a @def{registry},
2303a predefined table that can be used by any @N{C code} to
2304store whatever Lua values it needs to store.
2305The registry table is always located at pseudo-index
2306@defid{LUA_REGISTRYINDEX}.
2307Any @N{C library} can store data into this table,
2308but it must take care to choose keys
2309that are different from those used
2310by other libraries, to avoid collisions.
2311Typically, you should use as key a string containing your library name,
2312or a light userdata with the address of a @N{C object} in your code,
2313or any Lua object created by your code.
2314As with variable names,
2315string keys starting with an underscore followed by
2316uppercase letters are reserved for Lua.
2317
2318The integer keys in the registry are used
2319by the reference mechanism @seeC{luaL_ref}
2320and by some predefined values.
2321Therefore, integer keys must not be used for other purposes.
2322
2323When you create a new Lua state,
2324its registry comes with some predefined values.
2325These predefined values are indexed with integer keys
2326defined as constants in @id{lua.h}.
2327The following constants are defined:
2328@description{
2329@item{@defid{LUA_RIDX_MAINTHREAD}| At this index the registry has
2330the main thread of the state.
2331(The main thread is the one created together with the state.)
2332}
2333
2334@item{@defid{LUA_RIDX_GLOBALS}| At this index the registry has
2335the @x{global environment}.
2336}
2337}
2338
2339}
2340
2341@sect2{C-error|@title{Error Handling in C}
2342
2343Internally, Lua uses the C @id{longjmp} facility to handle errors.
2344(Lua will use exceptions if you compile it as C++;
2345search for @id{LUAI_THROW} in the source code for details.)
2346When Lua faces any error
2347(such as a @x{memory allocation error} or a type error)
2348it @emph{raises} an error;
2349that is, it does a long jump.
2350A @emphx{protected environment} uses @id{setjmp}
2351to set a recovery point;
2352any error jumps to the most recent active recovery point.
2353
2354Inside a @N{C function} you can raise an error by calling @Lid{lua_error}.
2355
2356Most functions in the API can raise an error,
2357for instance due to a @x{memory allocation error}.
2358The documentation for each function indicates whether
2359it can raise errors.
2360
2361If an error happens outside any protected environment,
2362Lua calls a @def{panic function} (see @Lid{lua_atpanic})
2363and then calls @T{abort},
2364thus exiting the host application.
2365Your panic function can avoid this exit by
2366never returning
2367(e.g., doing a long jump to your own recovery point outside Lua).
2368
2369The panic function,
2370as its name implies,
2371is a mechanism of last resort.
2372Programs should avoid it.
2373As a general rule,
2374when a @N{C function} is called by Lua with a Lua state,
2375it can do whatever it wants on that Lua state,
2376as it should be already protected.
2377However,
2378when C code operates on other Lua states
2379(e.g., a Lua argument to the function,
2380a Lua state stored in the registry, or
2381the result of @Lid{lua_newthread}),
2382it should use them only in API calls that cannot raise errors.
2383
2384The panic function runs as if it were a @x{message handler} @see{error};
2385in particular, the error object is at the top of the stack.
2386However, there is no guarantee about stack space.
2387To push anything on the stack,
2388the panic function must first check the available space @see{stacksize}.
2389
2390}
2391
2392@sect2{continuations|@title{Handling Yields in C}
2393
2394Internally, Lua uses the C @id{longjmp} facility to yield a coroutine.
2395Therefore, if a @N{C function} @id{foo} calls an API function
2396and this API function yields
2397(directly or indirectly by calling another function that yields),
2398Lua cannot return to @id{foo} any more,
2399because the @id{longjmp} removes its frame from the C stack.
2400
2401To avoid this kind of problem,
2402Lua raises an error whenever it tries to yield across an API call,
2403except for three functions:
2404@Lid{lua_yieldk}, @Lid{lua_callk}, and @Lid{lua_pcallk}.
2405All those functions receive a @def{continuation function}
2406(as a parameter named @id{k}) to continue execution after a yield.
2407
2408We need to set some terminology to explain continuations.
2409We have a @N{C function} called from Lua which we will call
2410the @emph{original function}.
2411This original function then calls one of those three functions in the C API,
2412which we will call the @emph{callee function},
2413that then yields the current thread.
2414(This can happen when the callee function is @Lid{lua_yieldk},
2415or when the callee function is either @Lid{lua_callk} or @Lid{lua_pcallk}
2416and the function called by them yields.)
2417
2418Suppose the running thread yields while executing the callee function.
2419After the thread resumes,
2420it eventually will finish running the callee function.
2421However,
2422the callee function cannot return to the original function,
2423because its frame in the C stack was destroyed by the yield.
2424Instead, Lua calls a @def{continuation function},
2425which was given as an argument to the callee function.
2426As the name implies,
2427the continuation function should continue the task
2428of the original function.
2429
2430As an illustration, consider the following function:
2431@verbatim{
2432int original_function (lua_State *L) {
2433 ... /* code 1 */
2434 status = lua_pcall(L, n, m, h); /* calls Lua */
2435 ... /* code 2 */
2436}
2437}
2438Now we want to allow
2439the Lua code being run by @Lid{lua_pcall} to yield.
2440First, we can rewrite our function like here:
2441@verbatim{
2442int k (lua_State *L, int status, lua_KContext ctx) {
2443 ... /* code 2 */
2444}
2445
2446int original_function (lua_State *L) {
2447 ... /* code 1 */
2448 return k(L, lua_pcall(L, n, m, h), ctx);
2449}
2450}
2451In the above code,
2452the new function @id{k} is a
2453@emph{continuation function} (with type @Lid{lua_KFunction}),
2454which should do all the work that the original function
2455was doing after calling @Lid{lua_pcall}.
2456Now, we must inform Lua that it must call @id{k} if the Lua code
2457being executed by @Lid{lua_pcall} gets interrupted in some way
2458(errors or yielding),
2459so we rewrite the code as here,
2460replacing @Lid{lua_pcall} by @Lid{lua_pcallk}:
2461@verbatim{
2462int original_function (lua_State *L) {
2463 ... /* code 1 */
2464 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2465}
2466}
2467Note the external, explicit call to the continuation:
2468Lua will call the continuation only if needed, that is,
2469in case of errors or resuming after a yield.
2470If the called function returns normally without ever yielding,
2471@Lid{lua_pcallk} (and @Lid{lua_callk}) will also return normally.
2472(Of course, instead of calling the continuation in that case,
2473you can do the equivalent work directly inside the original function.)
2474
2475Besides the Lua state,
2476the continuation function has two other parameters:
2477the final status of the call plus the context value (@id{ctx}) that
2478was passed originally to @Lid{lua_pcallk}.
2479(Lua does not use this context value;
2480it only passes this value from the original function to the
2481continuation function.)
2482For @Lid{lua_pcallk},
2483the status is the same value that would be returned by @Lid{lua_pcallk},
2484except that it is @Lid{LUA_YIELD} when being executed after a yield
2485(instead of @Lid{LUA_OK}).
2486For @Lid{lua_yieldk} and @Lid{lua_callk},
2487the status is always @Lid{LUA_YIELD} when Lua calls the continuation.
2488(For these two functions,
2489Lua will not call the continuation in case of errors,
2490because they do not handle errors.)
2491Similarly, when using @Lid{lua_callk},
2492you should call the continuation function
2493with @Lid{LUA_OK} as the status.
2494(For @Lid{lua_yieldk}, there is not much point in calling
2495directly the continuation function,
2496because @Lid{lua_yieldk} usually does not return.)
2497
2498Lua treats the continuation function as if it were the original function.
2499The continuation function receives the same Lua stack
2500from the original function,
2501in the same state it would be if the callee function had returned.
2502(For instance,
2503after a @Lid{lua_callk} the function and its arguments are
2504removed from the stack and replaced by the results from the call.)
2505It also has the same upvalues.
2506Whatever it returns is handled by Lua as if it were the return
2507of the original function.
2508
2509}
2510
2511@sect2{@title{Functions and Types}
2512
2513Here we list all functions and types from the @N{C API} in
2514alphabetical order.
2515Each function has an indicator like this:
2516@apii{o,p,x}
2517
2518The first field, @T{o},
2519is how many elements the function pops from the stack.
2520The second field, @T{p},
2521is how many elements the function pushes onto the stack.
2522(Any function always pushes its results after popping its arguments.)
2523A field in the form @T{x|y} means the function can push (or pop)
2524@T{x} or @T{y} elements,
2525depending on the situation;
2526an interrogation mark @Char{?} means that
2527we cannot know how many elements the function pops/pushes
2528by looking only at its arguments
2529(e.g., they may depend on what is on the stack).
2530The third field, @T{x},
2531tells whether the function may raise errors:
2532@Char{-} means the function never raises any error;
2533@Char{m} means the function may raise out-of-memory errors
2534and errors running a @idx{__gc} metamethod;
2535@Char{e} means the function may raise any errors
2536(it can run arbitrary Lua code,
2537either directly or through metamethods);
2538@Char{v} means the function may raise an error on purpose.
2539
2540
2541@APIEntry{int lua_absindex (lua_State *L, int idx);|
2542@apii{0,0,-}
2543
2544Converts the @x{acceptable index} @id{idx}
2545into an equivalent @x{absolute index}
2546(that is, one that does not depend on the stack top).
2547
2548}
2549
2550
2551@APIEntry{
2552typedef void * (*lua_Alloc) (void *ud,
2553 void *ptr,
2554 size_t osize,
2555 size_t nsize);|
2556
2557The type of the @x{memory-allocation function} used by Lua states.
2558The allocator function must provide a
2559functionality similar to @id{realloc},
2560but not exactly the same.
2561Its arguments are
2562@id{ud}, an opaque pointer passed to @Lid{lua_newstate};
2563@id{ptr}, a pointer to the block being allocated/reallocated/freed;
2564@id{osize}, the original size of the block or some code about what
2565is being allocated;
2566and @id{nsize}, the new size of the block.
2567
2568When @id{ptr} is not @id{NULL},
2569@id{osize} is the size of the block pointed by @id{ptr},
2570that is, the size given when it was allocated or reallocated.
2571
2572When @id{ptr} is @id{NULL},
2573@id{osize} encodes the kind of object that Lua is allocating.
2574@id{osize} is any of
2575@Lid{LUA_TSTRING}, @Lid{LUA_TTABLE}, @Lid{LUA_TFUNCTION},
2576@Lid{LUA_TUSERDATA}, or @Lid{LUA_TTHREAD} when (and only when)
2577Lua is creating a new object of that type.
2578When @id{osize} is some other value,
2579Lua is allocating memory for something else.
2580
2581Lua assumes the following behavior from the allocator function:
2582
2583When @id{nsize} is zero,
2584the allocator must behave like @id{free}
2585and return @id{NULL}.
2586
2587When @id{nsize} is not zero,
2588the allocator must behave like @id{realloc}.
2589The allocator returns @id{NULL}
2590if and only if it cannot fulfill the request.
2591Lua assumes that the allocator never fails when
2592@T{osize >= nsize}.
2593
2594Here is a simple implementation for the @x{allocator function}.
2595It is used in the auxiliary library by @Lid{luaL_newstate}.
2596@verbatim{
2597static void *l_alloc (void *ud, void *ptr, size_t osize,
2598 size_t nsize) {
2599 (void)ud; (void)osize; /* not used */
2600 if (nsize == 0) {
2601 free(ptr);
2602 return NULL;
2603 }
2604 else
2605 return realloc(ptr, nsize);
2606}
2607}
2608Note that @N{Standard C} ensures
2609that @T{free(NULL)} has no effect and that
2610@T{realloc(NULL,size)} is equivalent to @T{malloc(size)}.
2611This code assumes that @id{realloc} does not fail when shrinking a block.
2612(Although @N{Standard C} does not ensure this behavior,
2613it seems to be a safe assumption.)
2614
2615}
2616
2617@APIEntry{void lua_arith (lua_State *L, int op);|
2618@apii{2|1,1,e}
2619
2620Performs an arithmetic or bitwise operation over the two values
2621(or one, in the case of negations)
2622at the top of the stack,
2623with the value at the top being the second operand,
2624pops these values, and pushes the result of the operation.
2625The function follows the semantics of the corresponding Lua operator
2626(that is, it may call metamethods).
2627
2628The value of @id{op} must be one of the following constants:
2629@description{
2630
2631@item{@defid{LUA_OPADD}| performs addition (@T{+})}
2632@item{@defid{LUA_OPSUB}| performs subtraction (@T{-})}
2633@item{@defid{LUA_OPMUL}| performs multiplication (@T{*})}
2634@item{@defid{LUA_OPDIV}| performs float division (@T{/})}
2635@item{@defid{LUA_OPIDIV}| performs floor division (@T{//})}
2636@item{@defid{LUA_OPMOD}| performs modulo (@T{%})}
2637@item{@defid{LUA_OPPOW}| performs exponentiation (@T{^})}
2638@item{@defid{LUA_OPUNM}| performs mathematical negation (unary @T{-})}
2639@item{@defid{LUA_OPBNOT}| performs bitwise NOT (@T{~})}
2640@item{@defid{LUA_OPBAND}| performs bitwise AND (@T{&})}
2641@item{@defid{LUA_OPBOR}| performs bitwise OR (@T{|})}
2642@item{@defid{LUA_OPBXOR}| performs bitwise exclusive OR (@T{~})}
2643@item{@defid{LUA_OPSHL}| performs left shift (@T{<<})}
2644@item{@defid{LUA_OPSHR}| performs right shift (@T{>>})}
2645
2646}
2647
2648}
2649
2650@APIEntry{lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);|
2651@apii{0,0,-}
2652
2653Sets a new panic function and returns the old one @see{C-error}.
2654
2655}
2656
2657@APIEntry{void lua_call (lua_State *L, int nargs, int nresults);|
2658@apii{nargs+1,nresults,e}
2659
2660
2661Calls a function.
2662
2663To call a function you must use the following protocol:
2664first, the function to be called is pushed onto the stack;
2665then, the arguments to the function are pushed
2666in direct order;
2667that is, the first argument is pushed first.
2668Finally you call @Lid{lua_call};
2669@id{nargs} is the number of arguments that you pushed onto the stack.
2670All arguments and the function value are popped from the stack
2671when the function is called.
2672The function results are pushed onto the stack when the function returns.
2673The number of results is adjusted to @id{nresults},
2674unless @id{nresults} is @defid{LUA_MULTRET}.
2675In this case, all results from the function are pushed;
2676Lua takes care that the returned values fit into the stack space,
2677but it does not ensure any extra space in the stack.
2678The function results are pushed onto the stack in direct order
2679(the first result is pushed first),
2680so that after the call the last result is on the top of the stack.
2681
2682Any error inside the called function is propagated upwards
2683(with a @id{longjmp}).
2684
2685The following example shows how the host program can do the
2686equivalent to this Lua code:
2687@verbatim{
2688a = f("how", t.x, 14)
2689}
2690Here it is @N{in C}:
2691@verbatim{
2692lua_getglobal(L, "f"); /* function to be called */
2693lua_pushliteral(L, "how"); /* 1st argument */
2694lua_getglobal(L, "t"); /* table to be indexed */
2695lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
2696lua_remove(L, -2); /* remove 't' from the stack */
2697lua_pushinteger(L, 14); /* 3rd argument */
2698lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
2699lua_setglobal(L, "a"); /* set global 'a' */
2700}
2701Note that the code above is @emph{balanced}:
2702at its end, the stack is back to its original configuration.
2703This is considered good programming practice.
2704
2705}
2706
2707@APIEntry{
2708void lua_callk (lua_State *L,
2709 int nargs,
2710 int nresults,
2711 lua_KContext ctx,
2712 lua_KFunction k);|
2713@apii{nargs + 1,nresults,e}
2714
2715This function behaves exactly like @Lid{lua_call},
2716but allows the called function to yield @see{continuations}.
2717
2718}
2719
2720@APIEntry{typedef int (*lua_CFunction) (lua_State *L);|
2721
2722Type for @N{C functions}.
2723
2724In order to communicate properly with Lua,
2725a @N{C function} must use the following protocol,
2726which defines the way parameters and results are passed:
2727a @N{C function} receives its arguments from Lua in its stack
2728in direct order (the first argument is pushed first).
2729So, when the function starts,
2730@T{lua_gettop(L)} returns the number of arguments received by the function.
2731The first argument (if any) is at index 1
2732and its last argument is at index @T{lua_gettop(L)}.
2733To return values to Lua, a @N{C function} just pushes them onto the stack,
2734in direct order (the first result is pushed first),
2735and returns the number of results.
2736Any other value in the stack below the results will be properly
2737discarded by Lua.
2738Like a Lua function, a @N{C function} called by Lua can also return
2739many results.
2740
2741As an example, the following function receives a variable number
2742of numeric arguments and returns their average and their sum:
2743@verbatim{
2744static int foo (lua_State *L) {
2745 int n = lua_gettop(L); /* number of arguments */
2746 lua_Number sum = 0.0;
2747 int i;
2748 for (i = 1; i <= n; i++) {
2749 if (!lua_isnumber(L, i)) {
2750 lua_pushliteral(L, "incorrect argument");
2751 lua_error(L);
2752 }
2753 sum += lua_tonumber(L, i);
2754 }
2755 lua_pushnumber(L, sum/n); /* first result */
2756 lua_pushnumber(L, sum); /* second result */
2757 return 2; /* number of results */
2758}
2759}
2760
2761
2762
2763}
2764
2765
2766@APIEntry{int lua_checkstack (lua_State *L, int n);|
2767@apii{0,0,-}
2768
2769Ensures that the stack has space for at least @id{n} extra slots
2770(that is, that you can safely push up to @id{n} values into it).
2771It returns false if it cannot fulfill the request,
2772either because it would cause the stack
2773to be larger than a fixed maximum size
2774(typically at least several thousand elements) or
2775because it cannot allocate memory for the extra space.
2776This function never shrinks the stack;
2777if the stack already has space for the extra slots,
2778it is left unchanged.
2779
2780}
2781
2782@APIEntry{void lua_close (lua_State *L);|
2783@apii{0,0,-}
2784
2785Destroys all objects in the given Lua state
2786(calling the corresponding garbage-collection metamethods, if any)
2787and frees all dynamic memory used by this state.
2788In several platforms, you may not need to call this function,
2789because all resources are naturally released when the host program ends.
2790On the other hand, long-running programs that create multiple states,
2791such as daemons or web servers,
2792will probably need to close states as soon as they are not needed.
2793
2794}
2795
2796@APIEntry{int lua_compare (lua_State *L, int index1, int index2, int op);|
2797@apii{0,0,e}
2798
2799Compares two Lua values.
2800Returns 1 if the value at index @id{index1} satisfies @id{op}
2801when compared with the value at index @id{index2},
2802following the semantics of the corresponding Lua operator
2803(that is, it may call metamethods).
2804Otherwise @N{returns 0}.
2805Also @N{returns 0} if any of the indices is not valid.
2806
2807The value of @id{op} must be one of the following constants:
2808@description{
2809
2810@item{@defid{LUA_OPEQ}| compares for equality (@T{==})}
2811@item{@defid{LUA_OPLT}| compares for less than (@T{<})}
2812@item{@defid{LUA_OPLE}| compares for less or equal (@T{<=})}
2813
2814}
2815
2816}
2817
2818@APIEntry{void lua_concat (lua_State *L, int n);|
2819@apii{n,1,e}
2820
2821Concatenates the @id{n} values at the top of the stack,
2822pops them, and leaves the result at the top.
2823If @N{@T{n} is 1}, the result is the single value on the stack
2824(that is, the function does nothing);
2825if @id{n} is 0, the result is the empty string.
2826Concatenation is performed following the usual semantics of Lua
2827@see{concat}.
2828
2829}
2830
2831@APIEntry{void lua_copy (lua_State *L, int fromidx, int toidx);|
2832@apii{0,0,-}
2833
2834Copies the element at index @id{fromidx}
2835into the valid index @id{toidx},
2836replacing the value at that position.
2837Values at other positions are not affected.
2838
2839}
2840
2841@APIEntry{void lua_createtable (lua_State *L, int narr, int nrec);|
2842@apii{0,1,m}
2843
2844Creates a new empty table and pushes it onto the stack.
2845Parameter @id{narr} is a hint for how many elements the table
2846will have as a sequence;
2847parameter @id{nrec} is a hint for how many other elements
2848the table will have.
2849Lua may use these hints to preallocate memory for the new table.
2850This preallocation is useful for performance when you know in advance
2851how many elements the table will have.
2852Otherwise you can use the function @Lid{lua_newtable}.
2853
2854}
2855
2856@APIEntry{int lua_dump (lua_State *L,
2857 lua_Writer writer,
2858 void *data,
2859 int strip);|
2860@apii{0,0,-}
2861
2862Dumps a function as a binary chunk.
2863Receives a Lua function on the top of the stack
2864and produces a binary chunk that,
2865if loaded again,
2866results in a function equivalent to the one dumped.
2867As it produces parts of the chunk,
2868@Lid{lua_dump} calls function @id{writer} @seeC{lua_Writer}
2869with the given @id{data}
2870to write them.
2871
2872If @id{strip} is true,
2873the binary representation may not include all debug information
2874about the function,
2875to save space.
2876
2877The value returned is the error code returned by the last
2878call to the writer;
2879@N{0 means} no errors.
2880
2881This function does not pop the Lua function from the stack.
2882
2883}
2884
2885@APIEntry{int lua_error (lua_State *L);|
2886@apii{1,0,v}
2887
2888Generates a Lua error,
2889using the value at the top of the stack as the error object.
2890This function does a long jump,
2891and therefore never returns
2892@seeC{luaL_error}.
2893
2894}
2895
2896@APIEntry{int lua_gc (lua_State *L, int what, int data);|
2897@apii{0,0,m}
2898
2899Controls the garbage collector.
2900
2901This function performs several tasks,
2902according to the value of the parameter @id{what}:
2903@description{
2904
2905@item{@id{LUA_GCSTOP}|
2906stops the garbage collector.
2907}
2908
2909@item{@id{LUA_GCRESTART}|
2910restarts the garbage collector.
2911}
2912
2913@item{@id{LUA_GCCOLLECT}|
2914performs a full garbage-collection cycle.
2915}
2916
2917@item{@id{LUA_GCCOUNT}|
2918returns the current amount of memory (in Kbytes) in use by Lua.
2919}
2920
2921@item{@id{LUA_GCCOUNTB}|
2922returns the remainder of dividing the current amount of bytes of
2923memory in use by Lua by 1024.
2924}
2925
2926@item{@id{LUA_GCSTEP}|
2927performs an incremental step of garbage collection.
2928}
2929
2930@item{@id{LUA_GCSETPAUSE}|
2931sets @id{data} as the new value
2932for the @emph{pause} of the collector @see{GC}
2933and returns the previous value of the pause.
2934}
2935
2936@item{@id{LUA_GCSETSTEPMUL}|
2937sets @id{data} as the new value for the @emph{step multiplier} of
2938the collector @see{GC}
2939and returns the previous value of the step multiplier.
2940}
2941
2942@item{@id{LUA_GCISRUNNING}|
2943returns a boolean that tells whether the collector is running
2944(i.e., not stopped).
2945}
2946
2947}
2948
2949For more details about these options,
2950see @Lid{collectgarbage}.
2951
2952}
2953
2954@APIEntry{lua_Alloc lua_getallocf (lua_State *L, void **ud);|
2955@apii{0,0,-}
2956
2957Returns the @x{memory-allocation function} of a given state.
2958If @id{ud} is not @id{NULL}, Lua stores in @T{*ud} the
2959opaque pointer given when the memory-allocator function was set.
2960
2961}
2962
2963@APIEntry{int lua_getfield (lua_State *L, int index, const char *k);|
2964@apii{0,1,e}
2965
2966Pushes onto the stack the value @T{t[k]},
2967where @id{t} is the value at the given index.
2968As in Lua, this function may trigger a metamethod
2969for the @Q{index} event @see{metatable}.
2970
2971Returns the type of the pushed value.
2972
2973}
2974
2975@APIEntry{void *lua_getextraspace (lua_State *L);|
2976@apii{0,0,-}
2977
2978Returns a pointer to a raw memory area associated with the
2979given Lua state.
2980The application can use this area for any purpose;
2981Lua does not use it for anything.
2982
2983Each new thread has this area initialized with a copy
2984of the area of the @x{main thread}.
2985
2986By default, this area has the size of a pointer to void,
2987but you can recompile Lua with a different size for this area.
2988(See @id{LUA_EXTRASPACE} in @id{luaconf.h}.)
2989
2990}
2991
2992@APIEntry{int lua_getglobal (lua_State *L, const char *name);|
2993@apii{0,1,e}
2994
2995Pushes onto the stack the value of the global @id{name}.
2996Returns the type of that value.
2997
2998}
2999
3000@APIEntry{int lua_geti (lua_State *L, int index, lua_Integer i);|
3001@apii{0,1,e}
3002
3003Pushes onto the stack the value @T{t[i]},
3004where @id{t} is the value at the given index.
3005As in Lua, this function may trigger a metamethod
3006for the @Q{index} event @see{metatable}.
3007
3008Returns the type of the pushed value.
3009
3010}
3011
3012@APIEntry{int lua_getmetatable (lua_State *L, int index);|
3013@apii{0,0|1,-}
3014
3015If the value at the given index has a metatable,
3016the function pushes that metatable onto the stack and @N{returns 1}.
3017Otherwise,
3018the function @N{returns 0} and pushes nothing on the stack.
3019
3020}
3021
3022@APIEntry{int lua_gettable (lua_State *L, int index);|
3023@apii{1,1,e}
3024
3025Pushes onto the stack the value @T{t[k]},
3026where @id{t} is the value at the given index
3027and @id{k} is the value at the top of the stack.
3028
3029This function pops the key from the stack,
3030pushing the resulting value in its place.
3031As in Lua, this function may trigger a metamethod
3032for the @Q{index} event @see{metatable}.
3033
3034Returns the type of the pushed value.
3035
3036}
3037
3038@APIEntry{int lua_gettop (lua_State *L);|
3039@apii{0,0,-}
3040
3041Returns the index of the top element in the stack.
3042Because indices start @N{at 1},
3043this result is equal to the number of elements in the stack;
3044in particular, @N{0 means} an empty stack.
3045
3046}
3047
3048@APIEntry{int lua_getuservalue (lua_State *L, int index);|
3049@apii{0,1,-}
3050
3051Pushes onto the stack the Lua value associated with the full userdata
3052at the given index.
3053
3054Returns the type of the pushed value.
3055
3056}
3057
3058@APIEntry{void lua_insert (lua_State *L, int index);|
3059@apii{1,1,-}
3060
3061Moves the top element into the given valid index,
3062shifting up the elements above this index to open space.
3063This function cannot be called with a pseudo-index,
3064because a pseudo-index is not an actual stack position.
3065
3066}
3067
3068@APIEntry{typedef @ldots lua_Integer;|
3069
3070The type of integers in Lua.
3071
3072By default this type is @id{long long},
3073(usually a 64-bit two-complement integer),
3074but that can be changed to @id{long} or @id{int}
3075(usually a 32-bit two-complement integer).
3076(See @id{LUA_INT_TYPE} in @id{luaconf.h}.)
3077
3078Lua also defines the constants
3079@defid{LUA_MININTEGER} and @defid{LUA_MAXINTEGER},
3080with the minimum and the maximum values that fit in this type.
3081
3082}
3083
3084@APIEntry{int lua_isboolean (lua_State *L, int index);|
3085@apii{0,0,-}
3086
3087Returns 1 if the value at the given index is a boolean,
3088and @N{0 otherwise}.
3089
3090}
3091
3092@APIEntry{int lua_iscfunction (lua_State *L, int index);|
3093@apii{0,0,-}
3094
3095Returns 1 if the value at the given index is a @N{C function},
3096and @N{0 otherwise}.
3097
3098}
3099
3100@APIEntry{int lua_isfunction (lua_State *L, int index);|
3101@apii{0,0,-}
3102
3103Returns 1 if the value at the given index is a function
3104(either C or Lua), and @N{0 otherwise}.
3105
3106}
3107
3108@APIEntry{int lua_isinteger (lua_State *L, int index);|
3109@apii{0,0,-}
3110
3111Returns 1 if the value at the given index is an integer
3112(that is, the value is a number and is represented as an integer),
3113and @N{0 otherwise}.
3114
3115}
3116
3117@APIEntry{int lua_islightuserdata (lua_State *L, int index);|
3118@apii{0,0,-}
3119
3120Returns 1 if the value at the given index is a light userdata,
3121and @N{0 otherwise}.
3122
3123}
3124
3125@APIEntry{int lua_isnil (lua_State *L, int index);|
3126@apii{0,0,-}
3127
3128Returns 1 if the value at the given index is @nil,
3129and @N{0 otherwise}.
3130
3131}
3132
3133@APIEntry{int lua_isnone (lua_State *L, int index);|
3134@apii{0,0,-}
3135
3136Returns 1 if the given index is not valid,
3137and @N{0 otherwise}.
3138
3139}
3140
3141@APIEntry{int lua_isnoneornil (lua_State *L, int index);|
3142@apii{0,0,-}
3143
3144Returns 1 if the given index is not valid
3145or if the value at this index is @nil,
3146and @N{0 otherwise}.
3147
3148}
3149
3150@APIEntry{int lua_isnumber (lua_State *L, int index);|
3151@apii{0,0,-}
3152
3153Returns 1 if the value at the given index is a number
3154or a string convertible to a number,
3155and @N{0 otherwise}.
3156
3157}
3158
3159@APIEntry{int lua_isstring (lua_State *L, int index);|
3160@apii{0,0,-}
3161
3162Returns 1 if the value at the given index is a string
3163or a number (which is always convertible to a string),
3164and @N{0 otherwise}.
3165
3166}
3167
3168@APIEntry{int lua_istable (lua_State *L, int index);|
3169@apii{0,0,-}
3170
3171Returns 1 if the value at the given index is a table,
3172and @N{0 otherwise}.
3173
3174}
3175
3176@APIEntry{int lua_isthread (lua_State *L, int index);|
3177@apii{0,0,-}
3178
3179Returns 1 if the value at the given index is a thread,
3180and @N{0 otherwise}.
3181
3182}
3183
3184@APIEntry{int lua_isuserdata (lua_State *L, int index);|
3185@apii{0,0,-}
3186
3187Returns 1 if the value at the given index is a userdata
3188(either full or light), and @N{0 otherwise}.
3189
3190}
3191
3192@APIEntry{int lua_isyieldable (lua_State *L);|
3193@apii{0,0,-}
3194
3195Returns 1 if the given coroutine can yield,
3196and @N{0 otherwise}.
3197
3198}
3199
3200@APIEntry{typedef @ldots lua_KContext;|
3201
3202The type for continuation-function contexts.
3203It must be a numeric type.
3204This type is defined as @id{intptr_t}
3205when @id{intptr_t} is available,
3206so that it can store pointers too.
3207Otherwise, it is defined as @id{ptrdiff_t}.
3208
3209}
3210
3211@APIEntry{
3212typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);|
3213
3214Type for continuation functions @see{continuations}.
3215
3216}
3217
3218@APIEntry{void lua_len (lua_State *L, int index);|
3219@apii{0,1,e}
3220
3221Returns the length of the value at the given index.
3222It is equivalent to the @Char{#} operator in Lua @see{len-op} and
3223may trigger a metamethod for the @Q{length} event @see{metatable}.
3224The result is pushed on the stack.
3225
3226}
3227
3228@APIEntry{
3229int lua_load (lua_State *L,
3230 lua_Reader reader,
3231 void *data,
3232 const char *chunkname,
3233 const char *mode);|
3234@apii{0,1,-}
3235
3236Loads a Lua chunk without running it.
3237If there are no errors,
3238@id{lua_load} pushes the compiled chunk as a Lua
3239function on top of the stack.
3240Otherwise, it pushes an error message.
3241
3242The return values of @id{lua_load} are:
3243@description{
3244
3245@item{@Lid{LUA_OK}| no errors;}
3246
3247@item{@defid{LUA_ERRSYNTAX}|
3248syntax error during precompilation;}
3249
3250@item{@Lid{LUA_ERRMEM}|
3251@x{memory allocation (out-of-memory) error};}
3252
3253@item{@Lid{LUA_ERRGCMM}|
3254error while running a @idx{__gc} metamethod.
3255(This error has no relation with the chunk being loaded.
3256It is generated by the garbage collector.)
3257}
3258
3259}
3260
3261The @id{lua_load} function uses a user-supplied @id{reader} function
3262to read the chunk @seeC{lua_Reader}.
3263The @id{data} argument is an opaque value passed to the reader function.
3264
3265The @id{chunkname} argument gives a name to the chunk,
3266which is used for error messages and in debug information @see{debugI}.
3267
3268@id{lua_load} automatically detects whether the chunk is text or binary
3269and loads it accordingly (see program @idx{luac}).
3270The string @id{mode} works as in function @Lid{load},
3271with the addition that
3272a @id{NULL} value is equivalent to the string @St{bt}.
3273
3274@id{lua_load} uses the stack internally,
3275so the reader function must always leave the stack
3276unmodified when returning.
3277
3278If the resulting function has upvalues,
3279its first upvalue is set to the value of the @x{global environment}
3280stored at index @id{LUA_RIDX_GLOBALS} in the registry @see{registry}.
3281When loading main chunks,
3282this upvalue will be the @id{_ENV} variable @see{globalenv}.
3283Other upvalues are initialized with @nil.
3284
3285}
3286
3287@APIEntry{lua_State *lua_newstate (lua_Alloc f, void *ud);|
3288@apii{0,0,-}
3289
3290Creates a new thread running in a new, independent state.
3291Returns @id{NULL} if it cannot create the thread or the state
3292(due to lack of memory).
3293The argument @id{f} is the @x{allocator function};
3294Lua does all memory allocation for this state
3295through this function @seeF{lua_Alloc}.
3296The second argument, @id{ud}, is an opaque pointer that Lua
3297passes to the allocator in every call.
3298
3299}
3300
3301@APIEntry{void lua_newtable (lua_State *L);|
3302@apii{0,1,m}
3303
3304Creates a new empty table and pushes it onto the stack.
3305It is equivalent to @T{lua_createtable(L, 0, 0)}.
3306
3307}
3308
3309@APIEntry{lua_State *lua_newthread (lua_State *L);|
3310@apii{0,1,m}
3311
3312Creates a new thread, pushes it on the stack,
3313and returns a pointer to a @Lid{lua_State} that represents this new thread.
3314The new thread returned by this function shares with the original thread
3315its global environment,
3316but has an independent execution stack.
3317
3318There is no explicit function to close or to destroy a thread.
3319Threads are subject to garbage collection,
3320like any Lua object.
3321
3322}
3323
3324@APIEntry{void *lua_newuserdata (lua_State *L, size_t size);|
3325@apii{0,1,m}
3326
3327This function allocates a new block of memory with the given size,
3328pushes onto the stack a new full userdata with the block address,
3329and returns this address.
3330The host program can freely use this memory.
3331
3332}
3333
3334@APIEntry{int lua_next (lua_State *L, int index);|
3335@apii{1,2|0,e}
3336
3337Pops a key from the stack,
3338and pushes a key@En{}value pair from the table at the given index
3339(the @Q{next} pair after the given key).
3340If there are no more elements in the table,
3341then @Lid{lua_next} returns 0 (and pushes nothing).
3342
3343A typical traversal looks like this:
3344@verbatim{
3345/* table is in the stack at index 't' */
3346lua_pushnil(L); /* first key */
3347while (lua_next(L, t) != 0) {
3348 /* uses 'key' (at index -2) and 'value' (at index -1) */
3349 printf("%s - %s\n",
3350 lua_typename(L, lua_type(L, -2)),
3351 lua_typename(L, lua_type(L, -1)));
3352 /* removes 'value'; keeps 'key' for next iteration */
3353 lua_pop(L, 1);
3354}
3355}
3356
3357While traversing a table,
3358do not call @Lid{lua_tolstring} directly on a key,
3359unless you know that the key is actually a string.
3360Recall that @Lid{lua_tolstring} may change
3361the value at the given index;
3362this confuses the next call to @Lid{lua_next}.
3363
3364See function @Lid{next} for the caveats of modifying
3365the table during its traversal.
3366
3367}
3368
3369@APIEntry{typedef @ldots lua_Number;|
3370
3371The type of floats in Lua.
3372
3373By default this type is double,
3374but that can be changed to a single float or a long double.
3375(See @id{LUA_FLOAT_TYPE} in @id{luaconf.h}.)
3376
3377}
3378
3379@APIEntry{int lua_numbertointeger (lua_Number n, lua_Integer *p);|
3380
3381Converts a Lua float to a Lua integer.
3382This macro assumes that @id{n} has an integral value.
3383If that value is within the range of Lua integers,
3384it is converted to an integer and assigned to @T{*p}.
3385The macro results in a boolean indicating whether the
3386conversion was successful.
3387(Note that this range test can be tricky to do
3388correctly without this macro,
3389due to roundings.)
3390
3391This macro may evaluate its arguments more than once.
3392
3393}
3394
3395@APIEntry{int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);|
3396@apii{nargs + 1,nresults|1,-}
3397
3398Calls a function in protected mode.
3399
3400Both @id{nargs} and @id{nresults} have the same meaning as
3401in @Lid{lua_call}.
3402If there are no errors during the call,
3403@Lid{lua_pcall} behaves exactly like @Lid{lua_call}.
3404However, if there is any error,
3405@Lid{lua_pcall} catches it,
3406pushes a single value on the stack (the error object),
3407and returns an error code.
3408Like @Lid{lua_call},
3409@Lid{lua_pcall} always removes the function
3410and its arguments from the stack.
3411
3412If @id{msgh} is 0,
3413then the error object returned on the stack
3414is exactly the original error object.
3415Otherwise, @id{msgh} is the stack index of a
3416@emph{message handler}.
3417(This index cannot be a pseudo-index.)
3418In case of runtime errors,
3419this function will be called with the error object
3420and its return value will be the object
3421returned on the stack by @Lid{lua_pcall}.
3422
3423Typically, the message handler is used to add more debug
3424information to the error object, such as a stack traceback.
3425Such information cannot be gathered after the return of @Lid{lua_pcall},
3426since by then the stack has unwound.
3427
3428The @Lid{lua_pcall} function returns one of the following constants
3429(defined in @id{lua.h}):
3430@description{
3431
3432@item{@defid{LUA_OK} (0)|
3433success.}
3434
3435@item{@defid{LUA_ERRRUN}|
3436a runtime error.
3437}
3438
3439@item{@defid{LUA_ERRMEM}|
3440@x{memory allocation error}.
3441For such errors, Lua does not call the @x{message handler}.
3442}
3443
3444@item{@defid{LUA_ERRERR}|
3445error while running the @x{message handler}.
3446}
3447
3448@item{@defid{LUA_ERRGCMM}|
3449error while running a @idx{__gc} metamethod.
3450For such errors, Lua does not call the @x{message handler}
3451(as this kind of error typically has no relation
3452with the function being called).
3453}
3454
3455}
3456
3457}
3458
3459@APIEntry{
3460int lua_pcallk (lua_State *L,
3461 int nargs,
3462 int nresults,
3463 int msgh,
3464 lua_KContext ctx,
3465 lua_KFunction k);|
3466@apii{nargs + 1,nresults|1,-}
3467
3468This function behaves exactly like @Lid{lua_pcall},
3469but allows the called function to yield @see{continuations}.
3470
3471}
3472
3473@APIEntry{void lua_pop (lua_State *L, int n);|
3474@apii{n,0,-}
3475
3476Pops @id{n} elements from the stack.
3477
3478}
3479
3480@APIEntry{void lua_pushboolean (lua_State *L, int b);|
3481@apii{0,1,-}
3482
3483Pushes a boolean value with value @id{b} onto the stack.
3484
3485}
3486
3487@APIEntry{void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);|
3488@apii{n,1,m}
3489
3490Pushes a new @N{C closure} onto the stack.
3491
3492When a @N{C function} is created,
3493it is possible to associate some values with it,
3494thus creating a @x{@N{C closure}} @see{c-closure};
3495these values are then accessible to the function whenever it is called.
3496To associate values with a @N{C function},
3497first these values must be pushed onto the stack
3498(when there are multiple values, the first value is pushed first).
3499Then @Lid{lua_pushcclosure}
3500is called to create and push the @N{C function} onto the stack,
3501with the argument @id{n} telling how many values will be
3502associated with the function.
3503@Lid{lua_pushcclosure} also pops these values from the stack.
3504
3505The maximum value for @id{n} is 255.
3506
3507When @id{n} is zero,
3508this function creates a @def{light @N{C function}},
3509which is just a pointer to the @N{C function}.
3510In that case, it never raises a memory error.
3511
3512}
3513
3514@APIEntry{void lua_pushcfunction (lua_State *L, lua_CFunction f);|
3515@apii{0,1,-}
3516
3517Pushes a @N{C function} onto the stack.
3518This function receives a pointer to a @N{C function}
3519and pushes onto the stack a Lua value of type @id{function} that,
3520when called, invokes the corresponding @N{C function}.
3521
3522Any function to be callable by Lua must
3523follow the correct protocol to receive its parameters
3524and return its results @seeC{lua_CFunction}.
3525
3526}
3527
3528@APIEntry{const char *lua_pushfstring (lua_State *L, const char *fmt, ...);|
3529@apii{0,1,e}
3530
3531Pushes onto the stack a formatted string
3532and returns a pointer to this string.
3533It is similar to the @ANSI{sprintf},
3534but has some important differences:
3535@itemize{
3536
3537@item{
3538You do not have to allocate space for the result:
3539the result is a Lua string and Lua takes care of memory allocation
3540(and deallocation, through garbage collection).
3541}
3542
3543@item{
3544The conversion specifiers are quite restricted.
3545There are no flags, widths, or precisions.
3546The conversion specifiers can only be
3547@Char{%%} (inserts the character @Char{%}),
3548@Char{%s} (inserts a zero-terminated string, with no size restrictions),
3549@Char{%f} (inserts a @Lid{lua_Number}),
3550@Char{%I} (inserts a @Lid{lua_Integer}),
3551@Char{%p} (inserts a pointer as a hexadecimal numeral),
3552@Char{%d} (inserts an @T{int}),
3553@Char{%c} (inserts an @T{int} as a one-byte character), and
3554@Char{%U} (inserts a @T{long int} as a @x{UTF-8} byte sequence).
3555}
3556
3557}
3558
3559Unlike other push functions,
3560this function checks for the stack space it needs,
3561including the slot for its result.
3562
3563}
3564
3565@APIEntry{void lua_pushglobaltable (lua_State *L);|
3566@apii{0,1,-}
3567
3568Pushes the @x{global environment} onto the stack.
3569
3570}
3571
3572@APIEntry{void lua_pushinteger (lua_State *L, lua_Integer n);|
3573@apii{0,1,-}
3574
3575Pushes an integer with value @id{n} onto the stack.
3576
3577}
3578
3579@APIEntry{void lua_pushlightuserdata (lua_State *L, void *p);|
3580@apii{0,1,-}
3581
3582Pushes a light userdata onto the stack.
3583
3584Userdata represent @N{C values} in Lua.
3585A @def{light userdata} represents a pointer, a @T{void*}.
3586It is a value (like a number):
3587you do not create it, it has no individual metatable,
3588and it is not collected (as it was never created).
3589A light userdata is equal to @Q{any}
3590light userdata with the same @N{C address}.
3591
3592}
3593
3594@APIEntry{const char *lua_pushliteral (lua_State *L, const char *s);|
3595@apii{0,1,m}
3596
3597This macro is equivalent to @Lid{lua_pushstring},
3598but should be used only when @id{s} is a literal string.
3599
3600}
3601
3602@APIEntry{const char *lua_pushlstring (lua_State *L, const char *s, size_t len);|
3603@apii{0,1,m}
3604
3605Pushes the string pointed to by @id{s} with size @id{len}
3606onto the stack.
3607Lua makes (or reuses) an internal copy of the given string,
3608so the memory at @id{s} can be freed or reused immediately after
3609the function returns.
3610The string can contain any binary data,
3611including @x{embedded zeros}.
3612
3613Returns a pointer to the internal copy of the string.
3614
3615}
3616
3617@APIEntry{void lua_pushnil (lua_State *L);|
3618@apii{0,1,-}
3619
3620Pushes a nil value onto the stack.
3621
3622}
3623
3624@APIEntry{void lua_pushnumber (lua_State *L, lua_Number n);|
3625@apii{0,1,-}
3626
3627Pushes a float with value @id{n} onto the stack.
3628
3629}
3630
3631@APIEntry{const char *lua_pushstring (lua_State *L, const char *s);|
3632@apii{0,1,m}
3633
3634Pushes the zero-terminated string pointed to by @id{s}
3635onto the stack.
3636Lua makes (or reuses) an internal copy of the given string,
3637so the memory at @id{s} can be freed or reused immediately after
3638the function returns.
3639
3640Returns a pointer to the internal copy of the string.
3641
3642If @id{s} is @id{NULL}, pushes @nil and returns @id{NULL}.
3643
3644}
3645
3646@APIEntry{int lua_pushthread (lua_State *L);|
3647@apii{0,1,-}
3648
3649Pushes the thread represented by @id{L} onto the stack.
3650Returns 1 if this thread is the @x{main thread} of its state.
3651
3652}
3653
3654@APIEntry{void lua_pushvalue (lua_State *L, int index);|
3655@apii{0,1,-}
3656
3657Pushes a copy of the element at the given index
3658onto the stack.
3659
3660}
3661
3662@APIEntry{
3663const char *lua_pushvfstring (lua_State *L,
3664 const char *fmt,
3665 va_list argp);|
3666@apii{0,1,m}
3667
3668Equivalent to @Lid{lua_pushfstring}, except that it receives a @id{va_list}
3669instead of a variable number of arguments.
3670
3671}
3672
3673@APIEntry{int lua_rawequal (lua_State *L, int index1, int index2);|
3674@apii{0,0,-}
3675
3676Returns 1 if the two values in indices @id{index1} and
3677@id{index2} are primitively equal
3678(that is, without calling the @idx{__eq} metamethod).
3679Otherwise @N{returns 0}.
3680Also @N{returns 0} if any of the indices are not valid.
3681
3682}
3683
3684@APIEntry{int lua_rawget (lua_State *L, int index);|
3685@apii{1,1,-}
3686
3687Similar to @Lid{lua_gettable}, but does a raw access
3688(i.e., without metamethods).
3689
3690}
3691
3692@APIEntry{int lua_rawgeti (lua_State *L, int index, lua_Integer n);|
3693@apii{0,1,-}
3694
3695Pushes onto the stack the value @T{t[n]},
3696where @id{t} is the table at the given index.
3697The access is raw,
3698that is, it does not invoke the @idx{__index} metamethod.
3699
3700Returns the type of the pushed value.
3701
3702}
3703
3704@APIEntry{int lua_rawgetp (lua_State *L, int index, const void *p);|
3705@apii{0,1,-}
3706
3707Pushes onto the stack the value @T{t[k]},
3708where @id{t} is the table at the given index and
3709@id{k} is the pointer @id{p} represented as a light userdata.
3710The access is raw;
3711that is, it does not invoke the @idx{__index} metamethod.
3712
3713Returns the type of the pushed value.
3714
3715}
3716
3717@APIEntry{size_t lua_rawlen (lua_State *L, int index);|
3718@apii{0,0,-}
3719
3720Returns the raw @Q{length} of the value at the given index:
3721for strings, this is the string length;
3722for tables, this is the result of the length operator (@Char{#})
3723with no metamethods;
3724for userdata, this is the size of the block of memory allocated
3725for the userdata;
3726for other values, it @N{is 0}.
3727
3728}
3729
3730@APIEntry{void lua_rawset (lua_State *L, int index);|
3731@apii{2,0,m}
3732
3733Similar to @Lid{lua_settable}, but does a raw assignment
3734(i.e., without metamethods).
3735
3736}
3737
3738@APIEntry{void lua_rawseti (lua_State *L, int index, lua_Integer i);|
3739@apii{1,0,m}
3740
3741Does the equivalent of @T{t[i] = v},
3742where @id{t} is the table at the given index
3743and @id{v} is the value at the top of the stack.
3744
3745This function pops the value from the stack.
3746The assignment is raw,
3747that is, it does not invoke the @idx{__newindex} metamethod.
3748
3749}
3750
3751@APIEntry{void lua_rawsetp (lua_State *L, int index, const void *p);|
3752@apii{1,0,m}
3753
3754Does the equivalent of @T{t[p] = v},
3755where @id{t} is the table at the given index,
3756@id{p} is encoded as a light userdata,
3757and @id{v} is the value at the top of the stack.
3758
3759This function pops the value from the stack.
3760The assignment is raw,
3761that is, it does not invoke @idx{__newindex} metamethod.
3762
3763}
3764
3765@APIEntry{
3766typedef const char * (*lua_Reader) (lua_State *L,
3767 void *data,
3768 size_t *size);|
3769
3770The reader function used by @Lid{lua_load}.
3771Every time it needs another piece of the chunk,
3772@Lid{lua_load} calls the reader,
3773passing along its @id{data} parameter.
3774The reader must return a pointer to a block of memory
3775with a new piece of the chunk
3776and set @id{size} to the block size.
3777The block must exist until the reader function is called again.
3778To signal the end of the chunk,
3779the reader must return @id{NULL} or set @id{size} to zero.
3780The reader function may return pieces of any size greater than zero.
3781
3782}
3783
3784@APIEntry{void lua_register (lua_State *L, const char *name, lua_CFunction f);|
3785@apii{0,0,e}
3786
3787Sets the @N{C function} @id{f} as the new value of global @id{name}.
3788It is defined as a macro:
3789@verbatim{
3790#define lua_register(L,n,f) \
3791 (lua_pushcfunction(L, f), lua_setglobal(L, n))
3792}
3793
3794}
3795
3796@APIEntry{void lua_remove (lua_State *L, int index);|
3797@apii{1,0,-}
3798
3799Removes the element at the given valid index,
3800shifting down the elements above this index to fill the gap.
3801This function cannot be called with a pseudo-index,
3802because a pseudo-index is not an actual stack position.
3803
3804}
3805
3806@APIEntry{void lua_replace (lua_State *L, int index);|
3807@apii{1,0,-}
3808
3809Moves the top element into the given valid index
3810without shifting any element
3811(therefore replacing the value at that given index),
3812and then pops the top element.
3813
3814}
3815
3816@APIEntry{int lua_resume (lua_State *L, lua_State *from, int nargs);|
3817@apii{?,?,-}
3818
3819Starts and resumes a coroutine in the given thread @id{L}.
3820
3821To start a coroutine,
3822you push onto the thread stack the main function plus any arguments;
3823then you call @Lid{lua_resume},
3824with @id{nargs} being the number of arguments.
3825This call returns when the coroutine suspends or finishes its execution.
3826When it returns, the stack contains all values passed to @Lid{lua_yield},
3827or all values returned by the body function.
3828@Lid{lua_resume} returns
3829@Lid{LUA_YIELD} if the coroutine yields,
3830@Lid{LUA_OK} if the coroutine finishes its execution
3831without errors,
3832or an error code in case of errors @seeC{lua_pcall}.
3833
3834In case of errors,
3835the stack is not unwound,
3836so you can use the debug API over it.
3837The error object is on the top of the stack.
3838
3839To resume a coroutine,
3840you remove any results from the last @Lid{lua_yield},
3841put on its stack only the values to
3842be passed as results from @id{yield},
3843and then call @Lid{lua_resume}.
3844
3845The parameter @id{from} represents the coroutine that is resuming @id{L}.
3846If there is no such coroutine,
3847this parameter can be @id{NULL}.
3848
3849}
3850
3851@APIEntry{void lua_rotate (lua_State *L, int idx, int n);|
3852@apii{0,0,-}
3853
3854Rotates the stack elements between the valid index @id{idx}
3855and the top of the stack.
3856The elements are rotated @id{n} positions in the direction of the top,
3857for a positive @id{n},
3858or @T{-n} positions in the direction of the bottom,
3859for a negative @id{n}.
3860The absolute value of @id{n} must not be greater than the size
3861of the slice being rotated.
3862This function cannot be called with a pseudo-index,
3863because a pseudo-index is not an actual stack position.
3864
3865}
3866
3867@APIEntry{void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);|
3868@apii{0,0,-}
3869
3870Changes the @x{allocator function} of a given state to @id{f}
3871with user data @id{ud}.
3872
3873}
3874
3875@APIEntry{void lua_setfield (lua_State *L, int index, const char *k);|
3876@apii{1,0,e}
3877
3878Does the equivalent to @T{t[k] = v},
3879where @id{t} is the value at the given index
3880and @id{v} is the value at the top of the stack.
3881
3882This function pops the value from the stack.
3883As in Lua, this function may trigger a metamethod
3884for the @Q{newindex} event @see{metatable}.
3885
3886}
3887
3888@APIEntry{void lua_setglobal (lua_State *L, const char *name);|
3889@apii{1,0,e}
3890
3891Pops a value from the stack and
3892sets it as the new value of global @id{name}.
3893
3894}
3895
3896@APIEntry{void lua_seti (lua_State *L, int index, lua_Integer n);|
3897@apii{1,0,e}
3898
3899Does the equivalent to @T{t[n] = v},
3900where @id{t} is the value at the given index
3901and @id{v} is the value at the top of the stack.
3902
3903This function pops the value from the stack.
3904As in Lua, this function may trigger a metamethod
3905for the @Q{newindex} event @see{metatable}.
3906
3907}
3908
3909@APIEntry{void lua_setmetatable (lua_State *L, int index);|
3910@apii{1,0,-}
3911
3912Pops a table from the stack and
3913sets it as the new metatable for the value at the given index.
3914
3915}
3916
3917@APIEntry{void lua_settable (lua_State *L, int index);|
3918@apii{2,0,e}
3919
3920Does the equivalent to @T{t[k] = v},
3921where @id{t} is the value at the given index,
3922@id{v} is the value at the top of the stack,
3923and @id{k} is the value just below the top.
3924
3925This function pops both the key and the value from the stack.
3926As in Lua, this function may trigger a metamethod
3927for the @Q{newindex} event @see{metatable}.
3928
3929}
3930
3931@APIEntry{void lua_settop (lua_State *L, int index);|
3932@apii{?,?,-}
3933
3934Accepts any index, @N{or 0},
3935and sets the stack top to this index.
3936If the new top is larger than the old one,
3937then the new elements are filled with @nil.
3938If @id{index} @N{is 0}, then all stack elements are removed.
3939
3940}
3941
3942@APIEntry{void lua_setuservalue (lua_State *L, int index);|
3943@apii{1,0,-}
3944
3945Pops a value from the stack and sets it as
3946the new value associated to the full userdata at the given index.
3947
3948}
3949
3950@APIEntry{typedef struct lua_State lua_State;|
3951
3952An opaque structure that points to a thread and indirectly
3953(through the thread) to the whole state of a Lua interpreter.
3954The Lua library is fully reentrant:
3955it has no global variables.
3956All information about a state is accessible through this structure.
3957
3958A pointer to this structure must be passed as the first argument to
3959every function in the library, except to @Lid{lua_newstate},
3960which creates a Lua state from scratch.
3961
3962}
3963
3964@APIEntry{int lua_status (lua_State *L);|
3965@apii{0,0,-}
3966
3967Returns the status of the thread @id{L}.
3968
3969The status can be 0 (@Lid{LUA_OK}) for a normal thread,
3970an error code if the thread finished the execution
3971of a @Lid{lua_resume} with an error,
3972or @defid{LUA_YIELD} if the thread is suspended.
3973
3974You can only call functions in threads with status @Lid{LUA_OK}.
3975You can resume threads with status @Lid{LUA_OK}
3976(to start a new coroutine) or @Lid{LUA_YIELD}
3977(to resume a coroutine).
3978
3979}
3980
3981@APIEntry{size_t lua_stringtonumber (lua_State *L, const char *s);|
3982@apii{0,1,-}
3983
3984Converts the zero-terminated string @id{s} to a number,
3985pushes that number into the stack,
3986and returns the total size of the string,
3987that is, its length plus one.
3988The conversion can result in an integer or a float,
3989according to the lexical conventions of Lua @see{lexical}.
3990The string may have leading and trailing spaces and a sign.
3991If the string is not a valid numeral,
3992returns 0 and pushes nothing.
3993(Note that the result can be used as a boolean,
3994true if the conversion succeeds.)
3995
3996}
3997
3998@APIEntry{int lua_toboolean (lua_State *L, int index);|
3999@apii{0,0,-}
4000
4001Converts the Lua value at the given index to a @N{C boolean}
4002value (@N{0 or 1}).
4003Like all tests in Lua,
4004@Lid{lua_toboolean} returns true for any Lua value
4005different from @false and @nil;
4006otherwise it returns false.
4007(If you want to accept only actual boolean values,
4008use @Lid{lua_isboolean} to test the value's type.)
4009
4010}
4011
4012@APIEntry{lua_CFunction lua_tocfunction (lua_State *L, int index);|
4013@apii{0,0,-}
4014
4015Converts a value at the given index to a @N{C function}.
4016That value must be a @N{C function};
4017otherwise, returns @id{NULL}.
4018
4019}
4020
4021@APIEntry{lua_Integer lua_tointeger (lua_State *L, int index);|
4022@apii{0,0,-}
4023
4024Equivalent to @Lid{lua_tointegerx} with @id{isnum} equal to @id{NULL}.
4025
4026}
4027
4028@APIEntry{lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);|
4029@apii{0,0,-}
4030
4031Converts the Lua value at the given index
4032to the signed integral type @Lid{lua_Integer}.
4033The Lua value must be an integer,
4034or a number or string convertible to an integer @see{coercion};
4035otherwise, @id{lua_tointegerx} @N{returns 0}.
4036
4037If @id{isnum} is not @id{NULL},
4038its referent is assigned a boolean value that
4039indicates whether the operation succeeded.
4040
4041}
4042
4043@APIEntry{const char *lua_tolstring (lua_State *L, int index, size_t *len);|
4044@apii{0,0,m}
4045
4046Converts the Lua value at the given index to a @N{C string}.
4047If @id{len} is not @id{NULL},
4048it sets @T{*len} with the string length.
4049The Lua value must be a string or a number;
4050otherwise, the function returns @id{NULL}.
4051If the value is a number,
4052then @id{lua_tolstring} also
4053@emph{changes the actual value in the stack to a string}.
4054(This change confuses @Lid{lua_next}
4055when @id{lua_tolstring} is applied to keys during a table traversal.)
4056
4057@id{lua_tolstring} returns a pointer
4058to a string inside the Lua state.
4059This string always has a zero (@Char{\0})
4060after its last character (as @N{in C}),
4061but can contain other zeros in its body.
4062
4063Because Lua has garbage collection,
4064there is no guarantee that the pointer returned by @id{lua_tolstring}
4065will be valid after the corresponding Lua value is removed from the stack.
4066
4067}
4068
4069@APIEntry{lua_Number lua_tonumber (lua_State *L, int index);|
4070@apii{0,0,-}
4071
4072Equivalent to @Lid{lua_tonumberx} with @id{isnum} equal to @id{NULL}.
4073
4074}
4075
4076@APIEntry{lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);|
4077@apii{0,0,-}
4078
4079Converts the Lua value at the given index
4080to the @N{C type} @Lid{lua_Number} @seeC{lua_Number}.
4081The Lua value must be a number or a string convertible to a number
4082@see{coercion};
4083otherwise, @Lid{lua_tonumberx} @N{returns 0}.
4084
4085If @id{isnum} is not @id{NULL},
4086its referent is assigned a boolean value that
4087indicates whether the operation succeeded.
4088
4089}
4090
4091@APIEntry{const void *lua_topointer (lua_State *L, int index);|
4092@apii{0,0,-}
4093
4094Converts the value at the given index to a generic
4095@N{C pointer} (@T{void*}).
4096The value can be a userdata, a table, a thread, or a function;
4097otherwise, @id{lua_topointer} returns @id{NULL}.
4098Different objects will give different pointers.
4099There is no way to convert the pointer back to its original value.
4100
4101Typically this function is used only for hashing and debug information.
4102
4103}
4104
4105@APIEntry{const char *lua_tostring (lua_State *L, int index);|
4106@apii{0,0,m}
4107
4108Equivalent to @Lid{lua_tolstring} with @id{len} equal to @id{NULL}.
4109
4110}
4111
4112@APIEntry{lua_State *lua_tothread (lua_State *L, int index);|
4113@apii{0,0,-}
4114
4115Converts the value at the given index to a Lua thread
4116(represented as @T{lua_State*}).
4117This value must be a thread;
4118otherwise, the function returns @id{NULL}.
4119
4120}
4121
4122@APIEntry{void *lua_touserdata (lua_State *L, int index);|
4123@apii{0,0,-}
4124
4125If the value at the given index is a full userdata,
4126returns its block address.
4127If the value is a light userdata,
4128returns its pointer.
4129Otherwise, returns @id{NULL}.
4130
4131}
4132
4133@APIEntry{int lua_type (lua_State *L, int index);|
4134@apii{0,0,-}
4135
4136Returns the type of the value in the given valid index,
4137or @id{LUA_TNONE} for a non-valid (but acceptable) index.
4138The types returned by @Lid{lua_type} are coded by the following constants
4139defined in @id{lua.h}:
4140@defid{LUA_TNIL} (0),
4141@defid{LUA_TNUMBER},
4142@defid{LUA_TBOOLEAN},
4143@defid{LUA_TSTRING},
4144@defid{LUA_TTABLE},
4145@defid{LUA_TFUNCTION},
4146@defid{LUA_TUSERDATA},
4147@defid{LUA_TTHREAD},
4148and
4149@defid{LUA_TLIGHTUSERDATA}.
4150
4151}
4152
4153@APIEntry{const char *lua_typename (lua_State *L, int tp);|
4154@apii{0,0,-}
4155
4156Returns the name of the type encoded by the value @id{tp},
4157which must be one the values returned by @Lid{lua_type}.
4158
4159}
4160
4161@APIEntry{typedef @ldots lua_Unsigned;|
4162
4163The unsigned version of @Lid{lua_Integer}.
4164
4165}
4166
4167@APIEntry{int lua_upvalueindex (int i);|
4168@apii{0,0,-}
4169
4170Returns the pseudo-index that represents the @id{i}-th upvalue of
4171the running function @see{c-closure}.
4172
4173}
4174
4175@APIEntry{const lua_Number *lua_version (lua_State *L);|
4176@apii{0,0,-}
4177
4178Returns the address of the version number
4179(a C static variable)
4180stored in the Lua core.
4181When called with a valid @Lid{lua_State},
4182returns the address of the version used to create that state.
4183When called with @id{NULL},
4184returns the address of the version running the call.
4185
4186}
4187
4188@APIEntry{
4189typedef int (*lua_Writer) (lua_State *L,
4190 const void* p,
4191 size_t sz,
4192 void* ud);|
4193
4194The type of the writer function used by @Lid{lua_dump}.
4195Every time it produces another piece of chunk,
4196@Lid{lua_dump} calls the writer,
4197passing along the buffer to be written (@id{p}),
4198its size (@id{sz}),
4199and the @id{data} parameter supplied to @Lid{lua_dump}.
4200
4201The writer returns an error code:
4202@N{0 means} no errors;
4203any other value means an error and stops @Lid{lua_dump} from
4204calling the writer again.
4205
4206}
4207
4208@APIEntry{void lua_xmove (lua_State *from, lua_State *to, int n);|
4209@apii{?,?,-}
4210
4211Exchange values between different threads of the same state.
4212
4213This function pops @id{n} values from the stack @id{from},
4214and pushes them onto the stack @id{to}.
4215
4216}
4217
4218@APIEntry{int lua_yield (lua_State *L, int nresults);|
4219@apii{?,?,e}
4220
4221This function is equivalent to @Lid{lua_yieldk},
4222but it has no continuation @see{continuations}.
4223Therefore, when the thread resumes,
4224it continues the function that called
4225the function calling @id{lua_yield}.
4226
4227}
4228
4229
4230@APIEntry{
4231int lua_yieldk (lua_State *L,
4232 int nresults,
4233 lua_KContext ctx,
4234 lua_KFunction k);|
4235@apii{?,?,e}
4236
4237Yields a coroutine (thread).
4238
4239When a @N{C function} calls @Lid{lua_yieldk},
4240the running coroutine suspends its execution,
4241and the call to @Lid{lua_resume} that started this coroutine returns.
4242The parameter @id{nresults} is the number of values from the stack
4243that will be passed as results to @Lid{lua_resume}.
4244
4245When the coroutine is resumed again,
4246Lua calls the given @x{continuation function} @id{k} to continue
4247the execution of the @N{C function} that yielded @see{continuations}.
4248This continuation function receives the same stack
4249from the previous function,
4250with the @id{n} results removed and
4251replaced by the arguments passed to @Lid{lua_resume}.
4252Moreover,
4253the continuation function receives the value @id{ctx}
4254that was passed to @Lid{lua_yieldk}.
4255
4256Usually, this function does not return;
4257when the coroutine eventually resumes,
4258it continues executing the continuation function.
4259However, there is one special case,
4260which is when this function is called
4261from inside a line or a count hook @see{debugI}.
4262In that case, @id{lua_yieldk} should be called with no continuation
4263(probably in the form of @Lid{lua_yield}) and no results,
4264and the hook should return immediately after the call.
4265Lua will yield and,
4266when the coroutine resumes again,
4267it will continue the normal execution
4268of the (Lua) function that triggered the hook.
4269
4270This function can raise an error if it is called from a thread
4271with a pending C call with no continuation function,
4272or it is called from a thread that is not running inside a resume
4273(e.g., the main thread).
4274
4275}
4276
4277}
4278
4279@sect2{debugI| @title{The Debug Interface}
4280
4281Lua has no built-in debugging facilities.
4282Instead, it offers a special interface
4283by means of functions and @emph{hooks}.
4284This interface allows the construction of different
4285kinds of debuggers, profilers, and other tools
4286that need @Q{inside information} from the interpreter.
4287
4288
4289@APIEntry{
4290typedef struct lua_Debug {
4291 int event;
4292 const char *name; /* (n) */
4293 const char *namewhat; /* (n) */
4294 const char *what; /* (S) */
4295 const char *source; /* (S) */
4296 int currentline; /* (l) */
4297 int linedefined; /* (S) */
4298 int lastlinedefined; /* (S) */
4299 unsigned char nups; /* (u) number of upvalues */
4300 unsigned char nparams; /* (u) number of parameters */
4301 char isvararg; /* (u) */
4302 char istailcall; /* (t) */
4303 char short_src[LUA_IDSIZE]; /* (S) */
4304 /* private part */
4305 @rep{other fields}
4306} lua_Debug;
4307|
4308
4309A structure used to carry different pieces of
4310information about a function or an activation record.
4311@Lid{lua_getstack} fills only the private part
4312of this structure, for later use.
4313To fill the other fields of @Lid{lua_Debug} with useful information,
4314call @Lid{lua_getinfo}.
4315
4316The fields of @Lid{lua_Debug} have the following meaning:
4317@description{
4318
4319@item{@id{source}|
4320the name of the chunk that created the function.
4321If @T{source} starts with a @Char{@At},
4322it means that the function was defined in a file where
4323the file name follows the @Char{@At}.
4324If @T{source} starts with a @Char{=},
4325the remainder of its contents describe the source in a user-dependent manner.
4326Otherwise,
4327the function was defined in a string where
4328@T{source} is that string.
4329}
4330
4331@item{@id{short_src}|
4332a @Q{printable} version of @T{source}, to be used in error messages.
4333}
4334
4335@item{@id{linedefined}|
4336the line number where the definition of the function starts.
4337}
4338
4339@item{@id{lastlinedefined}|
4340the line number where the definition of the function ends.
4341}
4342
4343@item{@id{what}|
4344the string @T{"Lua"} if the function is a Lua function,
4345@T{"C"} if it is a @N{C function},
4346@T{"main"} if it is the main part of a chunk.
4347}
4348
4349@item{@id{currentline}|
4350the current line where the given function is executing.
4351When no line information is available,
4352@T{currentline} is set to @num{-1}.
4353}
4354
4355@item{@id{name}|
4356a reasonable name for the given function.
4357Because functions in Lua are first-class values,
4358they do not have a fixed name:
4359some functions can be the value of multiple global variables,
4360while others can be stored only in a table field.
4361The @T{lua_getinfo} function checks how the function was
4362called to find a suitable name.
4363If it cannot find a name,
4364then @id{name} is set to @id{NULL}.
4365}
4366
4367@item{@id{namewhat}|
4368explains the @T{name} field.
4369The value of @T{namewhat} can be
4370@T{"global"}, @T{"local"}, @T{"method"},
4371@T{"field"}, @T{"upvalue"}, or @T{""} (the empty string),
4372according to how the function was called.
4373(Lua uses the empty string when no other option seems to apply.)
4374}
4375
4376@item{@id{istailcall}|
4377true if this function invocation was called by a tail call.
4378In this case, the caller of this level is not in the stack.
4379}
4380
4381@item{@id{nups}|
4382the number of upvalues of the function.
4383}
4384
4385@item{@id{nparams}|
4386the number of fixed parameters of the function
4387(always @N{0 for} @N{C functions}).
4388}
4389
4390@item{@id{isvararg}|
4391true if the function is a vararg function
4392(always true for @N{C functions}).
4393}
4394
4395}
4396
4397}
4398
4399@APIEntry{lua_Hook lua_gethook (lua_State *L);|
4400@apii{0,0,-}
4401
4402Returns the current hook function.
4403
4404}
4405
4406@APIEntry{int lua_gethookcount (lua_State *L);|
4407@apii{0,0,-}
4408
4409Returns the current hook count.
4410
4411}
4412
4413@APIEntry{int lua_gethookmask (lua_State *L);|
4414@apii{0,0,-}
4415
4416Returns the current hook mask.
4417
4418}
4419
4420@APIEntry{int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);|
4421@apii{0|1,0|1|2,e}
4422
4423Gets information about a specific function or function invocation.
4424
4425To get information about a function invocation,
4426the parameter @id{ar} must be a valid activation record that was
4427filled by a previous call to @Lid{lua_getstack} or
4428given as argument to a hook @seeC{lua_Hook}.
4429
4430To get information about a function, you push it onto the stack
4431and start the @id{what} string with the character @Char{>}.
4432(In that case,
4433@id{lua_getinfo} pops the function from the top of the stack.)
4434For instance, to know in which line a function @id{f} was defined,
4435you can write the following code:
4436@verbatim{
4437lua_Debug ar;
4438lua_getglobal(L, "f"); /* get global 'f' */
4439lua_getinfo(L, ">S", &ar);
4440printf("%d\n", ar.linedefined);
4441}
4442
4443Each character in the string @id{what}
4444selects some fields of the structure @id{ar} to be filled or
4445a value to be pushed on the stack:
4446@description{
4447
4448@item{@Char{n}| fills in the field @id{name} and @id{namewhat};
4449}
4450
4451@item{@Char{S}|
4452fills in the fields @id{source}, @id{short_src},
4453@id{linedefined}, @id{lastlinedefined}, and @id{what};
4454}
4455
4456@item{@Char{l}| fills in the field @id{currentline};
4457}
4458
4459@item{@Char{t}| fills in the field @id{istailcall};
4460}
4461
4462@item{@Char{u}| fills in the fields
4463@id{nups}, @id{nparams}, and @id{isvararg};
4464}
4465
4466@item{@Char{f}|
4467pushes onto the stack the function that is
4468running at the given level;
4469}
4470
4471@item{@Char{L}|
4472pushes onto the stack a table whose indices are the
4473numbers of the lines that are valid on the function.
4474(A @emph{valid line} is a line with some associated code,
4475that is, a line where you can put a break point.
4476Non-valid lines include empty lines and comments.)
4477
4478If this option is given together with option @Char{f},
4479its table is pushed after the function.
4480}
4481
4482}
4483
4484This function returns 0 on error
4485(for instance, an invalid option in @id{what}).
4486
4487}
4488
4489@APIEntry{const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);|
4490@apii{0,0|1,-}
4491
4492Gets information about a local variable of
4493a given activation record or a given function.
4494
4495In the first case,
4496the parameter @id{ar} must be a valid activation record that was
4497filled by a previous call to @Lid{lua_getstack} or
4498given as argument to a hook @seeC{lua_Hook}.
4499The index @id{n} selects which local variable to inspect;
4500see @Lid{debug.getlocal} for details about variable indices
4501and names.
4502
4503@Lid{lua_getlocal} pushes the variable's value onto the stack
4504and returns its name.
4505
4506In the second case, @id{ar} must be @id{NULL} and the function
4507to be inspected must be at the top of the stack.
4508In this case, only parameters of Lua functions are visible
4509(as there is no information about what variables are active)
4510and no values are pushed onto the stack.
4511
4512Returns @id{NULL} (and pushes nothing)
4513when the index is greater than
4514the number of active local variables.
4515
4516}
4517
4518@APIEntry{int lua_getstack (lua_State *L, int level, lua_Debug *ar);|
4519@apii{0,0,-}
4520
4521Gets information about the interpreter runtime stack.
4522
4523This function fills parts of a @Lid{lua_Debug} structure with
4524an identification of the @emph{activation record}
4525of the function executing at a given level.
4526@N{Level 0} is the current running function,
4527whereas level @M{n+1} is the function that has called level @M{n}
4528(except for tail calls, which do not count on the stack).
4529When there are no errors, @Lid{lua_getstack} returns 1;
4530when called with a level greater than the stack depth,
4531it returns 0.
4532
4533}
4534
4535@APIEntry{const char *lua_getupvalue (lua_State *L, int funcindex, int n);|
4536@apii{0,0|1,-}
4537
4538Gets information about the @id{n}-th upvalue
4539of the closure at index @id{funcindex}.
4540It pushes the upvalue's value onto the stack
4541and returns its name.
4542Returns @id{NULL} (and pushes nothing)
4543when the index @id{n} is greater than the number of upvalues.
4544
4545For @N{C functions}, this function uses the empty string @T{""}
4546as a name for all upvalues.
4547(For Lua functions,
4548upvalues are the external local variables that the function uses,
4549and that are consequently included in its closure.)
4550
4551Upvalues have no particular order,
4552as they are active through the whole function.
4553They are numbered in an arbitrary order.
4554
4555}
4556
4557@APIEntry{typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);|
4558
4559Type for debugging hook functions.
4560
4561Whenever a hook is called, its @id{ar} argument has its field
4562@id{event} set to the specific event that triggered the hook.
4563Lua identifies these events with the following constants:
4564@defid{LUA_HOOKCALL}, @defid{LUA_HOOKRET},
4565@defid{LUA_HOOKTAILCALL}, @defid{LUA_HOOKLINE},
4566and @defid{LUA_HOOKCOUNT}.
4567Moreover, for line events, the field @id{currentline} is also set.
4568To get the value of any other field in @id{ar},
4569the hook must call @Lid{lua_getinfo}.
4570
4571For call events, @id{event} can be @id{LUA_HOOKCALL},
4572the normal value, or @id{LUA_HOOKTAILCALL}, for a tail call;
4573in this case, there will be no corresponding return event.
4574
4575While Lua is running a hook, it disables other calls to hooks.
4576Therefore, if a hook calls back Lua to execute a function or a chunk,
4577this execution occurs without any calls to hooks.
4578
4579Hook functions cannot have continuations,
4580that is, they cannot call @Lid{lua_yieldk},
4581@Lid{lua_pcallk}, or @Lid{lua_callk} with a non-null @id{k}.
4582
4583Hook functions can yield under the following conditions:
4584Only count and line events can yield;
4585to yield, a hook function must finish its execution
4586calling @Lid{lua_yield} with @id{nresults} equal to zero
4587(that is, with no values).
4588
4589}
4590
4591@APIEntry{void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);|
4592@apii{0,0,-}
4593
4594Sets the debugging hook function.
4595
4596Argument @id{f} is the hook function.
4597@id{mask} specifies on which events the hook will be called:
4598it is formed by a bitwise OR of the constants
4599@defid{LUA_MASKCALL},
4600@defid{LUA_MASKRET},
4601@defid{LUA_MASKLINE},
4602and @defid{LUA_MASKCOUNT}.
4603The @id{count} argument is only meaningful when the mask
4604includes @id{LUA_MASKCOUNT}.
4605For each event, the hook is called as explained below:
4606@description{
4607
4608@item{The call hook| is called when the interpreter calls a function.
4609The hook is called just after Lua enters the new function,
4610before the function gets its arguments.
4611}
4612
4613@item{The return hook| is called when the interpreter returns from a function.
4614The hook is called just before Lua leaves the function.
4615There is no standard way to access the values
4616to be returned by the function.
4617}
4618
4619@item{The line hook| is called when the interpreter is about to
4620start the execution of a new line of code,
4621or when it jumps back in the code (even to the same line).
4622(This event only happens while Lua is executing a Lua function.)
4623}
4624
4625@item{The count hook| is called after the interpreter executes every
4626@T{count} instructions.
4627(This event only happens while Lua is executing a Lua function.)
4628}
4629
4630}
4631
4632A hook is disabled by setting @id{mask} to zero.
4633
4634}
4635
4636@APIEntry{const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);|
4637@apii{0|1,0,-}
4638
4639Sets the value of a local variable of a given activation record.
4640It assigns the value at the top of the stack
4641to the variable and returns its name.
4642It also pops the value from the stack.
4643
4644Returns @id{NULL} (and pops nothing)
4645when the index is greater than
4646the number of active local variables.
4647
4648Parameters @id{ar} and @id{n} are as in function @Lid{lua_getlocal}.
4649
4650}
4651
4652@APIEntry{const char *lua_setupvalue (lua_State *L, int funcindex, int n);|
4653@apii{0|1,0,-}
4654
4655Sets the value of a closure's upvalue.
4656It assigns the value at the top of the stack
4657to the upvalue and returns its name.
4658It also pops the value from the stack.
4659
4660Returns @id{NULL} (and pops nothing)
4661when the index @id{n} is greater than the number of upvalues.
4662
4663Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue}.
4664
4665}
4666
4667@APIEntry{void *lua_upvalueid (lua_State *L, int funcindex, int n);|
4668@apii{0,0,-}
4669
4670Returns a unique identifier for the upvalue numbered @id{n}
4671from the closure at index @id{funcindex}.
4672
4673These unique identifiers allow a program to check whether different
4674closures share upvalues.
4675Lua closures that share an upvalue
4676(that is, that access a same external local variable)
4677will return identical ids for those upvalue indices.
4678
4679Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue},
4680but @id{n} cannot be greater than the number of upvalues.
4681
4682}
4683
4684@APIEntry{
4685void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
4686 int funcindex2, int n2);|
4687@apii{0,0,-}
4688
4689Make the @id{n1}-th upvalue of the Lua closure at index @id{funcindex1}
4690refer to the @id{n2}-th upvalue of the Lua closure at index @id{funcindex2}.
4691
4692}
4693
4694}
4695
4696}
4697
4698
4699@C{-------------------------------------------------------------------------}
4700@sect1{@title{The Auxiliary Library}
4701
4702@index{lauxlib.h}
4703The @def{auxiliary library} provides several convenient functions
4704to interface C with Lua.
4705While the basic API provides the primitive functions for all
4706interactions between C and Lua,
4707the auxiliary library provides higher-level functions for some
4708common tasks.
4709
4710All functions and types from the auxiliary library
4711are defined in header file @id{lauxlib.h} and
4712have a prefix @id{luaL_}.
4713
4714All functions in the auxiliary library are built on
4715top of the basic API,
4716and so they provide nothing that cannot be done with that API.
4717Nevertheless, the use of the auxiliary library ensures
4718more consistency to your code.
4719
4720
4721Several functions in the auxiliary library use internally some
4722extra stack slots.
4723When a function in the auxiliary library uses less than five slots,
4724it does not check the stack size;
4725it simply assumes that there are enough slots.
4726
4727Several functions in the auxiliary library are used to
4728check @N{C function} arguments.
4729Because the error message is formatted for arguments
4730(e.g., @St{bad argument #1}),
4731you should not use these functions for other stack values.
4732
4733Functions called @id{luaL_check*}
4734always raise an error if the check is not satisfied.
4735
4736@sect2{@title{Functions and Types}
4737
4738Here we list all functions and types from the auxiliary library
4739in alphabetical order.
4740
4741
4742@APIEntry{void luaL_addchar (luaL_Buffer *B, char c);|
4743@apii{?,?,m}
4744
4745Adds the byte @id{c} to the buffer @id{B}
4746@seeC{luaL_Buffer}.
4747
4748}
4749
4750@APIEntry{void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);|
4751@apii{?,?,m}
4752
4753Adds the string pointed to by @id{s} with length @id{l} to
4754the buffer @id{B}
4755@seeC{luaL_Buffer}.
4756The string can contain @x{embedded zeros}.
4757
4758}
4759
4760@APIEntry{void luaL_addsize (luaL_Buffer *B, size_t n);|
4761@apii{?,?,-}
4762
4763Adds to the buffer @id{B} @seeC{luaL_Buffer}
4764a string of length @id{n} previously copied to the
4765buffer area @seeC{luaL_prepbuffer}.
4766
4767}
4768
4769@APIEntry{void luaL_addstring (luaL_Buffer *B, const char *s);|
4770@apii{?,?,m}
4771
4772Adds the zero-terminated string pointed to by @id{s}
4773to the buffer @id{B}
4774@seeC{luaL_Buffer}.
4775
4776}
4777
4778@APIEntry{void luaL_addvalue (luaL_Buffer *B);|
4779@apii{1,?,m}
4780
4781Adds the value at the top of the stack
4782to the buffer @id{B}
4783@seeC{luaL_Buffer}.
4784Pops the value.
4785
4786This is the only function on string buffers that can (and must)
4787be called with an extra element on the stack,
4788which is the value to be added to the buffer.
4789
4790}
4791
4792@APIEntry{
4793void luaL_argcheck (lua_State *L,
4794 int cond,
4795 int arg,
4796 const char *extramsg);|
4797@apii{0,0,v}
4798
4799Checks whether @id{cond} is true.
4800If it is not, raises an error with a standard message @seeF{luaL_argerror}.
4801
4802}
4803
4804@APIEntry{int luaL_argerror (lua_State *L, int arg, const char *extramsg);|
4805@apii{0,0,v}
4806
4807Raises an error reporting a problem with argument @id{arg}
4808of the @N{C function} that called it,
4809using a standard message
4810that includes @id{extramsg} as a comment:
4811@verbatim{
4812bad argument #@rep{arg} to '@rep{funcname}' (@rep{extramsg})
4813}
4814This function never returns.
4815
4816}
4817
4818@APIEntry{typedef struct luaL_Buffer luaL_Buffer;|
4819
4820Type for a @def{string buffer}.
4821
4822A string buffer allows @N{C code} to build Lua strings piecemeal.
4823Its pattern of use is as follows:
4824@itemize{
4825
4826@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
4827
4828@item{Then initialize it with a call @T{luaL_buffinit(L, &b)}.}
4829
4830@item{
4831Then add string pieces to the buffer calling any of
4832the @id{luaL_add*} functions.
4833}
4834
4835@item{
4836Finish by calling @T{luaL_pushresult(&b)}.
4837This call leaves the final string on the top of the stack.
4838}
4839
4840}
4841
4842If you know beforehand the total size of the resulting string,
4843you can use the buffer like this:
4844@itemize{
4845
4846@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
4847
4848@item{Then initialize it and preallocate a space of
4849size @id{sz} with a call @T{luaL_buffinitsize(L, &b, sz)}.}
4850
4851@item{Then copy the string into that space.}
4852
4853@item{
4854Finish by calling @T{luaL_pushresultsize(&b, sz)},
4855where @id{sz} is the total size of the resulting string
4856copied into that space.
4857}
4858
4859}
4860
4861During its normal operation,
4862a string buffer uses a variable number of stack slots.
4863So, while using a buffer, you cannot assume that you know where
4864the top of the stack is.
4865You can use the stack between successive calls to buffer operations
4866as long as that use is balanced;
4867that is,
4868when you call a buffer operation,
4869the stack is at the same level
4870it was immediately after the previous buffer operation.
4871(The only exception to this rule is @Lid{luaL_addvalue}.)
4872After calling @Lid{luaL_pushresult} the stack is back to its
4873level when the buffer was initialized,
4874plus the final string on its top.
4875
4876}
4877
4878@APIEntry{void luaL_buffinit (lua_State *L, luaL_Buffer *B);|
4879@apii{0,0,-}
4880
4881Initializes a buffer @id{B}.
4882This function does not allocate any space;
4883the buffer must be declared as a variable
4884@seeC{luaL_Buffer}.
4885
4886}
4887
4888@APIEntry{char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);|
4889@apii{?,?,m}
4890
4891Equivalent to the sequence
4892@Lid{luaL_buffinit}, @Lid{luaL_prepbuffsize}.
4893
4894}
4895
4896@APIEntry{int luaL_callmeta (lua_State *L, int obj, const char *e);|
4897@apii{0,0|1,e}
4898
4899Calls a metamethod.
4900
4901If the object at index @id{obj} has a metatable and this
4902metatable has a field @id{e},
4903this function calls this field passing the object as its only argument.
4904In this case this function returns true and pushes onto the
4905stack the value returned by the call.
4906If there is no metatable or no metamethod,
4907this function returns false (without pushing any value on the stack).
4908
4909}
4910
4911@APIEntry{void luaL_checkany (lua_State *L, int arg);|
4912@apii{0,0,v}
4913
4914Checks whether the function has an argument
4915of any type (including @nil) at position @id{arg}.
4916
4917}
4918
4919@APIEntry{lua_Integer luaL_checkinteger (lua_State *L, int arg);|
4920@apii{0,0,v}
4921
4922Checks whether the function argument @id{arg} is an integer
4923(or can be converted to an integer)
4924and returns this integer cast to a @Lid{lua_Integer}.
4925
4926}
4927
4928@APIEntry{const char *luaL_checklstring (lua_State *L, int arg, size_t *l);|
4929@apii{0,0,v}
4930
4931Checks whether the function argument @id{arg} is a string
4932and returns this string;
4933if @id{l} is not @id{NULL} fills @T{*l}
4934with the string's length.
4935
4936This function uses @Lid{lua_tolstring} to get its result,
4937so all conversions and caveats of that function apply here.
4938
4939}
4940
4941@APIEntry{lua_Number luaL_checknumber (lua_State *L, int arg);|
4942@apii{0,0,v}
4943
4944Checks whether the function argument @id{arg} is a number
4945and returns this number.
4946
4947}
4948
4949@APIEntry{
4950int luaL_checkoption (lua_State *L,
4951 int arg,
4952 const char *def,
4953 const char *const lst[]);|
4954@apii{0,0,v}
4955
4956Checks whether the function argument @id{arg} is a string and
4957searches for this string in the array @id{lst}
4958(which must be NULL-terminated).
4959Returns the index in the array where the string was found.
4960Raises an error if the argument is not a string or
4961if the string cannot be found.
4962
4963If @id{def} is not @id{NULL},
4964the function uses @id{def} as a default value when
4965there is no argument @id{arg} or when this argument is @nil.
4966
4967This is a useful function for mapping strings to @N{C enums}.
4968(The usual convention in Lua libraries is
4969to use strings instead of numbers to select options.)
4970
4971}
4972
4973@APIEntry{void luaL_checkstack (lua_State *L, int sz, const char *msg);|
4974@apii{0,0,v}
4975
4976Grows the stack size to @T{top + sz} elements,
4977raising an error if the stack cannot grow to that size.
4978@id{msg} is an additional text to go into the error message
4979(or @id{NULL} for no additional text).
4980
4981}
4982
4983@APIEntry{const char *luaL_checkstring (lua_State *L, int arg);|
4984@apii{0,0,v}
4985
4986Checks whether the function argument @id{arg} is a string
4987and returns this string.
4988
4989This function uses @Lid{lua_tolstring} to get its result,
4990so all conversions and caveats of that function apply here.
4991
4992}
4993
4994@APIEntry{void luaL_checktype (lua_State *L, int arg, int t);|
4995@apii{0,0,v}
4996
4997Checks whether the function argument @id{arg} has type @id{t}.
4998See @Lid{lua_type} for the encoding of types for @id{t}.
4999
5000}
5001
5002@APIEntry{void *luaL_checkudata (lua_State *L, int arg, const char *tname);|
5003@apii{0,0,v}
5004
5005Checks whether the function argument @id{arg} is a userdata
5006of the type @id{tname} @seeC{luaL_newmetatable} and
5007returns the userdata address @seeC{lua_touserdata}.
5008
5009}
5010
5011@APIEntry{void luaL_checkversion (lua_State *L);|
5012@apii{0,0,v}
5013
5014Checks whether the core running the call,
5015the core that created the Lua state,
5016and the code making the call are all using the same version of Lua.
5017Also checks whether the core running the call
5018and the core that created the Lua state
5019are using the same address space.
5020
5021}
5022
5023@APIEntry{int luaL_dofile (lua_State *L, const char *filename);|
5024@apii{0,?,e}
5025
5026Loads and runs the given file.
5027It is defined as the following macro:
5028@verbatim{
5029(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
5030}
5031It returns false if there are no errors
5032or true in case of errors.
5033
5034}
5035
5036@APIEntry{int luaL_dostring (lua_State *L, const char *str);|
5037@apii{0,?,-}
5038
5039Loads and runs the given string.
5040It is defined as the following macro:
5041@verbatim{
5042(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
5043}
5044It returns false if there are no errors
5045or true in case of errors.
5046
5047}
5048
5049@APIEntry{int luaL_error (lua_State *L, const char *fmt, ...);|
5050@apii{0,0,v}
5051
5052Raises an error.
5053The error message format is given by @id{fmt}
5054plus any extra arguments,
5055following the same rules of @Lid{lua_pushfstring}.
5056It also adds at the beginning of the message the file name and
5057the line number where the error occurred,
5058if this information is available.
5059
5060This function never returns,
5061but it is an idiom to use it in @N{C functions}
5062as @T{return luaL_error(@rep{args})}.
5063
5064}
5065
5066@APIEntry{int luaL_execresult (lua_State *L, int stat);|
5067@apii{0,3,m}
5068
5069This function produces the return values for
5070process-related functions in the standard library
5071(@Lid{os.execute} and @Lid{io.close}).
5072
5073}
5074
5075@APIEntry{
5076int luaL_fileresult (lua_State *L, int stat, const char *fname);|
5077@apii{0,1|3,m}
5078
5079This function produces the return values for
5080file-related functions in the standard library
5081(@Lid{io.open}, @Lid{os.rename}, @Lid{file:seek}, etc.).
5082
5083}
5084
5085@APIEntry{int luaL_getmetafield (lua_State *L, int obj, const char *e);|
5086@apii{0,0|1,m}
5087
5088Pushes onto the stack the field @id{e} from the metatable
5089of the object at index @id{obj} and returns the type of the pushed value.
5090If the object does not have a metatable,
5091or if the metatable does not have this field,
5092pushes nothing and returns @id{LUA_TNIL}.
5093
5094}
5095
5096@APIEntry{int luaL_getmetatable (lua_State *L, const char *tname);|
5097@apii{0,1,m}
5098
5099Pushes onto the stack the metatable associated with name @id{tname}
5100in the registry @seeC{luaL_newmetatable}
5101(@nil if there is no metatable associated with that name).
5102Returns the type of the pushed value.
5103
5104}
5105
5106@APIEntry{int luaL_getsubtable (lua_State *L, int idx, const char *fname);|
5107@apii{0,1,e}
5108
5109Ensures that the value @T{t[fname]},
5110where @id{t} is the value at index @id{idx},
5111is a table,
5112and pushes that table onto the stack.
5113Returns true if it finds a previous table there
5114and false if it creates a new table.
5115
5116}
5117
5118@APIEntry{
5119const char *luaL_gsub (lua_State *L,
5120 const char *s,
5121 const char *p,
5122 const char *r);|
5123@apii{0,1,m}
5124
5125Creates a copy of string @id{s} by replacing
5126any occurrence of the string @id{p}
5127with the string @id{r}.
5128Pushes the resulting string on the stack and returns it.
5129
5130}
5131
5132@APIEntry{lua_Integer luaL_len (lua_State *L, int index);|
5133@apii{0,0,e}
5134
5135Returns the @Q{length} of the value at the given index
5136as a number;
5137it is equivalent to the @Char{#} operator in Lua @see{len-op}.
5138Raises an error if the result of the operation is not an integer.
5139(This case only can happen through metamethods.)
5140
5141}
5142
5143@APIEntry{
5144int luaL_loadbuffer (lua_State *L,
5145 const char *buff,
5146 size_t sz,
5147 const char *name);|
5148@apii{0,1,-}
5149
5150Equivalent to @Lid{luaL_loadbufferx} with @id{mode} equal to @id{NULL}.
5151
5152}
5153
5154
5155@APIEntry{
5156int luaL_loadbufferx (lua_State *L,
5157 const char *buff,
5158 size_t sz,
5159 const char *name,
5160 const char *mode);|
5161@apii{0,1,-}
5162
5163Loads a buffer as a Lua chunk.
5164This function uses @Lid{lua_load} to load the chunk in the
5165buffer pointed to by @id{buff} with size @id{sz}.
5166
5167This function returns the same results as @Lid{lua_load}.
5168@id{name} is the chunk name,
5169used for debug information and error messages.
5170The string @id{mode} works as in function @Lid{lua_load}.
5171
5172}
5173
5174
5175@APIEntry{int luaL_loadfile (lua_State *L, const char *filename);|
5176@apii{0,1,m}
5177
5178Equivalent to @Lid{luaL_loadfilex} with @id{mode} equal to @id{NULL}.
5179
5180}
5181
5182@APIEntry{int luaL_loadfilex (lua_State *L, const char *filename,
5183 const char *mode);|
5184@apii{0,1,m}
5185
5186Loads a file as a Lua chunk.
5187This function uses @Lid{lua_load} to load the chunk in the file
5188named @id{filename}.
5189If @id{filename} is @id{NULL},
5190then it loads from the standard input.
5191The first line in the file is ignored if it starts with a @T{#}.
5192
5193The string @id{mode} works as in function @Lid{lua_load}.
5194
5195This function returns the same results as @Lid{lua_load},
5196but it has an extra error code @defid{LUA_ERRFILE}
5197for file-related errors
5198(e.g., it cannot open or read the file).
5199
5200As @Lid{lua_load}, this function only loads the chunk;
5201it does not run it.
5202
5203}
5204
5205@APIEntry{int luaL_loadstring (lua_State *L, const char *s);|
5206@apii{0,1,-}
5207
5208Loads a string as a Lua chunk.
5209This function uses @Lid{lua_load} to load the chunk in
5210the zero-terminated string @id{s}.
5211
5212This function returns the same results as @Lid{lua_load}.
5213
5214Also as @Lid{lua_load}, this function only loads the chunk;
5215it does not run it.
5216
5217}
5218
5219
5220@APIEntry{void luaL_newlib (lua_State *L, const luaL_Reg l[]);|
5221@apii{0,1,m}
5222
5223Creates a new table and registers there
5224the functions in list @id{l}.
5225
5226It is implemented as the following macro:
5227@verbatim{
5228(luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
5229}
5230The array @id{l} must be the actual array,
5231not a pointer to it.
5232
5233}
5234
5235@APIEntry{void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);|
5236@apii{0,1,m}
5237
5238Creates a new table with a size optimized
5239to store all entries in the array @id{l}
5240(but does not actually store them).
5241It is intended to be used in conjunction with @Lid{luaL_setfuncs}
5242@seeF{luaL_newlib}.
5243
5244It is implemented as a macro.
5245The array @id{l} must be the actual array,
5246not a pointer to it.
5247
5248}
5249
5250@APIEntry{int luaL_newmetatable (lua_State *L, const char *tname);|
5251@apii{0,1,m}
5252
5253If the registry already has the key @id{tname},
5254returns 0.
5255Otherwise,
5256creates a new table to be used as a metatable for userdata,
5257adds to this new table the pair @T{__name = tname},
5258adds to the registry the pair @T{[tname] = new table},
5259and returns 1.
5260(The entry @idx{__name} is used by some error-reporting functions.)
5261
5262In both cases pushes onto the stack the final value associated
5263with @id{tname} in the registry.
5264
5265}
5266
5267@APIEntry{lua_State *luaL_newstate (void);|
5268@apii{0,0,-}
5269
5270Creates a new Lua state.
5271It calls @Lid{lua_newstate} with an
5272allocator based on the @N{standard C} @id{realloc} function
5273and then sets a panic function @see{C-error} that prints
5274an error message to the standard error output in case of fatal
5275errors.
5276
5277Returns the new state,
5278or @id{NULL} if there is a @x{memory allocation error}.
5279
5280}
5281
5282@APIEntry{void luaL_openlibs (lua_State *L);|
5283@apii{0,0,e}
5284
5285Opens all standard Lua libraries into the given state.
5286
5287}
5288
5289@APIEntry{
5290T luaL_opt (L, func, arg, dflt);|
5291@apii{0,0,e}
5292
5293This macro is defined as follows:
5294@verbatim{
5295(lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
5296}
5297In words, if the argument @id{arg} is nil or absent,
5298the macro results in the default @id{dflt}.
5299Otherwise, it results in the result of calling @id{func}
5300with the state @id{L} and the argument index @id{arg} as
5301arguments.
5302Note that it evaluates the expression @id{dflt} only if needed.
5303
5304}
5305
5306@APIEntry{
5307lua_Integer luaL_optinteger (lua_State *L,
5308 int arg,
5309 lua_Integer d);|
5310@apii{0,0,v}
5311
5312If the function argument @id{arg} is an integer
5313(or convertible to an integer),
5314returns this integer.
5315If this argument is absent or is @nil,
5316returns @id{d}.
5317Otherwise, raises an error.
5318
5319}
5320
5321@APIEntry{
5322const char *luaL_optlstring (lua_State *L,
5323 int arg,
5324 const char *d,
5325 size_t *l);|
5326@apii{0,0,v}
5327
5328If the function argument @id{arg} is a string,
5329returns this string.
5330If this argument is absent or is @nil,
5331returns @id{d}.
5332Otherwise, raises an error.
5333
5334If @id{l} is not @id{NULL},
5335fills the position @T{*l} with the result's length.
5336If the result is @id{NULL}
5337(only possible when returning @id{d} and @T{d == NULL}),
5338its length is considered zero.
5339
5340This function uses @Lid{lua_tolstring} to get its result,
5341so all conversions and caveats of that function apply here.
5342
5343}
5344
5345@APIEntry{lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);|
5346@apii{0,0,v}
5347
5348If the function argument @id{arg} is a number,
5349returns this number.
5350If this argument is absent or is @nil,
5351returns @id{d}.
5352Otherwise, raises an error.
5353
5354}
5355
5356@APIEntry{
5357const char *luaL_optstring (lua_State *L,
5358 int arg,
5359 const char *d);|
5360@apii{0,0,v}
5361
5362If the function argument @id{arg} is a string,
5363returns this string.
5364If this argument is absent or is @nil,
5365returns @id{d}.
5366Otherwise, raises an error.
5367
5368}
5369
5370@APIEntry{char *luaL_prepbuffer (luaL_Buffer *B);|
5371@apii{?,?,m}
5372
5373Equivalent to @Lid{luaL_prepbuffsize}
5374with the predefined size @defid{LUAL_BUFFERSIZE}.
5375
5376}
5377
5378@APIEntry{char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);|
5379@apii{?,?,m}
5380
5381Returns an address to a space of size @id{sz}
5382where you can copy a string to be added to buffer @id{B}
5383@seeC{luaL_Buffer}.
5384After copying the string into this space you must call
5385@Lid{luaL_addsize} with the size of the string to actually add
5386it to the buffer.
5387
5388}
5389
5390@APIEntry{void luaL_pushresult (luaL_Buffer *B);|
5391@apii{?,1,m}
5392
5393Finishes the use of buffer @id{B} leaving the final string on
5394the top of the stack.
5395
5396}
5397
5398@APIEntry{void luaL_pushresultsize (luaL_Buffer *B, size_t sz);|
5399@apii{?,1,m}
5400
5401Equivalent to the sequence @Lid{luaL_addsize}, @Lid{luaL_pushresult}.
5402
5403}
5404
5405@APIEntry{int luaL_ref (lua_State *L, int t);|
5406@apii{1,0,m}
5407
5408Creates and returns a @def{reference},
5409in the table at index @id{t},
5410for the object at the top of the stack (and pops the object).
5411
5412A reference is a unique integer key.
5413As long as you do not manually add integer keys into table @id{t},
5414@Lid{luaL_ref} ensures the uniqueness of the key it returns.
5415You can retrieve an object referred by reference @id{r}
5416by calling @T{lua_rawgeti(L, t, r)}.
5417Function @Lid{luaL_unref} frees a reference and its associated object.
5418
5419If the object at the top of the stack is @nil,
5420@Lid{luaL_ref} returns the constant @defid{LUA_REFNIL}.
5421The constant @defid{LUA_NOREF} is guaranteed to be different
5422from any reference returned by @Lid{luaL_ref}.
5423
5424}
5425
5426@APIEntry{
5427typedef struct luaL_Reg {
5428 const char *name;
5429 lua_CFunction func;
5430} luaL_Reg;
5431|
5432
5433Type for arrays of functions to be registered by
5434@Lid{luaL_setfuncs}.
5435@id{name} is the function name and @id{func} is a pointer to
5436the function.
5437Any array of @Lid{luaL_Reg} must end with a sentinel entry
5438in which both @id{name} and @id{func} are @id{NULL}.
5439
5440}
5441
5442@APIEntry{
5443void luaL_requiref (lua_State *L, const char *modname,
5444 lua_CFunction openf, int glb);|
5445@apii{0,1,e}
5446
5447If @id{modname} is not already present in @Lid{package.loaded},
5448calls function @id{openf} with string @id{modname} as an argument
5449and sets the call result in @T{package.loaded[modname]},
5450as if that function has been called through @Lid{require}.
5451
5452If @id{glb} is true,
5453also stores the module into global @id{modname}.
5454
5455Leaves a copy of the module on the stack.
5456
5457}
5458
5459@APIEntry{void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);|
5460@apii{nup,0,m}
5461
5462Registers all functions in the array @id{l}
5463@seeC{luaL_Reg} into the table on the top of the stack
5464(below optional upvalues, see next).
5465
5466When @id{nup} is not zero,
5467all functions are created sharing @id{nup} upvalues,
5468which must be previously pushed on the stack
5469on top of the library table.
5470These values are popped from the stack after the registration.
5471
5472}
5473
5474@APIEntry{void luaL_setmetatable (lua_State *L, const char *tname);|
5475@apii{0,0,-}
5476
5477Sets the metatable of the object at the top of the stack
5478as the metatable associated with name @id{tname}
5479in the registry @seeC{luaL_newmetatable}.
5480
5481}
5482
5483@APIEntry{
5484typedef struct luaL_Stream {
5485 FILE *f;
5486 lua_CFunction closef;
5487} luaL_Stream;
5488|
5489
5490The standard representation for @x{file handles},
5491which is used by the standard I/O library.
5492
5493A file handle is implemented as a full userdata,
5494with a metatable called @id{LUA_FILEHANDLE}
5495(where @id{LUA_FILEHANDLE} is a macro with the actual metatable's name).
5496The metatable is created by the I/O library
5497@seeF{luaL_newmetatable}.
5498
5499This userdata must start with the structure @id{luaL_Stream};
5500it can contain other data after this initial structure.
5501Field @id{f} points to the corresponding C stream
5502(or it can be @id{NULL} to indicate an incompletely created handle).
5503Field @id{closef} points to a Lua function
5504that will be called to close the stream
5505when the handle is closed or collected;
5506this function receives the file handle as its sole argument and
5507must return either @Rw{true} (in case of success)
5508or @nil plus an error message (in case of error).
5509Once Lua calls this field,
5510it changes the field value to @id{NULL}
5511to signal that the handle is closed.
5512
5513}
5514
5515@APIEntry{void *luaL_testudata (lua_State *L, int arg, const char *tname);|
5516@apii{0,0,m}
5517
5518This function works like @Lid{luaL_checkudata},
5519except that, when the test fails,
5520it returns @id{NULL} instead of raising an error.
5521
5522}
5523
5524@APIEntry{const char *luaL_tolstring (lua_State *L, int idx, size_t *len);|
5525@apii{0,1,e}
5526
5527Converts any Lua value at the given index to a @N{C string}
5528in a reasonable format.
5529The resulting string is pushed onto the stack and also
5530returned by the function.
5531If @id{len} is not @id{NULL},
5532the function also sets @T{*len} with the string length.
5533
5534If the value has a metatable with a @idx{__tostring} field,
5535then @id{luaL_tolstring} calls the corresponding metamethod
5536with the value as argument,
5537and uses the result of the call as its result.
5538
5539}
5540
5541@APIEntry{
5542void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
5543 int level);|
5544@apii{0,1,m}
5545
5546Creates and pushes a traceback of the stack @id{L1}.
5547If @id{msg} is not @id{NULL} it is appended
5548at the beginning of the traceback.
5549The @id{level} parameter tells at which level
5550to start the traceback.
5551
5552}
5553
5554@APIEntry{const char *luaL_typename (lua_State *L, int index);|
5555@apii{0,0,-}
5556
5557Returns the name of the type of the value at the given index.
5558
5559}
5560
5561@APIEntry{void luaL_unref (lua_State *L, int t, int ref);|
5562@apii{0,0,-}
5563
5564Releases reference @id{ref} from the table at index @id{t}
5565@seeC{luaL_ref}.
5566The entry is removed from the table,
5567so that the referred object can be collected.
5568The reference @id{ref} is also freed to be used again.
5569
5570If @id{ref} is @Lid{LUA_NOREF} or @Lid{LUA_REFNIL},
5571@Lid{luaL_unref} does nothing.
5572
5573}
5574
5575@APIEntry{void luaL_where (lua_State *L, int lvl);|
5576@apii{0,1,m}
5577
5578Pushes onto the stack a string identifying the current position
5579of the control at level @id{lvl} in the call stack.
5580Typically this string has the following format:
5581@verbatim{
5582@rep{chunkname}:@rep{currentline}:
5583}
5584@N{Level 0} is the running function,
5585@N{level 1} is the function that called the running function,
5586etc.
5587
5588This function is used to build a prefix for error messages.
5589
5590}
5591
5592}
5593
5594}
5595
5596
5597@C{-------------------------------------------------------------------------}
5598@sect1{libraries| @title{Standard Libraries}
5599
5600The standard Lua libraries provide useful functions
5601that are implemented directly through the @N{C API}.
5602Some of these functions provide essential services to the language
5603(e.g., @Lid{type} and @Lid{getmetatable});
5604others provide access to @Q{outside} services (e.g., I/O);
5605and others could be implemented in Lua itself,
5606but are quite useful or have critical performance requirements that
5607deserve an implementation in C (e.g., @Lid{table.sort}).
5608
5609All libraries are implemented through the official @N{C API}
5610and are provided as separate @N{C modules}.
5611Currently, Lua has the following standard libraries:
5612@itemize{
5613
5614@item{@link{predefined|basic library};}
5615
5616@item{@link{corolib|coroutine library};}
5617
5618@item{@link{packlib|package library};}
5619
5620@item{@link{strlib|string manipulation};}
5621
5622@item{@link{utf8|basic UTF-8 support};}
5623
5624@item{@link{tablib|table manipulation};}
5625
5626@item{@link{mathlib|mathematical functions} (sin, log, etc.);}
5627
5628@item{@link{iolib|input and output};}
5629
5630@item{@link{oslib|operating system facilities};}
5631
5632@item{@link{debuglib|debug facilities}.}
5633
5634}
5635Except for the basic and the package libraries,
5636each library provides all its functions as fields of a global table
5637or as methods of its objects.
5638
5639To have access to these libraries,
5640the @N{C host} program should call the @Lid{luaL_openlibs} function,
5641which opens all standard libraries.
5642Alternatively,
5643the host program can open them individually by using
5644@Lid{luaL_requiref} to call
5645@defid{luaopen_base} (for the basic library),
5646@defid{luaopen_package} (for the package library),
5647@defid{luaopen_coroutine} (for the coroutine library),
5648@defid{luaopen_string} (for the string library),
5649@defid{luaopen_utf8} (for the UTF8 library),
5650@defid{luaopen_table} (for the table library),
5651@defid{luaopen_math} (for the mathematical library),
5652@defid{luaopen_io} (for the I/O library),
5653@defid{luaopen_os} (for the operating system library),
5654and @defid{luaopen_debug} (for the debug library).
5655These functions are declared in @defid{lualib.h}.
5656
5657@sect2{predefined| @title{Basic Functions}
5658
5659The basic library provides core functions to Lua.
5660If you do not include this library in your application,
5661you should check carefully whether you need to provide
5662implementations for some of its facilities.
5663
5664
5665@LibEntry{assert (v [, message])|
5666
5667Calls @Lid{error} if
5668the value of its argument @id{v} is false (i.e., @nil or @false);
5669otherwise, returns all its arguments.
5670In case of error,
5671@id{message} is the error object;
5672when absent, it defaults to @St{assertion failed!}
5673
5674}
5675
5676@LibEntry{collectgarbage ([opt [, arg]])|
5677
5678This function is a generic interface to the garbage collector.
5679It performs different functions according to its first argument, @id{opt}:
5680@description{
5681
5682@item{@St{collect}|
5683performs a full garbage-collection cycle.
5684This is the default option.
5685}
5686
5687@item{@St{stop}|
5688stops automatic execution of the garbage collector.
5689The collector will run only when explicitly invoked,
5690until a call to restart it.
5691}
5692
5693@item{@St{restart}|
5694restarts automatic execution of the garbage collector.
5695}
5696
5697@item{@St{count}|
5698returns the total memory in use by Lua in Kbytes.
5699The value has a fractional part,
5700so that it multiplied by 1024
5701gives the exact number of bytes in use by Lua
5702(except for overflows).
5703}
5704
5705@item{@St{step}|
5706performs a garbage-collection step.
5707The step @Q{size} is controlled by @id{arg}.
5708With a zero value,
5709the collector will perform one basic (indivisible) step.
5710For non-zero values,
5711the collector will perform as if that amount of memory
5712(in KBytes) had been allocated by Lua.
5713Returns @Rw{true} if the step finished a collection cycle.
5714}
5715
5716@item{@St{setpause}|
5717sets @id{arg} as the new value for the @emph{pause} of
5718the collector @see{GC}.
5719Returns the previous value for @emph{pause}.
5720}
5721
5722@item{@St{setstepmul}|
5723sets @id{arg} as the new value for the @emph{step multiplier} of
5724the collector @see{GC}.
5725Returns the previous value for @emph{step}.
5726}
5727
5728@item{@St{isrunning}|
5729returns a boolean that tells whether the collector is running
5730(i.e., not stopped).
5731}
5732
5733}
5734
5735}
5736
5737@LibEntry{dofile ([filename])|
5738Opens the named file and executes its contents as a Lua chunk.
5739When called without arguments,
5740@id{dofile} executes the contents of the standard input (@id{stdin}).
5741Returns all values returned by the chunk.
5742In case of errors, @id{dofile} propagates the error
5743to its caller (that is, @id{dofile} does not run in protected mode).
5744
5745}
5746
5747@LibEntry{error (message [, level])|
5748Terminates the last protected function called
5749and returns @id{message} as the error object.
5750Function @id{error} never returns.
5751
5752Usually, @id{error} adds some information about the error position
5753at the beginning of the message, if the message is a string.
5754The @id{level} argument specifies how to get the error position.
5755With @N{level 1} (the default), the error position is where the
5756@id{error} function was called.
5757@N{Level 2} points the error to where the function
5758that called @id{error} was called; and so on.
5759Passing a @N{level 0} avoids the addition of error position information
5760to the message.
5761
5762}
5763
5764@LibEntry{_G|
5765A global variable (not a function) that
5766holds the @x{global environment} @see{globalenv}.
5767Lua itself does not use this variable;
5768changing its value does not affect any environment,
5769nor vice versa.
5770
5771}
5772
5773@LibEntry{getmetatable (object)|
5774
5775If @id{object} does not have a metatable, returns @nil.
5776Otherwise,
5777if the object's metatable has a @idx{__metatable} field,
5778returns the associated value.
5779Otherwise, returns the metatable of the given object.
5780
5781}
5782
5783@LibEntry{ipairs (t)|
5784
5785Returns three values (an iterator function, the table @id{t}, and 0)
5786so that the construction
5787@verbatim{
5788for i,v in ipairs(t) do @rep{body} end
5789}
5790will iterate over the key@En{}value pairs
5791(@T{1,t[1]}), (@T{2,t[2]}), @ldots,
5792up to the first nil value.
5793
5794}
5795
5796@LibEntry{load (chunk [, chunkname [, mode [, env]]])|
5797
5798Loads a chunk.
5799
5800If @id{chunk} is a string, the chunk is this string.
5801If @id{chunk} is a function,
5802@id{load} calls it repeatedly to get the chunk pieces.
5803Each call to @id{chunk} must return a string that concatenates
5804with previous results.
5805A return of an empty string, @nil, or no value signals the end of the chunk.
5806
5807If there are no syntactic errors,
5808returns the compiled chunk as a function;
5809otherwise, returns @nil plus the error message.
5810
5811If the resulting function has upvalues,
5812the first upvalue is set to the value of @id{env},
5813if that parameter is given,
5814or to the value of the @x{global environment}.
5815Other upvalues are initialized with @nil.
5816(When you load a main chunk,
5817the resulting function will always have exactly one upvalue,
5818the @id{_ENV} variable @see{globalenv}.
5819However,
5820when you load a binary chunk created from a function @seeF{string.dump},
5821the resulting function can have an arbitrary number of upvalues.)
5822All upvalues are fresh, that is,
5823they are not shared with any other function.
5824
5825@id{chunkname} is used as the name of the chunk for error messages
5826and debug information @see{debugI}.
5827When absent,
5828it defaults to @id{chunk}, if @id{chunk} is a string,
5829or to @St{=(load)} otherwise.
5830
5831The string @id{mode} controls whether the chunk can be text or binary
5832(that is, a precompiled chunk).
5833It may be the string @St{b} (only @x{binary chunk}s),
5834@St{t} (only text chunks),
5835or @St{bt} (both binary and text).
5836The default is @St{bt}.
5837
5838Lua does not check the consistency of binary chunks.
5839Maliciously crafted binary chunks can crash
5840the interpreter.
5841
5842}
5843
5844@LibEntry{loadfile ([filename [, mode [, env]]])|
5845
5846Similar to @Lid{load},
5847but gets the chunk from file @id{filename}
5848or from the standard input,
5849if no file name is given.
5850
5851}
5852
5853@LibEntry{next (table [, index])|
5854
5855Allows a program to traverse all fields of a table.
5856Its first argument is a table and its second argument
5857is an index in this table.
5858@id{next} returns the next index of the table
5859and its associated value.
5860When called with @nil as its second argument,
5861@id{next} returns an initial index
5862and its associated value.
5863When called with the last index,
5864or with @nil in an empty table,
5865@id{next} returns @nil.
5866If the second argument is absent, then it is interpreted as @nil.
5867In particular,
5868you can use @T{next(t)} to check whether a table is empty.
5869
5870The order in which the indices are enumerated is not specified,
5871@emph{even for numeric indices}.
5872(To traverse a table in numerical order,
5873use a numerical @Rw{for}.)
5874
5875The behavior of @id{next} is undefined if,
5876during the traversal,
5877you assign any value to a non-existent field in the table.
5878You may however modify existing fields.
5879In particular, you may clear existing fields.
5880
5881}
5882
5883@LibEntry{pairs (t)|
5884
5885If @id{t} has a metamethod @idx{__pairs},
5886calls it with @id{t} as argument and returns the first three
5887results from the call.
5888
5889Otherwise,
5890returns three values: the @Lid{next} function, the table @id{t}, and @nil,
5891so that the construction
5892@verbatim{
5893for k,v in pairs(t) do @rep{body} end
5894}
5895will iterate over all key@En{}value pairs of table @id{t}.
5896
5897See function @Lid{next} for the caveats of modifying
5898the table during its traversal.
5899
5900}
5901
5902@LibEntry{pcall (f [, arg1, @Cdots])|
5903
5904Calls function @id{f} with
5905the given arguments in @def{protected mode}.
5906This means that any error @N{inside @T{f}} is not propagated;
5907instead, @id{pcall} catches the error
5908and returns a status code.
5909Its first result is the status code (a boolean),
5910which is true if the call succeeds without errors.
5911In such case, @id{pcall} also returns all results from the call,
5912after this first result.
5913In case of any error, @id{pcall} returns @false plus the error message.
5914
5915}
5916
5917@LibEntry{print (@Cdots)|
5918Receives any number of arguments
5919and prints their values to @id{stdout},
5920using the @Lid{tostring} function to convert each argument to a string.
5921@id{print} is not intended for formatted output,
5922but only as a quick way to show a value,
5923for instance for debugging.
5924For complete control over the output,
5925use @Lid{string.format} and @Lid{io.write}.
5926
5927}
5928
5929@LibEntry{rawequal (v1, v2)|
5930Checks whether @id{v1} is equal to @id{v2},
5931without invoking the @idx{__eq} metamethod.
5932Returns a boolean.
5933
5934}
5935
5936@LibEntry{rawget (table, index)|
5937Gets the real value of @T{table[index]},
5938without invoking the @idx{__index} metamethod.
5939@id{table} must be a table;
5940@id{index} may be any value.
5941
5942}
5943
5944@LibEntry{rawlen (v)|
5945Returns the length of the object @id{v},
5946which must be a table or a string,
5947without invoking the @idx{__len} metamethod.
5948Returns an integer.
5949
5950}
5951
5952@LibEntry{rawset (table, index, value)|
5953Sets the real value of @T{table[index]} to @id{value},
5954without invoking the @idx{__newindex} metamethod.
5955@id{table} must be a table,
5956@id{index} any value different from @nil and @x{NaN},
5957and @id{value} any Lua value.
5958
5959This function returns @id{table}.
5960
5961}
5962
5963@LibEntry{select (index, @Cdots)|
5964
5965If @id{index} is a number,
5966returns all arguments after argument number @id{index};
5967a negative number indexes from the end (@num{-1} is the last argument).
5968Otherwise, @id{index} must be the string @T{"#"},
5969and @id{select} returns the total number of extra arguments it received.
5970
5971}
5972
5973@LibEntry{setmetatable (table, metatable)|
5974
5975Sets the metatable for the given table.
5976(To change the metatable of other types from Lua code,
5977you must use the @link{debuglib|debug library}.)
5978If @id{metatable} is @nil,
5979removes the metatable of the given table.
5980If the original metatable has a @idx{__metatable} field,
5981raises an error.
5982
5983This function returns @id{table}.
5984
5985}
5986
5987@LibEntry{tonumber (e [, base])|
5988
5989When called with no @id{base},
5990@id{tonumber} tries to convert its argument to a number.
5991If the argument is already a number or
5992a string convertible to a number,
5993then @id{tonumber} returns this number;
5994otherwise, it returns @nil.
5995
5996The conversion of strings can result in integers or floats,
5997according to the lexical conventions of Lua @see{lexical}.
5998(The string may have leading and trailing spaces and a sign.)
5999
6000When called with @id{base},
6001then @id{e} must be a string to be interpreted as
6002an integer numeral in that base.
6003The base may be any integer between 2 and 36, inclusive.
6004In bases @N{above 10}, the letter @Char{A} (in either upper or lower case)
6005@N{represents 10}, @Char{B} @N{represents 11}, and so forth,
6006with @Char{Z} representing 35.
6007If the string @id{e} is not a valid numeral in the given base,
6008the function returns @nil.
6009
6010}
6011
6012@LibEntry{tostring (v)|
6013Receives a value of any type and
6014converts it to a string in a human-readable format.
6015(For complete control of how numbers are converted,
6016use @Lid{string.format}.)
6017
6018If the metatable of @id{v} has a @idx{__tostring} field,
6019then @id{tostring} calls the corresponding value
6020with @id{v} as argument,
6021and uses the result of the call as its result.
6022
6023}
6024
6025@LibEntry{type (v)|
6026Returns the type of its only argument, coded as a string.
6027The possible results of this function are
6028@St{nil} (a string, not the value @nil),
6029@St{number},
6030@St{string},
6031@St{boolean},
6032@St{table},
6033@St{function},
6034@St{thread},
6035and @St{userdata}.
6036
6037}
6038
6039@LibEntry{_VERSION|
6040
6041A global variable (not a function) that
6042holds a string containing the running Lua version.
6043The current value of this variable is @St{Lua 5.3}.
6044
6045}
6046
6047@LibEntry{xpcall (f, msgh [, arg1, @Cdots])|
6048
6049This function is similar to @Lid{pcall},
6050except that it sets a new @x{message handler} @id{msgh}.
6051
6052}
6053
6054}
6055
6056@sect2{corolib| @title{Coroutine Manipulation}
6057
6058This library comprises the operations to manipulate coroutines,
6059which come inside the table @defid{coroutine}.
6060See @See{coroutine} for a general description of coroutines.
6061
6062
6063@LibEntry{coroutine.create (f)|
6064
6065Creates a new coroutine, with body @id{f}.
6066@id{f} must be a function.
6067Returns this new coroutine,
6068an object with type @T{"thread"}.
6069
6070}
6071
6072@LibEntry{coroutine.isyieldable ()|
6073
6074Returns true when the running coroutine can yield.
6075
6076A running coroutine is yieldable if it is not the main thread and
6077it is not inside a non-yieldable @N{C function}.
6078
6079}
6080
6081@LibEntry{coroutine.resume (co [, val1, @Cdots])|
6082
6083Starts or continues the execution of coroutine @id{co}.
6084The first time you resume a coroutine,
6085it starts running its body.
6086The values @id{val1}, @ldots are passed
6087as the arguments to the body function.
6088If the coroutine has yielded,
6089@id{resume} restarts it;
6090the values @id{val1}, @ldots are passed
6091as the results from the yield.
6092
6093If the coroutine runs without any errors,
6094@id{resume} returns @true plus any values passed to @id{yield}
6095(when the coroutine yields) or any values returned by the body function
6096(when the coroutine terminates).
6097If there is any error,
6098@id{resume} returns @false plus the error message.
6099
6100}
6101
6102@LibEntry{coroutine.running ()|
6103
6104Returns the running coroutine plus a boolean,
6105true when the running coroutine is the main one.
6106
6107}
6108
6109@LibEntry{coroutine.status (co)|
6110
6111Returns the status of coroutine @id{co}, as a string:
6112@T{"running"},
6113if the coroutine is running (that is, it called @id{status});
6114@T{"suspended"}, if the coroutine is suspended in a call to @id{yield},
6115or if it has not started running yet;
6116@T{"normal"} if the coroutine is active but not running
6117(that is, it has resumed another coroutine);
6118and @T{"dead"} if the coroutine has finished its body function,
6119or if it has stopped with an error.
6120
6121}
6122
6123@LibEntry{coroutine.wrap (f)|
6124
6125Creates a new coroutine, with body @id{f}.
6126@id{f} must be a function.
6127Returns a function that resumes the coroutine each time it is called.
6128Any arguments passed to the function behave as the
6129extra arguments to @id{resume}.
6130Returns the same values returned by @id{resume},
6131except the first boolean.
6132In case of error, propagates the error.
6133
6134}
6135
6136@LibEntry{coroutine.yield (@Cdots)|
6137
6138Suspends the execution of the calling coroutine.
6139Any arguments to @id{yield} are passed as extra results to @id{resume}.
6140
6141}
6142
6143}
6144
6145@sect2{packlib| @title{Modules}
6146
6147The package library provides basic
6148facilities for loading modules in Lua.
6149It exports one function directly in the global environment:
6150@Lid{require}.
6151Everything else is exported in a table @defid{package}.
6152
6153
6154@LibEntry{require (modname)|
6155
6156Loads the given module.
6157The function starts by looking into the @Lid{package.loaded} table
6158to determine whether @id{modname} is already loaded.
6159If it is, then @id{require} returns the value stored
6160at @T{package.loaded[modname]}.
6161Otherwise, it tries to find a @emph{loader} for the module.
6162
6163To find a loader,
6164@id{require} is guided by the @Lid{package.searchers} sequence.
6165By changing this sequence,
6166we can change how @id{require} looks for a module.
6167The following explanation is based on the default configuration
6168for @Lid{package.searchers}.
6169
6170First @id{require} queries @T{package.preload[modname]}.
6171If it has a value,
6172this value (which must be a function) is the loader.
6173Otherwise @id{require} searches for a Lua loader using the
6174path stored in @Lid{package.path}.
6175If that also fails, it searches for a @N{C loader} using the
6176path stored in @Lid{package.cpath}.
6177If that also fails,
6178it tries an @emph{all-in-one} loader @seeF{package.searchers}.
6179
6180Once a loader is found,
6181@id{require} calls the loader with two arguments:
6182@id{modname} and an extra value dependent on how it got the loader.
6183(If the loader came from a file,
6184this extra value is the file name.)
6185If the loader returns any non-nil value,
6186@id{require} assigns the returned value to @T{package.loaded[modname]}.
6187If the loader does not return a non-nil value and
6188has not assigned any value to @T{package.loaded[modname]},
6189then @id{require} assigns @Rw{true} to this entry.
6190In any case, @id{require} returns the
6191final value of @T{package.loaded[modname]}.
6192
6193If there is any error loading or running the module,
6194or if it cannot find any loader for the module,
6195then @id{require} raises an error.
6196
6197}
6198
6199@LibEntry{package.config|
6200
6201A string describing some compile-time configurations for packages.
6202This string is a sequence of lines:
6203@itemize{
6204
6205@item{The first line is the @x{directory separator} string.
6206Default is @Char{\} for @x{Windows} and @Char{/} for all other systems.}
6207
6208@item{The second line is the character that separates templates in a path.
6209Default is @Char{;}.}
6210
6211@item{The third line is the string that marks the
6212substitution points in a template.
6213Default is @Char{?}.}
6214
6215@item{The fourth line is a string that, in a path in @x{Windows},
6216is replaced by the executable's directory.
6217Default is @Char{!}.}
6218
6219@item{The fifth line is a mark to ignore all text after it
6220when building the @id{luaopen_} function name.
6221Default is @Char{-}.}
6222
6223}
6224
6225}
6226
6227@LibEntry{package.cpath|
6228
6229The path used by @Lid{require} to search for a @N{C loader}.
6230
6231Lua initializes the @N{C path} @Lid{package.cpath} in the same way
6232it initializes the Lua path @Lid{package.path},
6233using the environment variable @defid{LUA_CPATH_5_3},
6234or the environment variable @defid{LUA_CPATH},
6235or a default path defined in @id{luaconf.h}.
6236
6237}
6238
6239@LibEntry{package.loaded|
6240
6241A table used by @Lid{require} to control which
6242modules are already loaded.
6243When you require a module @id{modname} and
6244@T{package.loaded[modname]} is not false,
6245@Lid{require} simply returns the value stored there.
6246
6247This variable is only a reference to the real table;
6248assignments to this variable do not change the
6249table used by @Lid{require}.
6250
6251}
6252
6253@LibEntry{package.loadlib (libname, funcname)|
6254
6255Dynamically links the host program with the @N{C library} @id{libname}.
6256
6257If @id{funcname} is @St{*},
6258then it only links with the library,
6259making the symbols exported by the library
6260available to other dynamically linked libraries.
6261Otherwise,
6262it looks for a function @id{funcname} inside the library
6263and returns this function as a @N{C function}.
6264So, @id{funcname} must follow the @Lid{lua_CFunction} prototype
6265@seeC{lua_CFunction}.
6266
6267This is a low-level function.
6268It completely bypasses the package and module system.
6269Unlike @Lid{require},
6270it does not perform any path searching and
6271does not automatically adds extensions.
6272@id{libname} must be the complete file name of the @N{C library},
6273including if necessary a path and an extension.
6274@id{funcname} must be the exact name exported by the @N{C library}
6275(which may depend on the @N{C compiler} and linker used).
6276
6277This function is not supported by @N{Standard C}.
6278As such, it is only available on some platforms
6279(Windows, Linux, Mac OS X, Solaris, BSD,
6280plus other Unix systems that support the @id{dlfcn} standard).
6281
6282}
6283
6284@LibEntry{package.path|
6285
6286The path used by @Lid{require} to search for a Lua loader.
6287
6288At start-up, Lua initializes this variable with
6289the value of the environment variable @defid{LUA_PATH_5_3} or
6290the environment variable @defid{LUA_PATH} or
6291with a default path defined in @id{luaconf.h},
6292if those environment variables are not defined.
6293Any @St{;;} in the value of the environment variable
6294is replaced by the default path.
6295
6296}
6297
6298@LibEntry{package.preload|
6299
6300A table to store loaders for specific modules
6301@seeF{require}.
6302
6303This variable is only a reference to the real table;
6304assignments to this variable do not change the
6305table used by @Lid{require}.
6306
6307}
6308
6309@LibEntry{package.searchers|
6310
6311A table used by @Lid{require} to control how to load modules.
6312
6313Each entry in this table is a @def{searcher function}.
6314When looking for a module,
6315@Lid{require} calls each of these searchers in ascending order,
6316with the module name (the argument given to @Lid{require}) as its
6317sole parameter.
6318The function can return another function (the module @def{loader})
6319plus an extra value that will be passed to that loader,
6320or a string explaining why it did not find that module
6321(or @nil if it has nothing to say).
6322
6323Lua initializes this table with four searcher functions.
6324
6325The first searcher simply looks for a loader in the
6326@Lid{package.preload} table.
6327
6328The second searcher looks for a loader as a Lua library,
6329using the path stored at @Lid{package.path}.
6330The search is done as described in function @Lid{package.searchpath}.
6331
6332The third searcher looks for a loader as a @N{C library},
6333using the path given by the variable @Lid{package.cpath}.
6334Again,
6335the search is done as described in function @Lid{package.searchpath}.
6336For instance,
6337if the @N{C path} is the string
6338@verbatim{
6339"./?.so;./?.dll;/usr/local/?/init.so"
6340}
6341the searcher for module @id{foo}
6342will try to open the files @T{./foo.so}, @T{./foo.dll},
6343and @T{/usr/local/foo/init.so}, in that order.
6344Once it finds a @N{C library},
6345this searcher first uses a dynamic link facility to link the
6346application with the library.
6347Then it tries to find a @N{C function} inside the library to
6348be used as the loader.
6349The name of this @N{C function} is the string @St{luaopen_}
6350concatenated with a copy of the module name where each dot
6351is replaced by an underscore.
6352Moreover, if the module name has a hyphen,
6353its suffix after (and including) the first hyphen is removed.
6354For instance, if the module name is @id{a.b.c-v2.1},
6355the function name will be @id{luaopen_a_b_c}.
6356
6357The fourth searcher tries an @def{all-in-one loader}.
6358It searches the @N{C path} for a library for
6359the root name of the given module.
6360For instance, when requiring @id{a.b.c},
6361it will search for a @N{C library} for @id{a}.
6362If found, it looks into it for an open function for
6363the submodule;
6364in our example, that would be @id{luaopen_a_b_c}.
6365With this facility, a package can pack several @N{C submodules}
6366into one single library,
6367with each submodule keeping its original open function.
6368
6369All searchers except the first one (preload) return as the extra value
6370the file name where the module was found,
6371as returned by @Lid{package.searchpath}.
6372The first searcher returns no extra value.
6373
6374}
6375
6376@LibEntry{package.searchpath (name, path [, sep [, rep]])|
6377
6378Searches for the given @id{name} in the given @id{path}.
6379
6380A path is a string containing a sequence of
6381@emph{templates} separated by semicolons.
6382For each template,
6383the function replaces each interrogation mark (if any)
6384in the template with a copy of @id{name}
6385wherein all occurrences of @id{sep}
6386(a dot, by default)
6387were replaced by @id{rep}
6388(the system's directory separator, by default),
6389and then tries to open the resulting file name.
6390
6391For instance, if the path is the string
6392@verbatim{
6393"./?.lua;./?.lc;/usr/local/?/init.lua"
6394}
6395the search for the name @id{foo.a}
6396will try to open the files
6397@T{./foo/a.lua}, @T{./foo/a.lc}, and
6398@T{/usr/local/foo/a/init.lua}, in that order.
6399
6400Returns the resulting name of the first file that it can
6401open in read mode (after closing the file),
6402or @nil plus an error message if none succeeds.
6403(This error message lists all file names it tried to open.)
6404
6405}
6406
6407}
6408
6409@sect2{strlib| @title{String Manipulation}
6410
6411This library provides generic functions for string manipulation,
6412such as finding and extracting substrings, and pattern matching.
6413When indexing a string in Lua, the first character is at @N{position 1}
6414(not @N{at 0}, as in C).
6415Indices are allowed to be negative and are interpreted as indexing backwards,
6416from the end of the string.
6417Thus, the last character is at position @num{-1}, and so on.
6418
6419The string library provides all its functions inside the table
6420@defid{string}.
6421It also sets a @x{metatable for strings}
6422where the @idx{__index} field points to the @id{string} table.
6423Therefore, you can use the string functions in object-oriented style.
6424For instance, @T{string.byte(s,i)}
6425can be written as @T{s:byte(i)}.
6426
6427The string library assumes one-byte character encodings.
6428
6429
6430@LibEntry{string.byte (s [, i [, j]])|
6431Returns the internal numeric codes of the characters @T{s[i]},
6432@T{s[i+1]}, @ldots, @T{s[j]}.
6433The default value for @id{i} @N{is 1};
6434the default value for @id{j} @N{is @id{i}}.
6435These indices are corrected
6436following the same rules of function @Lid{string.sub}.
6437
6438Numeric codes are not necessarily portable across platforms.
6439
6440}
6441
6442@LibEntry{string.char (@Cdots)|
6443Receives zero or more integers.
6444Returns a string with length equal to the number of arguments,
6445in which each character has the internal numeric code equal
6446to its corresponding argument.
6447
6448Numeric codes are not necessarily portable across platforms.
6449
6450}
6451
6452@LibEntry{string.dump (function [, strip])|
6453
6454Returns a string containing a binary representation
6455(a @emph{binary chunk})
6456of the given function,
6457so that a later @Lid{load} on this string returns
6458a copy of the function (but with new upvalues).
6459If @id{strip} is a true value,
6460the binary representation may not include all debug information
6461about the function,
6462to save space.
6463
6464Functions with upvalues have only their number of upvalues saved.
6465When (re)loaded,
6466those upvalues receive fresh instances containing @nil.
6467(You can use the debug library to serialize
6468and reload the upvalues of a function
6469in a way adequate to your needs.)
6470
6471}
6472
6473@LibEntry{string.find (s, pattern [, init [, plain]])|
6474
6475Looks for the first match of
6476@id{pattern} @see{pm} in the string @id{s}.
6477If it finds a match, then @id{find} returns the indices @N{of @T{s}}
6478where this occurrence starts and ends;
6479otherwise, it returns @nil.
6480A third, optional numeric argument @id{init} specifies
6481where to start the search;
6482its default value @N{is 1} and can be negative.
6483A value of @true as a fourth, optional argument @id{plain}
6484turns off the pattern matching facilities,
6485so the function does a plain @Q{find substring} operation,
6486with no characters in @id{pattern} being considered magic.
6487Note that if @id{plain} is given, then @id{init} must be given as well.
6488
6489If the pattern has captures,
6490then in a successful match
6491the captured values are also returned,
6492after the two indices.
6493
6494}
6495
6496@LibEntry{string.format (formatstring, @Cdots)|
6497
6498Returns a formatted version of its variable number of arguments
6499following the description given in its first argument (which must be a string).
6500The format string follows the same rules as the @ANSI{sprintf}.
6501The only differences are that the options/modifiers
6502@T{*}, @id{h}, @id{L}, @id{l}, @id{n},
6503and @id{p} are not supported
6504and that there is an extra option, @id{q}.
6505
6506The @id{q} option formats a string between double quotes,
6507using escape sequences when necessary to ensure that
6508it can safely be read back by the Lua interpreter.
6509For instance, the call
6510@verbatim{
6511string.format('%q', 'a string with "quotes" and \n new line')
6512}
6513may produce the string:
6514@verbatim{
6515"a string with \"quotes\" and \
6516 new line"
6517}
6518
6519Options
6520@id{A}, @id{a}, @id{E}, @id{e}, @id{f},
6521@id{G}, and @id{g} all expect a number as argument.
6522Options @id{c}, @id{d},
6523@id{i}, @id{o}, @id{u}, @id{X}, and @id{x}
6524expect an integer.
6525When Lua is compiled with a C89 compiler,
6526options @id{A} and @id{a} (hexadecimal floats)
6527do not support any modifier (flags, width, length).
6528
6529Option @id{s} expects a string;
6530if its argument is not a string,
6531it is converted to one following the same rules of @Lid{tostring}.
6532If the option has any modifier (flags, width, length),
6533the string argument should not contain @x{embedded zeros}.
6534
6535}
6536
6537@LibEntry{string.gmatch (s, pattern)|
6538Returns an iterator function that,
6539each time it is called,
6540returns the next captures from @id{pattern} @see{pm}
6541over the string @id{s}.
6542If @id{pattern} specifies no captures,
6543then the whole match is produced in each call.
6544
6545As an example, the following loop
6546will iterate over all the words from string @id{s},
6547printing one per line:
6548@verbatim{
6549s = "hello world from Lua"
6550for w in string.gmatch(s, "%a+") do
6551 print(w)
6552end
6553}
6554The next example collects all pairs @T{key=value} from the
6555given string into a table:
6556@verbatim{
6557t = {}
6558s = "from=world, to=Lua"
6559for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6560 t[k] = v
6561end
6562}
6563
6564For this function, a caret @Char{^} at the start of a pattern does not
6565work as an anchor, as this would prevent the iteration.
6566
6567}
6568
6569@LibEntry{string.gsub (s, pattern, repl [, n])|
6570Returns a copy of @id{s}
6571in which all (or the first @id{n}, if given)
6572occurrences of the @id{pattern} @see{pm} have been
6573replaced by a replacement string specified by @id{repl},
6574which can be a string, a table, or a function.
6575@id{gsub} also returns, as its second value,
6576the total number of matches that occurred.
6577The name @id{gsub} comes from @emph{Global SUBstitution}.
6578
6579If @id{repl} is a string, then its value is used for replacement.
6580The @N{character @T{%}} works as an escape character:
6581any sequence in @id{repl} of the form @T{%@rep{d}},
6582with @rep{d} between 1 and 9,
6583stands for the value of the @rep{d}-th captured substring.
6584The sequence @T{%0} stands for the whole match.
6585The sequence @T{%%} stands for a @N{single @T{%}}.
6586
6587If @id{repl} is a table, then the table is queried for every match,
6588using the first capture as the key.
6589
6590If @id{repl} is a function, then this function is called every time a
6591match occurs, with all captured substrings passed as arguments,
6592in order.
6593
6594In any case,
6595if the pattern specifies no captures,
6596then it behaves as if the whole pattern was inside a capture.
6597
6598If the value returned by the table query or by the function call
6599is a string or a number,
6600then it is used as the replacement string;
6601otherwise, if it is @Rw{false} or @nil,
6602then there is no replacement
6603(that is, the original match is kept in the string).
6604
6605Here are some examples:
6606@verbatim{
6607x = string.gsub("hello world", "(%w+)", "%1 %1")
6608--> x="hello hello world world"
6609
6610x = string.gsub("hello world", "%w+", "%0 %0", 1)
6611--> x="hello hello world"
6612
6613x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6614--> x="world hello Lua from"
6615
6616x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6617--> x="home = /home/roberto, user = roberto"
6618
6619x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6620 return load(s)()
6621 end)
6622--> x="4+5 = 9"
6623
6624local t = {name="lua", version="5.3"}
6625x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
6626--> x="lua-5.3.tar.gz"
6627}
6628
6629}
6630
6631@LibEntry{string.len (s)|
6632Receives a string and returns its length.
6633The empty string @T{""} has length 0.
6634Embedded zeros are counted,
6635so @T{"a\000bc\000"} has length 5.
6636
6637}
6638
6639@LibEntry{string.lower (s)|
6640Receives a string and returns a copy of this string with all
6641uppercase letters changed to lowercase.
6642All other characters are left unchanged.
6643The definition of what an uppercase letter is depends on the current locale.
6644
6645}
6646
6647@LibEntry{string.match (s, pattern [, init])|
6648Looks for the first @emph{match} of
6649@id{pattern} @see{pm} in the string @id{s}.
6650If it finds one, then @id{match} returns
6651the captures from the pattern;
6652otherwise it returns @nil.
6653If @id{pattern} specifies no captures,
6654then the whole match is returned.
6655A third, optional numeric argument @id{init} specifies
6656where to start the search;
6657its default value @N{is 1} and can be negative.
6658
6659}
6660
6661@LibEntry{string.pack (fmt, v1, v2, @Cdots)|
6662
6663Returns a binary string containing the values @id{v1}, @id{v2}, etc.
6664packed (that is, serialized in binary form)
6665according to the format string @id{fmt} @see{pack}.
6666
6667}
6668
6669@LibEntry{string.packsize (fmt)|
6670
6671Returns the size of a string resulting from @Lid{string.pack}
6672with the given format.
6673The format string cannot have the variable-length options
6674@Char{s} or @Char{z} @see{pack}.
6675
6676}
6677
6678@LibEntry{string.rep (s, n [, sep])|
6679Returns a string that is the concatenation of @id{n} copies of
6680the string @id{s} separated by the string @id{sep}.
6681The default value for @id{sep} is the empty string
6682(that is, no separator).
6683Returns the empty string if @id{n} is not positive.
6684
6685(Note that it is very easy to exhaust the memory of your machine
6686with a single call to this function.)
6687
6688}
6689
6690@LibEntry{string.reverse (s)|
6691Returns a string that is the string @id{s} reversed.
6692
6693}
6694
6695@LibEntry{string.sub (s, i [, j])|
6696Returns the substring of @id{s} that
6697starts at @id{i} and continues until @id{j};
6698@id{i} and @id{j} can be negative.
6699If @id{j} is absent, then it is assumed to be equal to @num{-1}
6700(which is the same as the string length).
6701In particular,
6702the call @T{string.sub(s,1,j)} returns a prefix of @id{s}
6703with length @id{j},
6704and @T{string.sub(s, -i)} (for a positive @id{i})
6705returns a suffix of @id{s}
6706with length @id{i}.
6707
6708If, after the translation of negative indices,
6709@id{i} is less than 1,
6710it is corrected to 1.
6711If @id{j} is greater than the string length,
6712it is corrected to that length.
6713If, after these corrections,
6714@id{i} is greater than @id{j},
6715the function returns the empty string.
6716
6717}
6718
6719@LibEntry{string.unpack (fmt, s [, pos])|
6720
6721Returns the values packed in string @id{s} @seeF{string.pack}
6722according to the format string @id{fmt} @see{pack}.
6723An optional @id{pos} marks where
6724to start reading in @id{s} (default is 1).
6725After the read values,
6726this function also returns the index of the first unread byte in @id{s}.
6727
6728}
6729
6730@LibEntry{string.upper (s)|
6731Receives a string and returns a copy of this string with all
6732lowercase letters changed to uppercase.
6733All other characters are left unchanged.
6734The definition of what a lowercase letter is depends on the current locale.
6735
6736}
6737
6738
6739@sect3{pm| @title{Patterns}
6740
6741Patterns in Lua are described by regular strings,
6742which are interpreted as patterns by the pattern-matching functions
6743@Lid{string.find},
6744@Lid{string.gmatch},
6745@Lid{string.gsub},
6746and @Lid{string.match}.
6747This section describes the syntax and the meaning
6748(that is, what they match) of these strings.
6749
6750@sect4{@title{Character Class:}
6751A @def{character class} is used to represent a set of characters.
6752The following combinations are allowed in describing a character class:
6753@description{
6754
6755@item{@rep{x}|
6756(where @rep{x} is not one of the @emphx{magic characters}
6757@T{^$()%.[]*+-?})
6758represents the character @emph{x} itself.
6759}
6760
6761@item{@T{.}| (a dot) represents all characters.}
6762
6763@item{@T{%a}| represents all letters.}
6764
6765@item{@T{%c}| represents all control characters.}
6766
6767@item{@T{%d}| represents all digits.}
6768
6769@item{@T{%g}| represents all printable characters except space.}
6770
6771@item{@T{%l}| represents all lowercase letters.}
6772
6773@item{@T{%p}| represents all punctuation characters.}
6774
6775@item{@T{%s}| represents all space characters.}
6776
6777@item{@T{%u}| represents all uppercase letters.}
6778
6779@item{@T{%w}| represents all alphanumeric characters.}
6780
6781@item{@T{%x}| represents all hexadecimal digits.}
6782
6783@item{@T{%@rep{x}}| (where @rep{x} is any non-alphanumeric character)
6784represents the character @rep{x}.
6785This is the standard way to escape the magic characters.
6786Any non-alphanumeric character
6787(including all punctuation characters, even the non-magical)
6788can be preceded by a @Char{%}
6789when used to represent itself in a pattern.
6790}
6791
6792@item{@T{[@rep{set}]}|
6793represents the class which is the union of all
6794characters in @rep{set}.
6795A range of characters can be specified by
6796separating the end characters of the range,
6797in ascending order, with a @Char{-}.
6798All classes @T{%}@emph{x} described above can also be used as
6799components in @rep{set}.
6800All other characters in @rep{set} represent themselves.
6801For example, @T{[%w_]} (or @T{[_%w]})
6802represents all alphanumeric characters plus the underscore,
6803@T{[0-7]} represents the octal digits,
6804and @T{[0-7%l%-]} represents the octal digits plus
6805the lowercase letters plus the @Char{-} character.
6806
6807You can put a closing square bracket in a set
6808by positioning it as the first character in the set.
6809You can put a hyphen in a set
6810by positioning it as the first or the last character in the set.
6811(You can also use an escape for both cases.)
6812
6813The interaction between ranges and classes is not defined.
6814Therefore, patterns like @T{[%a-z]} or @T{[a-%%]}
6815have no meaning.
6816}
6817
6818@item{@T{[^@rep{set}]}|
6819represents the complement of @rep{set},
6820where @rep{set} is interpreted as above.
6821}
6822
6823}
6824For all classes represented by single letters (@T{%a}, @T{%c}, etc.),
6825the corresponding uppercase letter represents the complement of the class.
6826For instance, @T{%S} represents all non-space characters.
6827
6828The definitions of letter, space, and other character groups
6829depend on the current locale.
6830In particular, the class @T{[a-z]} may not be equivalent to @T{%l}.
6831
6832}
6833
6834@sect4{@title{Pattern Item:}
6835A @def{pattern item} can be
6836@itemize{
6837
6838@item{
6839a single character class,
6840which matches any single character in the class;
6841}
6842
6843@item{
6844a single character class followed by @Char{*},
6845which matches zero or more repetitions of characters in the class.
6846These repetition items will always match the longest possible sequence;
6847}
6848
6849@item{
6850a single character class followed by @Char{+},
6851which matches one or more repetitions of characters in the class.
6852These repetition items will always match the longest possible sequence;
6853}
6854
6855@item{
6856a single character class followed by @Char{-},
6857which also matches zero or more repetitions of characters in the class.
6858Unlike @Char{*},
6859these repetition items will always match the shortest possible sequence;
6860}
6861
6862@item{
6863a single character class followed by @Char{?},
6864which matches zero or one occurrence of a character in the class.
6865It always matches one occurrence if possible;
6866}
6867
6868@item{
6869@T{%@rep{n}}, for @rep{n} between 1 and 9;
6870such item matches a substring equal to the @rep{n}-th captured string
6871(see below);
6872}
6873
6874@item{
6875@T{%b@rep{xy}}, where @rep{x} and @rep{y} are two distinct characters;
6876such item matches strings that start @N{with @rep{x}}, end @N{with @rep{y}},
6877and where the @rep{x} and @rep{y} are @emph{balanced}.
6878This means that, if one reads the string from left to right,
6879counting @M{+1} for an @rep{x} and @M{-1} for a @rep{y},
6880the ending @rep{y} is the first @rep{y} where the count reaches 0.
6881For instance, the item @T{%b()} matches expressions with
6882balanced parentheses.
6883}
6884
6885@item{
6886@T{%f[@rep{set}]}, a @def{frontier pattern};
6887such item matches an empty string at any position such that
6888the next character belongs to @rep{set}
6889and the previous character does not belong to @rep{set}.
6890The set @rep{set} is interpreted as previously described.
6891The beginning and the end of the subject are handled as if
6892they were the character @Char{\0}.
6893}
6894
6895}
6896
6897}
6898
6899@sect4{@title{Pattern:}
6900A @def{pattern} is a sequence of pattern items.
6901A caret @Char{^} at the beginning of a pattern anchors the match at the
6902beginning of the subject string.
6903A @Char{$} at the end of a pattern anchors the match at the
6904end of the subject string.
6905At other positions,
6906@Char{^} and @Char{$} have no special meaning and represent themselves.
6907
6908}
6909
6910@sect4{@title{Captures:}
6911A pattern can contain sub-patterns enclosed in parentheses;
6912they describe @def{captures}.
6913When a match succeeds, the substrings of the subject string
6914that match captures are stored (@emph{captured}) for future use.
6915Captures are numbered according to their left parentheses.
6916For instance, in the pattern @T{"(a*(.)%w(%s*))"},
6917the part of the string matching @T{"a*(.)%w(%s*)"} is
6918stored as the first capture (and therefore has @N{number 1});
6919the character matching @St{.} is captured with @N{number 2},
6920and the part matching @St{%s*} has @N{number 3}.
6921
6922As a special case, the empty capture @T{()} captures
6923the current string position (a number).
6924For instance, if we apply the pattern @T{"()aa()"} on the
6925string @T{"flaaap"}, there will be two captures: @N{3 and 5}.
6926
6927}
6928
6929}
6930
6931
6932@sect3{pack| @title{Format Strings for Pack and Unpack}
6933
6934The first argument to @Lid{string.pack},
6935@Lid{string.packsize}, and @Lid{string.unpack}
6936is a format string,
6937which describes the layout of the structure being created or read.
6938
6939A format string is a sequence of conversion options.
6940The conversion options are as follows:
6941@description{
6942@item{@T{<}|sets little endian}
6943@item{@T{>}|sets big endian}
6944@item{@T{=}|sets native endian}
6945@item{@T{![@rep{n}]}|sets maximum alignment to @id{n}
6946(default is native alignment)}
6947@item{@T{b}|a signed byte (@id{char})}
6948@item{@T{B}|an unsigned byte (@id{char})}
6949@item{@T{h}|a signed @id{short} (native size)}
6950@item{@T{H}|an unsigned @id{short} (native size)}
6951@item{@T{l}|a signed @id{long} (native size)}
6952@item{@T{L}|an unsigned @id{long} (native size)}
6953@item{@T{j}|a @id{lua_Integer}}
6954@item{@T{J}|a @id{lua_Unsigned}}
6955@item{@T{T}|a @id{size_t} (native size)}
6956@item{@T{i[@rep{n}]}|a signed @id{int} with @id{n} bytes
6957(default is native size)}
6958@item{@T{I[@rep{n}]}|an unsigned @id{int} with @id{n} bytes
6959(default is native size)}
6960@item{@T{f}|a @id{float} (native size)}
6961@item{@T{d}|a @id{double} (native size)}
6962@item{@T{n}|a @id{lua_Number}}
6963@item{@T{c@rep{n}}|a fixed-sized string with @id{n} bytes}
6964@item{@T{z}|a zero-terminated string}
6965@item{@T{s[@emph{n}]}|a string preceded by its length
6966coded as an unsigned integer with @id{n} bytes
6967(default is a @id{size_t})}
6968@item{@T{x}|one byte of padding}
6969@item{@T{X@rep{op}}|an empty item that aligns
6970according to option @id{op}
6971(which is otherwise ignored)}
6972@item{@Char{ }|(empty space) ignored}
6973}
6974(A @St{[@rep{n}]} means an optional integral numeral.)
6975Except for padding, spaces, and configurations
6976(options @St{xX <=>!}),
6977each option corresponds to an argument (in @Lid{string.pack})
6978or a result (in @Lid{string.unpack}).
6979
6980For options @St{!@rep{n}}, @St{s@rep{n}}, @St{i@rep{n}}, and @St{I@rep{n}},
6981@id{n} can be any integer between 1 and 16.
6982All integral options check overflows;
6983@Lid{string.pack} checks whether the given value fits in the given size;
6984@Lid{string.unpack} checks whether the read value fits in a Lua integer.
6985
6986Any format string starts as if prefixed by @St{!1=},
6987that is,
6988with maximum alignment of 1 (no alignment)
6989and native endianness.
6990
6991Alignment works as follows:
6992For each option,
6993the format gets extra padding until the data starts
6994at an offset that is a multiple of the minimum between the
6995option size and the maximum alignment;
6996this minimum must be a power of 2.
6997Options @St{c} and @St{z} are not aligned;
6998option @St{s} follows the alignment of its starting integer.
6999
7000All padding is filled with zeros by @Lid{string.pack}
7001(and ignored by @Lid{string.unpack}).
7002
7003}
7004
7005}
7006
7007@sect2{utf8| @title{UTF-8 Support}
7008
7009This library provides basic support for @x{UTF-8} encoding.
7010It provides all its functions inside the table @defid{utf8}.
7011This library does not provide any support for @x{Unicode} other
7012than the handling of the encoding.
7013Any operation that needs the meaning of a character,
7014such as character classification, is outside its scope.
7015
7016Unless stated otherwise,
7017all functions that expect a byte position as a parameter
7018assume that the given position is either the start of a byte sequence
7019or one plus the length of the subject string.
7020As in the string library,
7021negative indices count from the end of the string.
7022
7023
7024@LibEntry{utf8.char (@Cdots)|
7025Receives zero or more integers,
7026converts each one to its corresponding UTF-8 byte sequence
7027and returns a string with the concatenation of all these sequences.
7028
7029}
7030
7031@LibEntry{utf8.charpattern|
7032The pattern (a string, not a function) @St{[\0-\x7F\xC2-\xF4][\x80-\xBF]*}
7033@see{pm},
7034which matches exactly one UTF-8 byte sequence,
7035assuming that the subject is a valid UTF-8 string.
7036
7037}
7038
7039@LibEntry{utf8.codes (s)|
7040
7041Returns values so that the construction
7042@verbatim{
7043for p, c in utf8.codes(s) do @rep{body} end
7044}
7045will iterate over all characters in string @id{s},
7046with @id{p} being the position (in bytes) and @id{c} the code point
7047of each character.
7048It raises an error if it meets any invalid byte sequence.
7049
7050}
7051
7052@LibEntry{utf8.codepoint (s [, i [, j]])|
7053Returns the codepoints (as integers) from all characters in @id{s}
7054that start between byte position @id{i} and @id{j} (both included).
7055The default for @id{i} is 1 and for @id{j} is @id{i}.
7056It raises an error if it meets any invalid byte sequence.
7057
7058}
7059
7060@LibEntry{utf8.len (s [, i [, j]])|
7061Returns the number of UTF-8 characters in string @id{s}
7062that start between positions @id{i} and @id{j} (both inclusive).
7063The default for @id{i} is @num{1} and for @id{j} is @num{-1}.
7064If it finds any invalid byte sequence,
7065returns a false value plus the position of the first invalid byte.
7066
7067}
7068
7069@LibEntry{utf8.offset (s, n [, i])|
7070Returns the position (in bytes) where the encoding of the
7071@id{n}-th character of @id{s}
7072(counting from position @id{i}) starts.
7073A negative @id{n} gets characters before position @id{i}.
7074The default for @id{i} is 1 when @id{n} is non-negative
7075and @T{#s + 1} otherwise,
7076so that @T{utf8.offset(s, -n)} gets the offset of the
7077@id{n}-th character from the end of the string.
7078If the specified character is neither in the subject
7079nor right after its end,
7080the function returns @nil.
7081
7082As a special case,
7083when @id{n} is 0 the function returns the start of the encoding
7084of the character that contains the @id{i}-th byte of @id{s}.
7085
7086This function assumes that @id{s} is a valid UTF-8 string.
7087
7088}
7089
7090}
7091
7092@sect2{tablib| @title{Table Manipulation}
7093
7094This library provides generic functions for table manipulation.
7095It provides all its functions inside the table @defid{table}.
7096
7097Remember that, whenever an operation needs the length of a table,
7098all caveats about the length operator apply @see{len-op}.
7099All functions ignore non-numeric keys
7100in the tables given as arguments.
7101
7102
7103@LibEntry{table.concat (list [, sep [, i [, j]]])|
7104
7105Given a list where all elements are strings or numbers,
7106returns the string @T{list[i]..sep..list[i+1] @Cdots sep..list[j]}.
7107The default value for @id{sep} is the empty string,
7108the default for @id{i} is 1,
7109and the default for @id{j} is @T{#list}.
7110If @id{i} is greater than @id{j}, returns the empty string.
7111
7112}
7113
7114@LibEntry{table.insert (list, [pos,] value)|
7115
7116Inserts element @id{value} at position @id{pos} in @id{list},
7117shifting up the elements
7118@T{list[pos], list[pos+1], @Cdots, list[#list]}.
7119The default value for @id{pos} is @T{#list+1},
7120so that a call @T{table.insert(t,x)} inserts @id{x} at the end
7121of list @id{t}.
7122
7123}
7124
7125@LibEntry{table.move (a1, f, e, t [,a2])|
7126
7127Moves elements from table @id{a1} to table @id{a2},
7128performing the equivalent to the following
7129multiple assignment:
7130@T{a2[t],@Cdots = a1[f],@Cdots,a1[e]}.
7131The default for @id{a2} is @id{a1}.
7132The destination range can overlap with the source range.
7133The number of elements to be moved must fit in a Lua integer.
7134
7135Returns the destination table @id{a2}.
7136
7137}
7138
7139@LibEntry{table.pack (@Cdots)|
7140
7141Returns a new table with all arguments stored into keys 1, 2, etc.
7142and with a field @St{n} with the total number of arguments.
7143Note that the resulting table may not be a sequence.
7144
7145}
7146
7147@LibEntry{table.remove (list [, pos])|
7148
7149Removes from @id{list} the element at position @id{pos},
7150returning the value of the removed element.
7151When @id{pos} is an integer between 1 and @T{#list},
7152it shifts down the elements
7153@T{list[pos+1], list[pos+2], @Cdots, list[#list]}
7154and erases element @T{list[#list]};
7155The index @id{pos} can also be 0 when @T{#list} is 0,
7156or @T{#list + 1};
7157in those cases, the function erases the element @T{list[pos]}.
7158
7159The default value for @id{pos} is @T{#list},
7160so that a call @T{table.remove(l)} removes the last element
7161of list @id{l}.
7162
7163}
7164
7165@LibEntry{table.sort (list [, comp])|
7166
7167Sorts list elements in a given order, @emph{in-place},
7168from @T{list[1]} to @T{list[#list]}.
7169If @id{comp} is given,
7170then it must be a function that receives two list elements
7171and returns true when the first element must come
7172before the second in the final order
7173(so that, after the sort,
7174@T{i < j} implies @T{not comp(list[j],list[i])}).
7175If @id{comp} is not given,
7176then the standard Lua operator @T{<} is used instead.
7177
7178Note that the @id{comp} function must define
7179a strict partial order over the elements in the list;
7180that is, it must be asymmetric and transitive.
7181Otherwise, no valid sort may be possible.
7182
7183The sort algorithm is not stable:
7184elements considered equal by the given order
7185may have their relative positions changed by the sort.
7186
7187}
7188
7189@LibEntry{table.unpack (list [, i [, j]])|
7190
7191Returns the elements from the given list.
7192This function is equivalent to
7193@verbatim{
7194return list[i], list[i+1], @Cdots, list[j]
7195}
7196By default, @id{i} @N{is 1} and @id{j} is @T{#list}.
7197
7198}
7199
7200}
7201
7202@sect2{mathlib| @title{Mathematical Functions}
7203
7204This library provides basic mathematical functions.
7205It provides all its functions and constants inside the table @defid{math}.
7206Functions with the annotation @St{integer/float} give
7207integer results for integer arguments
7208and float results for float (or mixed) arguments.
7209Rounding functions
7210(@Lid{math.ceil}, @Lid{math.floor}, and @Lid{math.modf})
7211return an integer when the result fits in the range of an integer,
7212or a float otherwise.
7213
7214@LibEntry{math.abs (x)|
7215
7216Returns the absolute value of @id{x}. (integer/float)
7217
7218}
7219
7220@LibEntry{math.acos (x)|
7221
7222Returns the arc cosine of @id{x} (in radians).
7223
7224}
7225
7226@LibEntry{math.asin (x)|
7227
7228Returns the arc sine of @id{x} (in radians).
7229
7230}
7231
7232@LibEntry{math.atan (y [, x])|
7233
7234@index{atan2}
7235Returns the arc tangent of @T{y/x} (in radians),
7236but uses the signs of both arguments to find the
7237quadrant of the result.
7238(It also handles correctly the case of @id{x} being zero.)
7239
7240The default value for @id{x} is 1,
7241so that the call @T{math.atan(y)}
7242returns the arc tangent of @id{y}.
7243
7244}
7245
7246@LibEntry{math.ceil (x)|
7247
7248Returns the smallest integral value larger than or equal to @id{x}.
7249
7250}
7251
7252@LibEntry{math.cos (x)|
7253
7254Returns the cosine of @id{x} (assumed to be in radians).
7255
7256}
7257
7258@LibEntry{math.deg (x)|
7259
7260Converts the angle @id{x} from radians to degrees.
7261
7262}
7263
7264@LibEntry{math.exp (x)|
7265
7266Returns the value @M{e@sp{x}}
7267(where @id{e} is the base of natural logarithms).
7268
7269}
7270
7271@LibEntry{math.floor (x)|
7272
7273Returns the largest integral value smaller than or equal to @id{x}.
7274
7275}
7276
7277@LibEntry{math.fmod (x, y)|
7278
7279Returns the remainder of the division of @id{x} by @id{y}
7280that rounds the quotient towards zero. (integer/float)
7281
7282}
7283
7284@LibEntry{math.huge|
7285
7286The float value @idx{HUGE_VAL},
7287a value larger than any other numeric value.
7288
7289}
7290
7291@LibEntry{math.log (x [, base])|
7292
7293Returns the logarithm of @id{x} in the given base.
7294The default for @id{base} is @M{e}
7295(so that the function returns the natural logarithm of @id{x}).
7296
7297}
7298
7299@LibEntry{math.max (x, @Cdots)|
7300
7301Returns the argument with the maximum value,
7302according to the Lua operator @T{<}. (integer/float)
7303
7304}
7305
7306@LibEntry{math.maxinteger|
7307An integer with the maximum value for an integer.
7308
7309}
7310
7311@LibEntry{math.min (x, @Cdots)|
7312
7313Returns the argument with the minimum value,
7314according to the Lua operator @T{<}. (integer/float)
7315
7316}
7317
7318@LibEntry{math.mininteger|
7319An integer with the minimum value for an integer.
7320
7321}
7322
7323@LibEntry{math.modf (x)|
7324
7325Returns the integral part of @id{x} and the fractional part of @id{x}.
7326Its second result is always a float.
7327
7328}
7329
7330@LibEntry{math.pi|
7331
7332The value of @M{@pi}.
7333
7334}
7335
7336@LibEntry{math.rad (x)|
7337
7338Converts the angle @id{x} from degrees to radians.
7339
7340}
7341
7342@LibEntry{math.random ([m [, n]])|
7343
7344When called without arguments,
7345returns a pseudo-random float with uniform distribution
7346in the range @C{(} @M{[0,1)}. @C{]}
7347When called with two integers @id{m} and @id{n},
7348@id{math.random} returns a pseudo-random integer
7349with uniform distribution in the range @M{[m, n]}.
7350(The value @M{n-m} cannot be negative and must fit in a Lua integer.)
7351The call @T{math.random(n)} is equivalent to @T{math.random(1,n)}.
7352
7353This function is an interface to the underling
7354pseudo-random generator function provided by C.
7355
7356}
7357
7358@LibEntry{math.randomseed (x)|
7359
7360Sets @id{x} as the @Q{seed}
7361for the pseudo-random generator:
7362equal seeds produce equal sequences of numbers.
7363
7364}
7365
7366@LibEntry{math.sin (x)|
7367
7368Returns the sine of @id{x} (assumed to be in radians).
7369
7370}
7371
7372@LibEntry{math.sqrt (x)|
7373
7374Returns the square root of @id{x}.
7375(You can also use the expression @T{x^0.5} to compute this value.)
7376
7377}
7378
7379@LibEntry{math.tan (x)|
7380
7381Returns the tangent of @id{x} (assumed to be in radians).
7382
7383}
7384
7385@LibEntry{math.tointeger (x)|
7386
7387If the value @id{x} is convertible to an integer,
7388returns that integer.
7389Otherwise, returns @nil.
7390
7391}
7392
7393@LibEntry{math.type (x)|
7394
7395Returns @St{integer} if @id{x} is an integer,
7396@St{float} if it is a float,
7397or @nil if @id{x} is not a number.
7398
7399}
7400
7401@LibEntry{math.ult (m, n)|
7402
7403Returns a boolean,
7404true if and only if integer @id{m} is below integer @id{n} when
7405they are compared as @x{unsigned integers}.
7406
7407}
7408
7409}
7410
7411
7412@sect2{iolib| @title{Input and Output Facilities}
7413
7414The I/O library provides two different styles for file manipulation.
7415The first one uses implicit file handles;
7416that is, there are operations to set a default input file and a
7417default output file,
7418and all input/output operations are over these default files.
7419The second style uses explicit file handles.
7420
7421When using implicit file handles,
7422all operations are supplied by table @defid{io}.
7423When using explicit file handles,
7424the operation @Lid{io.open} returns a file handle
7425and then all operations are supplied as methods of the file handle.
7426
7427The table @id{io} also provides
7428three predefined file handles with their usual meanings from C:
7429@defid{io.stdin}, @defid{io.stdout}, and @defid{io.stderr}.
7430The I/O library never closes these files.
7431
7432Unless otherwise stated,
7433all I/O functions return @nil on failure
7434(plus an error message as a second result and
7435a system-dependent error code as a third result)
7436and some value different from @nil on success.
7437In non-POSIX systems,
7438the computation of the error message and error code
7439in case of errors
7440may be not @x{thread safe},
7441because they rely on the global C variable @id{errno}.
7442
7443@LibEntry{io.close ([file])|
7444
7445Equivalent to @T{file:close()}.
7446Without a @id{file}, closes the default output file.
7447
7448}
7449
7450@LibEntry{io.flush ()|
7451
7452Equivalent to @T{io.output():flush()}.
7453
7454}
7455
7456@LibEntry{io.input ([file])|
7457
7458When called with a file name, it opens the named file (in text mode),
7459and sets its handle as the default input file.
7460When called with a file handle,
7461it simply sets this file handle as the default input file.
7462When called without arguments,
7463it returns the current default input file.
7464
7465In case of errors this function raises the error,
7466instead of returning an error code.
7467
7468}
7469
7470@LibEntry{io.lines ([filename, @Cdots])|
7471
7472Opens the given file name in read mode
7473and returns an iterator function that
7474works like @T{file:lines(@Cdots)} over the opened file.
7475When the iterator function detects the end of file,
7476it returns no values (to finish the loop) and automatically closes the file.
7477
7478The call @T{io.lines()} (with no file name) is equivalent
7479to @T{io.input():lines("*l")};
7480that is, it iterates over the lines of the default input file.
7481In this case, the iterator does not close the file when the loop ends.
7482
7483In case of errors this function raises the error,
7484instead of returning an error code.
7485
7486}
7487
7488@LibEntry{io.open (filename [, mode])|
7489
7490This function opens a file,
7491in the mode specified in the string @id{mode}.
7492In case of success,
7493it returns a new file handle.
7494
7495The @id{mode} string can be any of the following:
7496@description{
7497@item{@St{r}| read mode (the default);}
7498@item{@St{w}| write mode;}
7499@item{@St{a}| append mode;}
7500@item{@St{r+}| update mode, all previous data is preserved;}
7501@item{@St{w+}| update mode, all previous data is erased;}
7502@item{@St{a+}| append update mode, previous data is preserved,
7503 writing is only allowed at the end of file.}
7504}
7505The @id{mode} string can also have a @Char{b} at the end,
7506which is needed in some systems to open the file in binary mode.
7507
7508}
7509
7510@LibEntry{io.output ([file])|
7511
7512Similar to @Lid{io.input}, but operates over the default output file.
7513
7514}
7515
7516@LibEntry{io.popen (prog [, mode])|
7517
7518This function is system dependent and is not available
7519on all platforms.
7520
7521Starts program @id{prog} in a separated process and returns
7522a file handle that you can use to read data from this program
7523(if @id{mode} is @T{"r"}, the default)
7524or to write data to this program
7525(if @id{mode} is @T{"w"}).
7526
7527}
7528
7529@LibEntry{io.read (@Cdots)|
7530
7531Equivalent to @T{io.input():read(@Cdots)}.
7532
7533}
7534
7535@LibEntry{io.tmpfile ()|
7536
7537In case of success,
7538returns a handle for a temporary file.
7539This file is opened in update mode
7540and it is automatically removed when the program ends.
7541
7542}
7543
7544@LibEntry{io.type (obj)|
7545
7546Checks whether @id{obj} is a valid file handle.
7547Returns the string @T{"file"} if @id{obj} is an open file handle,
7548@T{"closed file"} if @id{obj} is a closed file handle,
7549or @nil if @id{obj} is not a file handle.
7550
7551}
7552
7553@LibEntry{io.write (@Cdots)|
7554
7555Equivalent to @T{io.output():write(@Cdots)}.
7556
7557
7558}
7559
7560@LibEntry{file:close ()|
7561
7562Closes @id{file}.
7563Note that files are automatically closed when
7564their handles are garbage collected,
7565but that takes an unpredictable amount of time to happen.
7566
7567When closing a file handle created with @Lid{io.popen},
7568@Lid{file:close} returns the same values
7569returned by @Lid{os.execute}.
7570
7571}
7572
7573@LibEntry{file:flush ()|
7574
7575Saves any written data to @id{file}.
7576
7577}
7578
7579@LibEntry{file:lines (@Cdots)|
7580
7581Returns an iterator function that,
7582each time it is called,
7583reads the file according to the given formats.
7584When no format is given,
7585uses @St{l} as a default.
7586As an example, the construction
7587@verbatim{
7588for c in file:lines(1) do @rep{body} end
7589}
7590will iterate over all characters of the file,
7591starting at the current position.
7592Unlike @Lid{io.lines}, this function does not close the file
7593when the loop ends.
7594
7595In case of errors this function raises the error,
7596instead of returning an error code.
7597
7598}
7599
7600@LibEntry{file:read (@Cdots)|
7601
7602Reads the file @id{file},
7603according to the given formats, which specify what to read.
7604For each format,
7605the function returns a string or a number with the characters read,
7606or @nil if it cannot read data with the specified format.
7607(In this latter case,
7608the function does not read subsequent formats.)
7609When called without formats,
7610it uses a default format that reads the next line
7611(see below).
7612
7613The available formats are
7614@description{
7615
7616@item{@St{n}|
7617reads a numeral and returns it as a float or an integer,
7618following the lexical conventions of Lua.
7619(The numeral may have leading spaces and a sign.)
7620This format always reads the longest input sequence that
7621is a valid prefix for a numeral;
7622if that prefix does not form a valid numeral
7623(e.g., an empty string, @St{0x}, or @St{3.4e-}),
7624it is discarded and the function returns @nil.
7625}
7626
7627@item{@St{a}|
7628reads the whole file, starting at the current position.
7629On end of file, it returns the empty string.
7630}
7631
7632@item{@St{l}|
7633reads the next line skipping the end of line,
7634returning @nil on end of file.
7635This is the default format.
7636}
7637
7638@item{@St{L}|
7639reads the next line keeping the end-of-line character (if present),
7640returning @nil on end of file.
7641}
7642
7643@item{@emph{number}|
7644reads a string with up to this number of bytes,
7645returning @nil on end of file.
7646If @id{number} is zero,
7647it reads nothing and returns an empty string,
7648or @nil on end of file.
7649}
7650
7651}
7652The formats @St{l} and @St{L} should be used only for text files.
7653
7654}
7655
7656@LibEntry{file:seek ([whence [, offset]])|
7657
7658Sets and gets the file position,
7659measured from the beginning of the file,
7660to the position given by @id{offset} plus a base
7661specified by the string @id{whence}, as follows:
7662@description{
7663@item{@St{set}| base is position 0 (beginning of the file);}
7664@item{@St{cur}| base is current position;}
7665@item{@St{end}| base is end of file;}
7666}
7667In case of success, @id{seek} returns the final file position,
7668measured in bytes from the beginning of the file.
7669If @id{seek} fails, it returns @nil,
7670plus a string describing the error.
7671
7672The default value for @id{whence} is @T{"cur"},
7673and for @id{offset} is 0.
7674Therefore, the call @T{file:seek()} returns the current
7675file position, without changing it;
7676the call @T{file:seek("set")} sets the position to the
7677beginning of the file (and returns 0);
7678and the call @T{file:seek("end")} sets the position to the
7679end of the file, and returns its size.
7680
7681}
7682
7683@LibEntry{file:setvbuf (mode [, size])|
7684
7685Sets the buffering mode for an output file.
7686There are three available modes:
7687@description{
7688
7689@item{@St{no}|
7690no buffering; the result of any output operation appears immediately.
7691}
7692
7693@item{@St{full}|
7694full buffering; output operation is performed only
7695when the buffer is full or when
7696you explicitly @T{flush} the file @seeF{io.flush}.
7697}
7698
7699@item{@St{line}|
7700line buffering; output is buffered until a newline is output
7701or there is any input from some special files
7702(such as a terminal device).
7703}
7704
7705}
7706For the last two cases, @id{size}
7707specifies the size of the buffer, in bytes.
7708The default is an appropriate size.
7709
7710}
7711
7712@LibEntry{file:write (@Cdots)|
7713
7714Writes the value of each of its arguments to @id{file}.
7715The arguments must be strings or numbers.
7716
7717In case of success, this function returns @id{file}.
7718Otherwise it returns @nil plus a string describing the error.
7719
7720}
7721
7722}
7723
7724@sect2{oslib| @title{Operating System Facilities}
7725
7726This library is implemented through table @defid{os}.
7727
7728
7729@LibEntry{os.clock ()|
7730
7731Returns an approximation of the amount in seconds of CPU time
7732used by the program.
7733
7734}
7735
7736@LibEntry{os.date ([format [, time]])|
7737
7738Returns a string or a table containing date and time,
7739formatted according to the given string @id{format}.
7740
7741If the @id{time} argument is present,
7742this is the time to be formatted
7743(see the @Lid{os.time} function for a description of this value).
7744Otherwise, @id{date} formats the current time.
7745
7746If @id{format} starts with @Char{!},
7747then the date is formatted in Coordinated Universal Time.
7748After this optional character,
7749if @id{format} is the string @St{*t},
7750then @id{date} returns a table with the following fields:
7751@id{year}, @id{month} (1@En{}12), @id{day} (1@En{}31),
7752@id{hour} (0@En{}23), @id{min} (0@En{}59), @id{sec} (0@En{}61),
7753@id{wday} (weekday, 1@En{}7, Sunday @N{is 1}),
7754@id{yday} (day of the year, 1@En{}366),
7755and @id{isdst} (daylight saving flag, a boolean).
7756This last field may be absent
7757if the information is not available.
7758
7759If @id{format} is not @St{*t},
7760then @id{date} returns the date as a string,
7761formatted according to the same rules as the @ANSI{strftime}.
7762
7763When called without arguments,
7764@id{date} returns a reasonable date and time representation that depends on
7765the host system and on the current locale.
7766(More specifically, @T{os.date()} is equivalent to @T{os.date("%c")}.)
7767
7768In non-POSIX systems,
7769this function may be not @x{thread safe}
7770because of its reliance on @CId{gmtime} and @CId{localtime}.
7771
7772}
7773
7774@LibEntry{os.difftime (t2, t1)|
7775
7776Returns the difference, in seconds,
7777from time @id{t1} to time @id{t2}
7778(where the times are values returned by @Lid{os.time}).
7779In @x{POSIX}, @x{Windows}, and some other systems,
7780this value is exactly @id{t2}@M{-}@id{t1}.
7781
7782}
7783
7784@LibEntry{os.execute ([command])|
7785
7786This function is equivalent to the @ANSI{system}.
7787It passes @id{command} to be executed by an operating system shell.
7788Its first result is @true
7789if the command terminated successfully,
7790or @nil otherwise.
7791After this first result
7792the function returns a string plus a number,
7793as follows:
7794@description{
7795
7796@item{@St{exit}|
7797the command terminated normally;
7798the following number is the exit status of the command.
7799}
7800
7801@item{@St{signal}|
7802the command was terminated by a signal;
7803the following number is the signal that terminated the command.
7804}
7805
7806}
7807
7808When called without a @id{command},
7809@id{os.execute} returns a boolean that is true if a shell is available.
7810
7811}
7812
7813@LibEntry{os.exit ([code [, close]])|
7814
7815Calls the @ANSI{exit} to terminate the host program.
7816If @id{code} is @Rw{true},
7817the returned status is @idx{EXIT_SUCCESS};
7818if @id{code} is @Rw{false},
7819the returned status is @idx{EXIT_FAILURE};
7820if @id{code} is a number,
7821the returned status is this number.
7822The default value for @id{code} is @Rw{true}.
7823
7824If the optional second argument @id{close} is true,
7825closes the Lua state before exiting.
7826
7827}
7828
7829@LibEntry{os.getenv (varname)|
7830
7831Returns the value of the process environment variable @id{varname},
7832or @nil if the variable is not defined.
7833
7834}
7835
7836@LibEntry{os.remove (filename)|
7837
7838Deletes the file (or empty directory, on @x{POSIX} systems)
7839with the given name.
7840If this function fails, it returns @nil,
7841plus a string describing the error and the error code.
7842Otherwise, it returns true.
7843
7844}
7845
7846@LibEntry{os.rename (oldname, newname)|
7847
7848Renames the file or directory named @id{oldname} to @id{newname}.
7849If this function fails, it returns @nil,
7850plus a string describing the error and the error code.
7851Otherwise, it returns true.
7852
7853}
7854
7855@LibEntry{os.setlocale (locale [, category])|
7856
7857Sets the current locale of the program.
7858@id{locale} is a system-dependent string specifying a locale;
7859@id{category} is an optional string describing which category to change:
7860@T{"all"}, @T{"collate"}, @T{"ctype"},
7861@T{"monetary"}, @T{"numeric"}, or @T{"time"};
7862the default category is @T{"all"}.
7863The function returns the name of the new locale,
7864or @nil if the request cannot be honored.
7865
7866If @id{locale} is the empty string,
7867the current locale is set to an implementation-defined native locale.
7868If @id{locale} is the string @St{C},
7869the current locale is set to the standard C locale.
7870
7871When called with @nil as the first argument,
7872this function only returns the name of the current locale
7873for the given category.
7874
7875This function may be not @x{thread safe}
7876because of its reliance on @CId{setlocale}.
7877
7878}
7879
7880@LibEntry{os.time ([table])|
7881
7882Returns the current time when called without arguments,
7883or a time representing the local date and time specified by the given table.
7884This table must have fields @id{year}, @id{month}, and @id{day},
7885and may have fields
7886@id{hour} (default is 12),
7887@id{min} (default is 0),
7888@id{sec} (default is 0),
7889and @id{isdst} (default is @nil).
7890Other fields are ignored.
7891For a description of these fields, see the @Lid{os.date} function.
7892
7893The values in these fields do not need to be inside their valid ranges.
7894For instance, if @id{sec} is -10,
7895it means -10 seconds from the time specified by the other fields;
7896if @id{hour} is 1000,
7897it means +1000 hours from the time specified by the other fields.
7898
7899The returned value is a number, whose meaning depends on your system.
7900In @x{POSIX}, @x{Windows}, and some other systems,
7901this number counts the number
7902of seconds since some given start time (the @Q{epoch}).
7903In other systems, the meaning is not specified,
7904and the number returned by @id{time} can be used only as an argument to
7905@Lid{os.date} and @Lid{os.difftime}.
7906
7907}
7908
7909@LibEntry{os.tmpname ()|
7910
7911Returns a string with a file name that can
7912be used for a temporary file.
7913The file must be explicitly opened before its use
7914and explicitly removed when no longer needed.
7915
7916In @x{POSIX} systems,
7917this function also creates a file with that name,
7918to avoid security risks.
7919(Someone else might create the file with wrong permissions
7920in the time between getting the name and creating the file.)
7921You still have to open the file to use it
7922and to remove it (even if you do not use it).
7923
7924When possible,
7925you may prefer to use @Lid{io.tmpfile},
7926which automatically removes the file when the program ends.
7927
7928}
7929
7930}
7931
7932@sect2{debuglib| @title{The Debug Library}
7933
7934This library provides
7935the functionality of the @link{debugI|debug interface} to Lua programs.
7936You should exert care when using this library.
7937Several of its functions
7938violate basic assumptions about Lua code
7939(e.g., that variables local to a function
7940cannot be accessed from outside;
7941that userdata metatables cannot be changed by Lua code;
7942that Lua programs do not crash)
7943and therefore can compromise otherwise secure code.
7944Moreover, some functions in this library may be slow.
7945
7946All functions in this library are provided
7947inside the @defid{debug} table.
7948All functions that operate over a thread
7949have an optional first argument which is the
7950thread to operate over.
7951The default is always the current thread.
7952
7953
7954@LibEntry{debug.debug ()|
7955
7956Enters an interactive mode with the user,
7957running each string that the user enters.
7958Using simple commands and other debug facilities,
7959the user can inspect global and local variables,
7960change their values, evaluate expressions, and so on.
7961A line containing only the word @id{cont} finishes this function,
7962so that the caller continues its execution.
7963
7964Note that commands for @id{debug.debug} are not lexically nested
7965within any function and so have no direct access to local variables.
7966
7967}
7968
7969@LibEntry{debug.gethook ([thread])|
7970
7971Returns the current hook settings of the thread, as three values:
7972the current hook function, the current hook mask,
7973and the current hook count
7974(as set by the @Lid{debug.sethook} function).
7975
7976}
7977
7978@LibEntry{debug.getinfo ([thread,] f [, what])|
7979
7980Returns a table with information about a function.
7981You can give the function directly
7982or you can give a number as the value of @id{f},
7983which means the function running at level @id{f} of the call stack
7984of the given thread:
7985@N{level 0} is the current function (@id{getinfo} itself);
7986@N{level 1} is the function that called @id{getinfo}
7987(except for tail calls, which do not count on the stack);
7988and so on.
7989If @id{f} is a number larger than the number of active functions,
7990then @id{getinfo} returns @nil.
7991
7992The returned table can contain all the fields returned by @Lid{lua_getinfo},
7993with the string @id{what} describing which fields to fill in.
7994The default for @id{what} is to get all information available,
7995except the table of valid lines.
7996If present,
7997the option @Char{f}
7998adds a field named @id{func} with the function itself.
7999If present,
8000the option @Char{L}
8001adds a field named @id{activelines} with the table of
8002valid lines.
8003
8004For instance, the expression @T{debug.getinfo(1,"n").name} returns
8005a name for the current function,
8006if a reasonable name can be found,
8007and the expression @T{debug.getinfo(print)}
8008returns a table with all available information
8009about the @Lid{print} function.
8010
8011}
8012
8013@LibEntry{debug.getlocal ([thread,] f, local)|
8014
8015This function returns the name and the value of the local variable
8016with index @id{local} of the function at level @id{f} of the stack.
8017This function accesses not only explicit local variables,
8018but also parameters, temporaries, etc.
8019
8020The first parameter or local variable has @N{index 1}, and so on,
8021following the order that they are declared in the code,
8022counting only the variables that are active
8023in the current scope of the function.
8024Negative indices refer to vararg arguments;
8025@num{-1} is the first vararg argument.
8026The function returns @nil if there is no variable with the given index,
8027and raises an error when called with a level out of range.
8028(You can call @Lid{debug.getinfo} to check whether the level is valid.)
8029
8030Variable names starting with @Char{(} (open parenthesis) @C{)}
8031represent variables with no known names
8032(internal variables such as loop control variables,
8033and variables from chunks saved without debug information).
8034
8035The parameter @id{f} may also be a function.
8036In that case, @id{getlocal} returns only the name of function parameters.
8037
8038}
8039
8040@LibEntry{debug.getmetatable (value)|
8041
8042Returns the metatable of the given @id{value}
8043or @nil if it does not have a metatable.
8044
8045}
8046
8047@LibEntry{debug.getregistry ()|
8048
8049Returns the registry table @see{registry}.
8050
8051}
8052
8053@LibEntry{debug.getupvalue (f, up)|
8054
8055This function returns the name and the value of the upvalue
8056with index @id{up} of the function @id{f}.
8057The function returns @nil if there is no upvalue with the given index.
8058
8059Variable names starting with @Char{(} (open parenthesis) @C{)}
8060represent variables with no known names
8061(variables from chunks saved without debug information).
8062
8063}
8064
8065@LibEntry{debug.getuservalue (u)|
8066
8067Returns the Lua value associated to @id{u}.
8068If @id{u} is not a full userdata,
8069returns @nil.
8070
8071}
8072
8073@LibEntry{debug.sethook ([thread,] hook, mask [, count])|
8074
8075Sets the given function as a hook.
8076The string @id{mask} and the number @id{count} describe
8077when the hook will be called.
8078The string mask may have any combination of the following characters,
8079with the given meaning:
8080@description{
8081@item{@Char{c}| the hook is called every time Lua calls a function;}
8082@item{@Char{r}| the hook is called every time Lua returns from a function;}
8083@item{@Char{l}| the hook is called every time Lua enters a new line of code.}
8084}
8085Moreover,
8086with a @id{count} different from zero,
8087the hook is called also after every @id{count} instructions.
8088
8089When called without arguments,
8090@Lid{debug.sethook} turns off the hook.
8091
8092When the hook is called, its first argument is a string
8093describing the event that has triggered its call:
8094@T{"call"} (or @T{"tail call"}),
8095@T{"return"},
8096@T{"line"}, and @T{"count"}.
8097For line events,
8098the hook also gets the new line number as its second parameter.
8099Inside a hook,
8100you can call @id{getinfo} with @N{level 2} to get more information about
8101the running function
8102(@N{level 0} is the @id{getinfo} function,
8103and @N{level 1} is the hook function).
8104
8105}
8106
8107@LibEntry{debug.setlocal ([thread,] level, local, value)|
8108
8109This function assigns the value @id{value} to the local variable
8110with index @id{local} of the function at level @id{level} of the stack.
8111The function returns @nil if there is no local
8112variable with the given index,
8113and raises an error when called with a @id{level} out of range.
8114(You can call @id{getinfo} to check whether the level is valid.)
8115Otherwise, it returns the name of the local variable.
8116
8117See @Lid{debug.getlocal} for more information about
8118variable indices and names.
8119
8120}
8121
8122@LibEntry{debug.setmetatable (value, table)|
8123
8124Sets the metatable for the given @id{value} to the given @id{table}
8125(which can be @nil).
8126Returns @id{value}.
8127
8128}
8129
8130@LibEntry{debug.setupvalue (f, up, value)|
8131
8132This function assigns the value @id{value} to the upvalue
8133with index @id{up} of the function @id{f}.
8134The function returns @nil if there is no upvalue
8135with the given index.
8136Otherwise, it returns the name of the upvalue.
8137
8138}
8139
8140@LibEntry{debug.setuservalue (udata, value)|
8141
8142Sets the given @id{value} as
8143the Lua value associated to the given @id{udata}.
8144@id{udata} must be a full userdata.
8145
8146Returns @id{udata}.
8147
8148}
8149
8150@LibEntry{debug.traceback ([thread,] [message [, level]])|
8151
8152If @id{message} is present but is neither a string nor @nil,
8153this function returns @id{message} without further processing.
8154Otherwise,
8155it returns a string with a traceback of the call stack.
8156The optional @id{message} string is appended
8157at the beginning of the traceback.
8158An optional @id{level} number tells at which level
8159to start the traceback
8160(default is 1, the function calling @id{traceback}).
8161
8162}
8163
8164@LibEntry{debug.upvalueid (f, n)|
8165
8166Returns a unique identifier (as a light userdata)
8167for the upvalue numbered @id{n}
8168from the given function.
8169
8170These unique identifiers allow a program to check whether different
8171closures share upvalues.
8172Lua closures that share an upvalue
8173(that is, that access a same external local variable)
8174will return identical ids for those upvalue indices.
8175
8176}
8177
8178@LibEntry{debug.upvaluejoin (f1, n1, f2, n2)|
8179
8180Make the @id{n1}-th upvalue of the Lua closure @id{f1}
8181refer to the @id{n2}-th upvalue of the Lua closure @id{f2}.
8182
8183}
8184
8185}
8186
8187}
8188
8189
8190@C{-------------------------------------------------------------------------}
8191@sect1{lua-sa| @title{Lua Standalone}
8192
8193Although Lua has been designed as an extension language,
8194to be embedded in a host @N{C program},
8195it is also frequently used as a standalone language.
8196An interpreter for Lua as a standalone language,
8197called simply @id{lua},
8198is provided with the standard distribution.
8199The @x{standalone interpreter} includes
8200all standard libraries, including the debug library.
8201Its usage is:
8202@verbatim{
8203lua [options] [script [args]]
8204}
8205The options are:
8206@description{
8207@item{@T{-e @rep{stat}}| executes string @rep{stat};}
8208@item{@T{-l @rep{mod}}| @Q{requires} @rep{mod} and assigns the
8209 result to global @@rep{mod};}
8210@item{@T{-i}| enters interactive mode after running @rep{script};}
8211@item{@T{-v}| prints version information;}
8212@item{@T{-E}| ignores environment variables;}
8213@item{@T{--}| stops handling options;}
8214@item{@T{-}| executes @id{stdin} as a file and stops handling options.}
8215}
8216After handling its options, @id{lua} runs the given @emph{script}.
8217When called without arguments,
8218@id{lua} behaves as @T{lua -v -i}
8219when the standard input (@id{stdin}) is a terminal,
8220and as @T{lua -} otherwise.
8221
8222When called without option @T{-E},
8223the interpreter checks for an environment variable @defid{LUA_INIT_5_3}
8224(or @defid{LUA_INIT} if the versioned name is not defined)
8225before running any argument.
8226If the variable content has the format @T{@At@rep{filename}},
8227then @id{lua} executes the file.
8228Otherwise, @id{lua} executes the string itself.
8229
8230When called with option @T{-E},
8231besides ignoring @id{LUA_INIT},
8232Lua also ignores
8233the values of @id{LUA_PATH} and @id{LUA_CPATH},
8234setting the values of
8235@Lid{package.path} and @Lid{package.cpath}
8236with the default paths defined in @id{luaconf.h}.
8237
8238All options are handled in order, except @T{-i} and @T{-E}.
8239For instance, an invocation like
8240@verbatim{
8241$ lua -e'a=1' -e 'print(a)' script.lua
8242}
8243will first set @id{a} to 1, then print the value of @id{a},
8244and finally run the file @id{script.lua} with no arguments.
8245(Here @T{$} is the shell prompt. Your prompt may be different.)
8246
8247Before running any code,
8248@id{lua} collects all command-line arguments
8249in a global table called @id{arg}.
8250The script name goes to index 0,
8251the first argument after the script name goes to index 1,
8252and so on.
8253Any arguments before the script name
8254(that is, the interpreter name plus its options)
8255go to negative indices.
8256For instance, in the call
8257@verbatim{
8258$ lua -la b.lua t1 t2
8259}
8260the table is like this:
8261@verbatim{
8262arg = { [-2] = "lua", [-1] = "-la",
8263 [0] = "b.lua",
8264 [1] = "t1", [2] = "t2" }
8265}
8266If there is no script in the call,
8267the interpreter name goes to index 0,
8268followed by the other arguments.
8269For instance, the call
8270@verbatim{
8271$ lua -e "print(arg[1])"
8272}
8273will print @St{-e}.
8274If there is a script,
8275the script is called with arguments
8276@T{arg[1]}, @Cdots, @T{arg[#arg]}.
8277(Like all chunks in Lua,
8278the script is compiled as a vararg function.)
8279
8280In interactive mode,
8281Lua repeatedly prompts and waits for a line.
8282After reading a line,
8283Lua first try to interpret the line as an expression.
8284If it succeeds, it prints its value.
8285Otherwise, it interprets the line as a statement.
8286If you write an incomplete statement,
8287the interpreter waits for its completion
8288by issuing a different prompt.
8289
8290If the global variable @defid{_PROMPT} contains a string,
8291then its value is used as the prompt.
8292Similarly, if the global variable @defid{_PROMPT2} contains a string,
8293its value is used as the secondary prompt
8294(issued during incomplete statements).
8295
8296In case of unprotected errors in the script,
8297the interpreter reports the error to the standard error stream.
8298If the error object is not a string but
8299has a metamethod @idx{__tostring},
8300the interpreter calls this metamethod to produce the final message.
8301Otherwise, the interpreter converts the error object to a string
8302and adds a stack traceback to it.
8303
8304When finishing normally,
8305the interpreter closes its main Lua state
8306@seeF{lua_close}.
8307The script can avoid this step by
8308calling @Lid{os.exit} to terminate.
8309
8310To allow the use of Lua as a
8311script interpreter in Unix systems,
8312the standalone interpreter skips
8313the first line of a chunk if it starts with @T{#}.
8314Therefore, Lua scripts can be made into executable programs
8315by using @T{chmod +x} and @N{the @T{#!}} form,
8316as in
8317@verbatim{
8318#!/usr/local/bin/lua
8319}
8320(Of course,
8321the location of the Lua interpreter may be different in your machine.
8322If @id{lua} is in your @id{PATH},
8323then
8324@verbatim{
8325#!/usr/bin/env lua
8326}
8327is a more portable solution.)
8328
8329}
8330
8331
8332@sect1{incompat| @title{Incompatibilities with the Previous Version}
8333
8334Here we list the incompatibilities that you may find when moving a program
8335from @N{Lua 5.2} to @N{Lua 5.3}.
8336You can avoid some incompatibilities by compiling Lua with
8337appropriate options (see file @id{luaconf.h}).
8338However,
8339all these compatibility options will be removed in the future.
8340
8341Lua versions can always change the C API in ways that
8342do not imply source-code changes in a program,
8343such as the numeric values for constants
8344or the implementation of functions as macros.
8345Therefore,
8346you should not assume that binaries are compatible between
8347different Lua versions.
8348Always recompile clients of the Lua API when
8349using a new version.
8350
8351Similarly, Lua versions can always change the internal representation
8352of precompiled chunks;
8353precompiled chunks are not compatible between different Lua versions.
8354
8355The standard paths in the official distribution may
8356change between versions.
8357
8358@sect2{@title{Changes in the Language}
8359@itemize{
8360
8361@item{
8362The main difference between @N{Lua 5.2} and @N{Lua 5.3} is the
8363introduction of an integer subtype for numbers.
8364Although this change should not affect @Q{normal} computations,
8365some computations
8366(mainly those that involve some kind of overflow)
8367can give different results.
8368
8369You can fix these differences by forcing a number to be a float
8370(in @N{Lua 5.2} all numbers were float),
8371in particular writing constants with an ending @T{.0}
8372or using @T{x = x + 0.0} to convert a variable.
8373(This recommendation is only for a quick fix
8374for an occasional incompatibility;
8375it is not a general guideline for good programming.
8376For good programming,
8377use floats where you need floats
8378and integers where you need integers.)
8379}
8380
8381@item{
8382The conversion of a float to a string now adds a @T{.0} suffix
8383to the result if it looks like an integer.
8384(For instance, the float 2.0 will be printed as @T{2.0},
8385not as @T{2}.)
8386You should always use an explicit format
8387when you need a specific format for numbers.
8388
8389(Formally this is not an incompatibility,
8390because Lua does not specify how numbers are formatted as strings,
8391but some programs assumed a specific format.)
8392}
8393
8394@item{
8395The generational mode for the garbage collector was removed.
8396(It was an experimental feature in @N{Lua 5.2}.)
8397}
8398
8399}
8400
8401}
8402
8403@sect2{@title{Changes in the Libraries}
8404@itemize{
8405
8406@item{
8407The @id{bit32} library has been deprecated.
8408It is easy to require a compatible external library or,
8409better yet, to replace its functions with appropriate bitwise operations.
8410(Keep in mind that @id{bit32} operates on 32-bit integers,
8411while the bitwise operators in @N{Lua 5.3} operate on Lua integers,
8412which by default have @N{64 bits}.)
8413}
8414
8415@item{
8416The Table library now respects metamethods
8417for setting and getting elements.
8418}
8419
8420@item{
8421The @Lid{ipairs} iterator now respects metamethods and
8422its @idx{__ipairs} metamethod has been deprecated.
8423}
8424
8425
8426@item{
8427Option names in @Lid{io.read} do not have a starting @Char{*} anymore.
8428For compatibility, Lua will continue to accept (and ignore) this character.
8429}
8430
8431@item{
8432The following functions were deprecated in the mathematical library:
8433@id{atan2}, @id{cosh}, @id{sinh}, @id{tanh}, @id{pow},
8434@id{frexp}, and @id{ldexp}.
8435You can replace @T{math.pow(x,y)} with @T{x^y};
8436you can replace @id{math.atan2} with @id{math.atan},
8437which now accepts one or two arguments;
8438you can replace @T{math.ldexp(x,exp)} with @T{x * 2.0^exp}.
8439For the other operations,
8440you can either use an external library or
8441implement them in Lua.
8442}
8443
8444@item{
8445The searcher for C loaders used by @Lid{require}
8446changed the way it handles versioned names.
8447Now, the version should come after the module name
8448(as is usual in most other tools).
8449For compatibility, that searcher still tries the old format
8450if it cannot find an open function according to the new style.
8451(@N{Lua 5.2} already worked that way,
8452but it did not document the change.)
8453}
8454
8455@item{
8456The call @T{collectgarbage("count")} now returns only one result.
8457(You can compute that second result from the fractional part
8458of the first result.)
8459}
8460
8461}
8462
8463}
8464
8465@sect2{@title{Changes in the API}
8466
8467@itemize{
8468
8469@item{
8470Continuation functions now receive as arguments what they needed
8471to get through @id{lua_getctx},
8472so @id{lua_getctx} has been removed.
8473Adapt your code accordingly.
8474}
8475
8476@item{
8477Function @Lid{lua_dump} has an extra parameter, @id{strip}.
8478Use 0 as the value of this parameter to get the old behavior.
8479}
8480
8481@item{
8482Functions to inject/project unsigned integers
8483(@id{lua_pushunsigned}, @id{lua_tounsigned}, @id{lua_tounsignedx},
8484@id{luaL_checkunsigned}, @id{luaL_optunsigned})
8485were deprecated.
8486Use their signed equivalents with a type cast.
8487}
8488
8489@item{
8490Macros to project non-default integer types
8491(@id{luaL_checkint}, @id{luaL_optint}, @id{luaL_checklong}, @id{luaL_optlong})
8492were deprecated.
8493Use their equivalent over @Lid{lua_Integer} with a type cast
8494(or, when possible, use @Lid{lua_Integer} in your code).
8495}
8496
8497}
8498
8499}
8500
8501}
8502
8503
8504@C{[===============================================================}
8505
8506@sect1{BNF| @title{The Complete Syntax of Lua}
8507
8508Here is the complete syntax of Lua in extended BNF.
8509As usual in extended BNF,
8510@bnfNter{{A}} means 0 or more @bnfNter{A}s,
8511and @bnfNter{[A]} means an optional @bnfNter{A}.
8512(For operator precedences, see @See{prec};
8513for a description of the terminals
8514@bnfNter{Name}, @bnfNter{Numeral},
8515and @bnfNter{LiteralString}, see @See{lexical}.)
8516@index{grammar}
8517
8518@Produc{
8519
8520@producname{chunk}@producbody{block}
8521
8522@producname{block}@producbody{@bnfrep{stat} @bnfopt{retstat}}
8523
8524@producname{stat}@producbody{
8525 @bnfter{;}
8526@OrNL varlist @bnfter{=} explist
8527@OrNL functioncall
8528@OrNL label
8529@OrNL @Rw{break}
8530@OrNL @Rw{goto} Name
8531@OrNL @Rw{do} block @Rw{end}
8532@OrNL @Rw{while} exp @Rw{do} block @Rw{end}
8533@OrNL @Rw{repeat} block @Rw{until} exp
8534@OrNL @Rw{if} exp @Rw{then} block
8535 @bnfrep{@Rw{elseif} exp @Rw{then} block}
8536 @bnfopt{@Rw{else} block} @Rw{end}
8537@OrNL @Rw{for} @bnfNter{Name} @bnfter{=} exp @bnfter{,} exp @bnfopt{@bnfter{,} exp}
8538 @Rw{do} block @Rw{end}
8539@OrNL @Rw{for} namelist @Rw{in} explist @Rw{do} block @Rw{end}
8540@OrNL @Rw{function} funcname funcbody
8541@OrNL @Rw{local} @Rw{function} @bnfNter{Name} funcbody
8542@OrNL @Rw{local} namelist @bnfopt{@bnfter{=} explist}
8543}
8544
8545@producname{retstat}@producbody{@Rw{return}
8546 @bnfopt{explist} @bnfopt{@bnfter{;}}}
8547
8548@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
8549
8550@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}}
8551 @bnfopt{@bnfter{:} @bnfNter{Name}}}
8552
8553@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
8554
8555@producname{var}@producbody{
8556 @bnfNter{Name}
8557@Or prefixexp @bnfter{[} exp @bnfter{]}
8558@Or prefixexp @bnfter{.} @bnfNter{Name}
8559}
8560
8561@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
8562
8563
8564@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
8565
8566@producname{exp}@producbody{
8567 @Rw{nil}
8568@Or @Rw{false}
8569@Or @Rw{true}
8570@Or @bnfNter{Numeral}
8571@Or @bnfNter{LiteralString}
8572@Or @bnfter{...}
8573@Or functiondef
8574@OrNL prefixexp
8575@Or tableconstructor
8576@Or exp binop exp
8577@Or unop exp
8578}
8579
8580@producname{prefixexp}@producbody{var @Or functioncall @Or @bnfter{(} exp @bnfter{)}}
8581
8582@producname{functioncall}@producbody{
8583 prefixexp args
8584@Or prefixexp @bnfter{:} @bnfNter{Name} args
8585}
8586
8587@producname{args}@producbody{
8588 @bnfter{(} @bnfopt{explist} @bnfter{)}
8589@Or tableconstructor
8590@Or @bnfNter{LiteralString}
8591}
8592
8593@producname{functiondef}@producbody{@Rw{function} funcbody}
8594
8595@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
8596
8597@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}}
8598 @Or @bnfter{...}}
8599
8600@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
8601
8602@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
8603
8604@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or @bnfNter{Name} @bnfter{=} exp @Or exp}
8605
8606@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
8607
8608@producname{binop}@producbody{
8609 @bnfter{+} @Or @bnfter{-} @Or @bnfter{*} @Or @bnfter{/} @Or @bnfter{//}
8610 @Or @bnfter{^} @Or @bnfter{%}
8611 @OrNL
8612 @bnfter{&} @Or @bnfter{~} @Or @bnfter{|} @Or @bnfter{>>} @Or @bnfter{<<}
8613 @Or @bnfter{..}
8614 @OrNL
8615 @bnfter{<} @Or @bnfter{<=} @Or @bnfter{>} @Or @bnfter{>=}
8616 @Or @bnfter{==} @Or @bnfter{~=}
8617 @OrNL
8618 @Rw{and} @Or @Rw{or}}
8619
8620@producname{unop}@producbody{@bnfter{-} @Or @Rw{not} @Or @bnfter{#} @Or
8621 @bnfter{~}}
8622
8623}
8624
8625}
8626
8627@C{]===============================================================}
8628
8629}
8630@C{)]-------------------------------------------------------------------------}