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