interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / manual / manual.of

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