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