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