luaref.txt (227178B)
1 *luaref.txt* Nvim 2 *luaref* 3 4 LUA REFERENCE MANUAL 5 6 7 Version 0.3.0 8 August 7th, 2022 9 10 11 Vimdoc version (c) 2006 by Luis Carvalho 12 <lexcarvalho at gmail dot com> 13 14 Adapted from "Lua: 5.1 reference manual" 15 R. Ierusalimschy, L. H. de Figueiredo, W. Celes 16 Copyright (c) 2006 Lua.org, PUC-Rio. 17 18 19 See |lua-ref-doc| for information on this manual. 20 See |lua-ref-copyright| for copyright and licenses. 21 22 23 Type |gO| to see the table of contents. 24 25 ============================================================================== 26 1 INTRODUCTION *luaref-intro* 27 28 Lua is an extension programming language designed to support general 29 procedural programming with data description facilities. It also offers good 30 support for object-oriented programming, functional programming, and 31 data-driven programming. Lua is intended to be used as a powerful, 32 light-weight scripting language for any program that needs one. Lua is 33 implemented as a library, written in clean C (that is, in the common subset of 34 ANSI C and C++). 35 36 Being an extension language, Lua has no notion of a "main" program: it only 37 works embedded in a host client, called the embedding program or simply the 38 host. This host program can invoke functions to execute a piece of Lua code, 39 can write and read Lua variables, and can register C functions to be called by 40 Lua code. Through the use of C functions, Lua can be augmented to cope with a 41 wide range of different domains, thus creating customized programming 42 languages sharing a syntactical framework. 43 44 Lua is free software, and is provided as usual with no guarantees, as stated 45 in its license. The implementation described in this manual is available at 46 Lua's official web site, www.lua.org. 47 48 Like any other reference manual, this document is dry in places. For a 49 discussion of the decisions behind the design of Lua, see references at 50 |lua-ref-bibliography|. For a detailed introduction to programming in Lua, see 51 Roberto's book, Programming in Lua. 52 53 Lua means "moon" in Portuguese and is pronounced LOO-ah. 54 55 ============================================================================== 56 2 THE LANGUAGE *lua-language* 57 58 This section describes the lexis, the syntax, and the semantics of Lua. In 59 other words, this section describes which tokens are valid, how they can be 60 combined, and what their combinations mean. 61 62 The language constructs will be explained using the usual extended BNF 63 notation, in which `{ a }` means 0 or more `a`'s, and `[ a ]` means an optional `a`. 64 65 ============================================================================== 66 2.1 Lexical Conventions *lua-lexical* 67 68 *lua-names* *lua-identifiers* 69 Names (also called identifiers) in Lua can be any string of letters, digits, 70 and underscores, not beginning with a digit. This coincides with the 71 definition of identifiers in most languages. (The definition of letter depends 72 on the current locale: any character considered alphabetic by the current 73 locale can be used in an identifier.) Identifiers are used to name variables 74 and table fields. 75 76 The following keywords are reserved and cannot be used as names: 77 > 78 and break do else elseif 79 end false for function if 80 in local nil not or 81 repeat return then true until while 82 < 83 Lua is a case-sensitive language: `and` is a reserved word, but `And` and `AND` are 84 two different, valid names. As a convention, names starting with an underscore 85 followed by uppercase letters (such as `_VERSION`) are reserved for internal 86 global variables used by Lua. 87 88 The following strings denote other tokens: 89 > 90 + - * / % ^ # 91 == ~= <= >= < > = 92 ( ) { } [ ] 93 ; : , . .. ... 94 < 95 *lua-literal* 96 Literal strings can be delimited by matching single or double quotes, and can 97 contain the following C-like escape sequences: 98 99 - `\a` bell 100 - `\b` backspace 101 - `\f` form feed 102 - `\n` newline 103 - `\r` carriage return 104 - `\t` horizontal tab 105 - `\v` vertical tab 106 - `\\` backslash 107 - `\"` quotation mark (double quote) 108 - `\'` apostrophe (single quote) 109 110 Moreover, a backslash followed by a real newline results in a newline in the 111 string. A character in a string may also be specified by its numerical value 112 using the escape sequence `\ddd`, where `ddd` is a sequence of up to three 113 decimal digits. (Note that if a numerical escape is to be followed by a digit, 114 it must be expressed using exactly three digits.) Strings in Lua may contain 115 any 8-bit value, including embedded zeros, which can be specified as `\0`. 116 117 To put a double (single) quote, a newline, a backslash, or an embedded zero 118 inside a literal string enclosed by double (single) quotes you must use an 119 escape sequence. Any other character may be directly inserted into the 120 literal. (Some control characters may cause problems for the file system, but 121 Lua has no problem with them.) 122 123 Literal strings can also be defined using a long format enclosed by long 124 brackets. We define an opening long bracket of level n as an opening square 125 bracket followed by n equal signs followed by another opening square bracket. 126 So, an opening long bracket of level 0 is written as `[[`, an opening long 127 bracket of level 1 is written as `[=[`, and so on. 128 A closing long bracket is defined similarly; for instance, a closing long 129 bracket of level 4 is written as `]====]`. A long string starts with an 130 opening long bracket of any level and ends at the first closing long bracket 131 of the same level. Literals in this bracketed form may run for several lines, 132 do not interpret any escape sequences, and ignore long brackets of any other 133 level. They may contain anything except a closing bracket of the proper level. 134 135 For convenience, when the opening long bracket is immediately followed by a 136 newline, the newline is not included in the string. As an example, in a system 137 using ASCII (in which `a` is coded as 97, newline is coded as 10, and `1` is 138 coded as 49), the five literals below denote the same string: 139 >lua 140 a = 'alo\n123"' 141 a = "alo\n123\"" 142 a = '\97lo\10\04923"' 143 a = [[alo 144 123"]] 145 a = [==[ 146 alo 147 123"]==] 148 < 149 *lua-numconstant* 150 A numerical constant may be written with an optional decimal part and an 151 optional decimal exponent. Lua also accepts integer hexadecimal constants, by 152 prefixing them with `0x`. Examples of valid numerical constants are 153 > 154 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56 155 < 156 *lua-comment* 157 A comment starts with a double hyphen (`--`) anywhere outside a string. If the 158 text immediately after `--` is not an opening long bracket, the comment is a 159 short comment, which runs until the end of the line. Otherwise, it is a long 160 comment, which runs until the corresponding closing long bracket. Long 161 comments are frequently used to disable code temporarily. 162 163 ============================================================================== 164 2.2 Values and Types *lua-values* 165 166 Lua is a dynamically typed language. This means that variables do not have 167 types; only values do. There are no type definitions in the language. All 168 values carry their own type. 169 170 All values in Lua are first-class values. This means that all values can be 171 stored in variables, passed as arguments to other functions, and returned as 172 results. 173 174 *lua-types* *lua-nil* 175 *lua-true* *lua-false* 176 *lua-number* *lua-string* 177 There are eight basic types in Lua: `nil`, `boolean`, `number`, `string`, 178 `function`, `userdata`, `thread`, and `table`. Nil is the type of the value 179 `nil`, whose main property is to be different from any other value; it usually 180 represents the absence of a useful value. Boolean is the type of the values 181 `false` and `true`. Both `nil` and `false` make a condition false; any other 182 value makes it true. Number represents real (double-precision floating-point) 183 numbers. (It is easy to build Lua interpreters that use other internal 184 representations for numbers, such as single-precision float or long integers; 185 see file `luaconf.h`.) String represents arrays of characters. Lua is 8-bit 186 clean: strings may contain any 8-bit character, including embedded zeros 187 (`\0`) (see |lua-literal|). 188 189 Lua can call (and manipulate) functions written in Lua and functions written 190 in C (see |lua-function|). 191 192 *lua-userdatatype* 193 The type userdata is provided to allow arbitrary C data to be stored in Lua 194 variables. This type corresponds to a block of raw memory and has no 195 pre-defined operations in Lua, except assignment and identity test. However, 196 by using metatables, the programmer can define operations for userdata values 197 (see |lua-metatable|). Userdata values cannot be created or modified in Lua, 198 only through the C API. This guarantees the integrity of data owned by the 199 host program. 200 201 *lua-thread* 202 The type `thread` represents independent threads of execution and it is used to 203 implement coroutines (see |lua-coroutine|). Do not confuse Lua threads with 204 operating-system threads. Lua supports coroutines on all systems, even those 205 that do not support threads. 206 207 *lua-table* 208 The type `table` implements associative arrays, that is, arrays that can be 209 indexed not only with numbers, but with any value (except `nil`). Tables can 210 be heterogeneous; that is, they can contain values of all types (except 211 `nil`). Tables are the sole data structuring mechanism in Lua; they may be 212 used to represent ordinary arrays, symbol tables, sets, records, graphs, 213 trees, etc. To represent records, Lua uses the field name as an index. The 214 language supports this representation by providing `a.name` as syntactic sugar 215 for `a["name"]`. There are several convenient ways to create tables in Lua 216 (see |lua-tableconstructor|). 217 218 Like indices, the value of a table field can be of any type (except `nil`). In 219 particular, because functions are first-class values, table fields may contain 220 functions. Thus tables may also carry methods (see |lua-function-define|). 221 222 Tables, functions, threads and (full) userdata values are objects: variables 223 do not actually contain these values, only references to them. Assignment, 224 parameter passing, and function returns always manipulate references to such 225 values; these operations do not imply any kind of copy. 226 227 The library function `type` returns a string describing the type of a given 228 value (see |lua-type()|). 229 230 ------------------------------------------------------------------------------ 231 2.2.1 Coercion *lua-coercion* 232 233 Lua provides automatic conversion between string and number values at run 234 time. Any arithmetic operation applied to a string tries to convert that 235 string to a number, following the usual conversion rules. Conversely, whenever 236 a number is used where a string is expected, the number is converted to a 237 string, in a reasonable format. For complete control of how numbers are 238 converted to strings, use the `format` function from the string library (see 239 |string.format()|). 240 241 ============================================================================== 242 2.3 Variables *lua-variables* 243 244 Variables are places that store values. There are three kinds of variables in 245 Lua: global variables, local variables, and table fields. 246 247 A single name can denote a global variable or a local variable (or a 248 function's formal parameter, which is a particular form of local variable): 249 > 250 var ::= Name 251 < 252 Name denotes identifiers, as defined in |lua-lexical|. 253 254 Any variable is assumed to be global unless explicitly declared as a local 255 (see |lua-local|). Local variables are lexically scoped: local 256 variables can be freely accessed by functions defined inside their scope (see 257 |lua-visibility|). 258 259 Before the first assignment to a variable, its value is `nil`. 260 261 Square brackets are used to index a table: 262 > 263 var ::= prefixexp [ exp ] 264 < 265 The first expression (`prefixexp`) should result in a table value; the second 266 expression (`exp`) identifies a specific entry inside that table. The 267 expression denoting the table to be indexed has a restricted syntax; see 268 |lua-expressions| for details. 269 270 The syntax `var.NAME` is just syntactic sugar for `var["NAME"]` : 271 > 272 var ::= prefixexp . Name 273 < 274 All global variables live as fields in ordinary Lua tables, called environment 275 tables or simply environments (see |lua-environments|). Each function 276 has its own reference to an environment, so that all global variables in this 277 function will refer to this environment table. When a function is created, it 278 inherits the environment from the function that created it. To get the 279 environment table of a Lua function, you call `getfenv` (see 280 |lua_getfenv()|). To replace it, you call `setfenv` (see |setfenv()|). 281 (You can only manipulate the environment of C functions through the debug 282 library; see |lua-lib-debug|.) 283 284 An access to a global variable `x` is equivalent to `_env.x`, which in turn is 285 equivalent to 286 >lua 287 gettable_event(_env, "x") 288 < 289 where `_env` is the environment of the running function. (The `_env` variable is 290 not defined in Lua. We use it here only for explanatory purposes.) 291 292 The meaning of accesses to global variables and table fields can be changed 293 via metatables. An access to an indexed variable `t[i]` is equivalent to a 294 call `gettable_event(t,i)`. (See |lua-metatable| for a complete description of 295 the `gettable_event` function. This function is not defined or callable in 296 Lua. We use it here only for explanatory purposes.) 297 298 ============================================================================== 299 2.4 Statements *lua-statement* 300 301 Lua supports an almost conventional set of statements, similar to those in 302 Pascal or C. This set includes assignment, control structures, function 303 calls, and variable declarations. 304 305 ------------------------------------------------------------------------------ 306 2.4.1 Chunks *lua-chunk* 307 308 The unit of execution of Lua is called a chunk. A chunk is simply a sequence 309 of statements, which are executed sequentially. Each statement can be 310 optionally followed by a semicolon: 311 > 312 chunk ::= {stat [ ; ]} 313 < 314 There are no empty statements and thus `;;` is not legal. 315 316 Lua handles a chunk as the body of an anonymous function with a variable 317 number of arguments (see |lua-function-define|). As such, chunks can define 318 local variables, receive arguments, and return values. 319 320 A chunk may be stored in a file or in a string inside the host program. When a 321 chunk is executed, first it is pre-compiled into instructions for a virtual 322 machine, and then the compiled code is executed by an interpreter for the 323 virtual machine. 324 325 Chunks may also be pre-compiled into binary form; see program `luac` for 326 details. Programs in source and compiled forms are interchangeable; Lua 327 automatically detects the file type and acts accordingly. 328 329 ------------------------------------------------------------------------------ 330 2.4.2 Blocks *lua-block* 331 332 A block is a list of statements; syntactically, a block is the same as a 333 chunk: 334 > 335 block ::= chunk 336 < 337 *lua-do* *lua-end* 338 A block may be explicitly delimited to produce a single statement: 339 > 340 stat ::= do block end 341 < 342 Explicit blocks are useful to control the scope of variable declarations. 343 Explicit blocks are also sometimes used to add a `return` or `break` statement 344 in the middle of another block (see |lua-control|). 345 346 ------------------------------------------------------------------------------ 347 2.4.3 Assignment *lua-assign* 348 349 Lua allows multiple assignment. Therefore, the syntax for assignment defines a 350 list of variables on the left side and a list of expressions on the right 351 side. The elements in both lists are separated by commas: 352 > 353 stat ::= varlist1 = explist1 354 varlist1 ::= var { , var } 355 explist1 ::= exp { , exp } 356 < 357 Expressions are discussed in |lua-expressions|. 358 359 Before the assignment, the list of values is adjusted to the length of the 360 list of variables. If there are more values than needed, the excess values are 361 thrown away. If there are fewer values than needed, the list is extended with 362 as many `nil`s as needed. If the list of expressions ends with a function 363 call, then all values returned by this call enter in the list of values, 364 before the adjustment (except when the call is enclosed in parentheses; see 365 |lua-expressions|). 366 367 The assignment statement first evaluates all its expressions and only then are 368 the assignments performed. Thus the code 369 >lua 370 i = 3 371 i, a[i] = i+1, 20 372 < 373 sets `a[3]` to 20, without affecting `a[4]` because the `i` in `a[i]` is evaluated (to 374 3) before it is assigned 4. Similarly, the line 375 >lua 376 x, y = y, x 377 < 378 exchanges the values of `x` and `y`. 379 380 The meaning of assignments to global variables and table fields can be changed 381 via metatables. An assignment to an indexed variable `t[i] = val` is 382 equivalent to `settable_event(t,i,val)`. (See |lua-metatable| for a complete 383 description of the `settable_event` function. This function is not defined or 384 callable in Lua. We use it here only for explanatory purposes.) 385 386 An assignment to a global variable `x = val` is equivalent to the 387 assignment `_env.x = val`, which in turn is equivalent to 388 >lua 389 settable_event(_env, "x", val) 390 < 391 where `_env` is the environment of the running function. (The `_env` variable is 392 not defined in Lua. We use it here only for explanatory purposes.) 393 394 ------------------------------------------------------------------------------ 395 2.4.4 Control Structures *lua-control* 396 397 *lua-if* *lua-then* *lua-else* *lua-elseif* 398 *lua-while* *lua-repeat* *lua-until* 399 The control structures `if`, `while`, and `repeat` have the usual meaning and 400 familiar syntax: 401 > 402 stat ::= while exp do block end 403 stat ::= repeat block until exp 404 stat ::= if exp then block { elseif exp then block } 405 [ else block ] end 406 < 407 Lua also has a `for` statement, in two flavors (see |lua-for|). 408 409 The condition expression of a control structure may return any value. 410 Both `false` and `nil` are considered false. All values different 411 from `nil` and `false` are considered true (in particular, the number 0 and the 412 empty string are also true). 413 414 In the `repeat-until` loop, the inner block does not end at the `until` keyword, 415 but only after the condition. So, the condition can refer to local variables 416 declared inside the loop block. 417 418 *lua-return* 419 The `return` statement is used to return values from a function or a chunk 420 (which is just a function). Functions and chunks may return more than one 421 value, so the syntax for the `return` statement is 422 423 `stat ::=` `return` `[explist1]` 424 425 *lua-break* 426 The `break` statement is used to terminate the execution of a `while`, `repeat`, 427 or `for` loop, skipping to the next statement after the loop: 428 429 `stat ::=` `break` 430 431 A `break` ends the innermost enclosing loop. 432 433 The `return` and `break` statements can only be written as the `last` 434 statement of a block. If it is really necessary to `return` or `break` in the 435 middle of a block, then an explicit inner block can be used, as in the idioms 436 `do return end` and `do break end`, because now `return` and `break` are 437 the last statements in their (inner) blocks. 438 439 ------------------------------------------------------------------------------ 440 2.4.5 For Statement *for* *lua-for* 441 442 The `for` statement has two forms: one numeric and one generic. 443 444 The numeric `for` loop repeats a block of code while a control variable runs 445 through an arithmetic progression. It has the following syntax: 446 > 447 stat ::= for Name = exp , exp [ , exp ] do block end 448 < 449 The `block` is repeated for `name` starting at the value of the first `exp`, until 450 it passes the second `exp` by steps of the third `exp`. More precisely, 451 a `for` statement like 452 453 `for var = e1, e2, e3 do block end` 454 455 is equivalent to the code: >lua 456 457 do 458 local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) 459 if not ( var and limit and step ) then error() end 460 while ( step >0 and var <= limit ) 461 or ( step <=0 and var >= limit ) do 462 block 463 var = var + step 464 end 465 end 466 < 467 468 Note the following: 469 470 - All three control expressions are evaluated only once, before the loop 471 starts. They must all result in numbers. 472 - `var`, `limit` and `step` are invisible variables. The names are here for 473 explanatory purposes only. 474 - If the third expression (the step) is absent, then a step of 1 is used. 475 - You can use `break` to exit a `for` loop. 476 - The loop variable `var` is local to the loop; you cannot use its value 477 after the `for` ends or is broken. If you need this value, assign it to 478 another variable before breaking or exiting the loop. 479 480 *for-in* 481 The generic `for` statement works over functions, called |iterator|s. On each 482 iteration, the iterator function is called to produce a new value, stopping 483 when this new value is `nil`. The generic `for` loop has the following syntax: 484 > 485 stat ::= for namelist in explist1 do block end 486 namelist ::= Name { , Name } 487 < 488 A `for` statement like 489 490 `for` `var1, ..., varn` `in` `explist` `do` `block` `end` 491 492 is equivalent to the code: >lua 493 494 do 495 local f, s, var = explist 496 while true do 497 local var1, ..., varn = f(s, var) 498 var = var1 499 if var == nil then break end 500 block 501 end 502 end 503 < 504 Note the following: 505 506 - `explist` is evaluated only once. Its results are an iterator function, 507 a `state`, and an initial value for the first iterator variable. 508 - `f`, `s`, and `var` are invisible variables. The names are here for 509 explanatory purposes only. 510 - You can use `break` to exit a `for` loop. 511 - The loop variables `var1, ..., varn` are local to the loop; you cannot use 512 their values after the `for` ends. If you need these values, then assign 513 them to other variables before breaking or exiting the loop. 514 515 ------------------------------------------------------------------------------ 516 2.4.6 Function Calls as Statements *lua-funcstatement* 517 518 To allow possible side-effects, function calls can be executed as statements: 519 > 520 stat ::= functioncall 521 < 522 In this case, all returned values are thrown away. Function calls are 523 explained in |lua-function|. 524 525 ------------------------------------------------------------------------------ 526 2.4.7 Local Declarations *lua-local* 527 528 Local variables may be declared anywhere inside a block. The declaration may 529 include an initial assignment: 530 > 531 stat ::= local namelist [ = explist1 ] 532 namelist ::= Name { , Name } 533 < 534 If present, an initial assignment has the same semantics of a multiple 535 assignment (see |lua-assign|). Otherwise, all variables are initialized 536 with `nil`. 537 538 A chunk is also a block (see |lua-chunk|), and so local variables can be 539 declared in a chunk outside any explicit block. The scope of such local 540 variables extends until the end of the chunk. 541 542 The visibility rules for local variables are explained in |lua-visibility|. 543 544 ============================================================================== 545 2.5 Expressions *lua-expressions* 546 547 The basic expressions in Lua are the following: 548 > 549 exp ::= prefixexp 550 exp ::= nil | false | true 551 exp ::= Number 552 exp ::= String 553 exp ::= function 554 exp ::= tableconstructor 555 exp ::= ... 556 exp ::= exp binop exp 557 exp ::= unop exp 558 prefixexp ::= var | functioncall | ( exp ) 559 < 560 Numbers and literal strings are explained in |lua-lexical|; variables are 561 explained in |lua-variables|; function definitions are explained in 562 |lua-function-define|; function calls are explained in |lua-function|; 563 table constructors are explained in |lua-tableconstructor|. Vararg expressions, 564 denoted by three dots (`...`), can only be used inside vararg functions; 565 they are explained in |lua-function-define|. 566 567 Binary operators comprise arithmetic operators (see |lua-arithmetic|), 568 relational operators (see |lua-relational|), logical operators (see 569 |lua-logicalop|), and the concatenation operator (see |lua-concat|). 570 Unary operators comprise the unary minus (see |lua-arithmetic|), the unary 571 `not` (see |lua-logicalop|), and the unary length operator (see |lua-length|). 572 573 Both function calls and vararg expressions may result in multiple values. If 574 the expression is used as a statement (see |lua-funcstatement|) 575 (only possible for function calls), then its return list is adjusted to zero 576 elements, thus discarding all returned values. If the expression is used as 577 the last (or the only) element of a list of expressions, then no adjustment is 578 made (unless the call is enclosed in parentheses). In all other contexts, Lua 579 adjusts the result list to one element, discarding all values except the first 580 one. 581 582 Here are some examples: 583 >lua 584 f() -- adjusted to 0 results 585 g(f(), x) -- f() is adjusted to 1 result 586 g(x, f()) -- g gets x plus all results from f() 587 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) 588 a,b = ... -- a gets the first vararg parameter, b gets 589 -- the second (both a and b may get nil if there 590 -- is no corresponding vararg parameter) 591 592 a,b,c = x, f() -- f() is adjusted to 2 results 593 a,b,c = f() -- f() is adjusted to 3 results 594 return f() -- returns all results from f() 595 return ... -- returns all received vararg parameters 596 return x,y,f() -- returns x, y, and all results from f() 597 {f()} -- creates a list with all results from f() 598 {...} -- creates a list with all vararg parameters 599 {f(), nil} -- f() is adjusted to 1 result 600 < 601 An expression enclosed in parentheses always results in only one value. Thus, 602 `(f(x,y,z))` is always a single value, even if `f` returns several values. 603 (The value of `(f(x,y,z))` is the first value returned by `f` or `nil` if `f` does not 604 return any values.) 605 606 ------------------------------------------------------------------------------ 607 2.5.1 Arithmetic Operators *lua-arithmetic* 608 609 Lua supports the usual arithmetic operators: the binary `+` (addition), 610 `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulo) 611 and `^` (exponentiation); and unary `-` (negation). If the operands are numbers, 612 or strings that can be converted to numbers (see |lua-coercion|), then all 613 operations have the usual meaning. Exponentiation works for any exponent. For 614 instance, `x^(-0.5)` computes the inverse of the square root of `x`. Modulo is 615 defined as 616 >lua 617 a % b == a - math.floor(a/b)*b 618 < 619 That is, it is the remainder of a division that rounds the quotient towards 620 minus infinity. 621 622 ------------------------------------------------------------------------------ 623 2.5.2 Relational Operators *lua-relational* 624 625 The relational operators in Lua are 626 > 627 == ~= < > <= >= 628 < 629 These operators always result in `false` or `true`. 630 631 Equality (`==`) first compares the type of its operands. If the types are 632 different, then the result is `false`. Otherwise, the values of the operands 633 are compared. Numbers and strings are compared in the usual way. Objects 634 (tables, userdata, threads, and functions) are compared by reference: two 635 objects are considered equal only if they are the same object. Every time you 636 create a new object (a table, userdata, or function), this new object is 637 different from any previously existing object. 638 639 You can change the way that Lua compares tables and userdata using the "eq" 640 metamethod (see |lua-metatable|). 641 642 The conversion rules of coercion |lua-coercion| do not apply to 643 equality comparisons. Thus, `"0"==0` evaluates to `false`, and `t[0]` and 644 `t["0"]` denote different entries in a table. 645 646 The operator `~=` is exactly the negation of equality (`==`). 647 648 The order operators work as follows. If both arguments are numbers, then they 649 are compared as such. Otherwise, if both arguments are strings, then their 650 values are compared according to the current locale. Otherwise, Lua tries to 651 call the "lt" or the "le" metamethod (see |lua-metatable|). 652 653 ------------------------------------------------------------------------------ 654 2.5.3 Logical Operators *lua-logicalop* 655 656 The logical operators in Lua are 657 > 658 and or not 659 < 660 Like the control structures (see |lua-control|), all logical operators 661 consider both `false` and `nil` as false and anything else as true. 662 663 *lua-not* *lua-and* *lua-or* 664 The negation operator `not` always returns `false` or `true`. The conjunction 665 operator `and` returns its first argument if this value is `false` or `nil`; 666 otherwise, `and` returns its second argument. The disjunction 667 operator `or` returns its first argument if this value is different 668 from `nil` and `false`; otherwise, `or` returns its second argument. 669 Both `and` and `or` use short-cut evaluation, that is, the second operand is 670 evaluated only if necessary. Here are some examples: 671 > 672 10 or 20 --> 10 673 10 or error() --> 10 674 nil or "a" --> "a" 675 nil and 10 --> nil 676 false and error() --> false 677 false and nil --> false 678 false or nil --> nil 679 10 and 20 --> 20 680 < 681 (In this manual, `-->` indicates the result of the preceding expression.) 682 683 ------------------------------------------------------------------------------ 684 2.5.4 Concatenation *lua-concat* 685 686 The string concatenation operator in Lua is denoted by two dots (`..`). 687 If both operands are strings or numbers, then they are converted to strings 688 according to the rules mentioned in |lua-coercion|. Otherwise, the 689 "concat" metamethod is called (see |lua-metatable|). 690 691 ------------------------------------------------------------------------------ 692 2.5.5 The Length Operator *lua-#* *lua-length* 693 694 The length operator is denoted by the unary operator `#`. The length of a 695 string is its number of bytes (that is, the usual meaning of string length 696 when each character is one byte). 697 698 The length of a table `t` is defined to be any integer index `n` such that `t[n]` is 699 not `nil` and `t[n+1]` is `nil`; moreover, if `t[1]` is `nil`, `n` may be zero. For a 700 regular array, with non-nil values from 1 to a given `n`, its length is exactly 701 that `n`, the index of its last value. If the array has "holes" (that 702 is, `nil` values between other non-nil values), then `#t` may be any of the 703 indices that directly precedes a `nil` value (that is, it may consider any 704 such `nil` value as the end of the array). 705 706 ------------------------------------------------------------------------------ 707 2.5.6 Precedence *lua-precedence* 708 709 Operator precedence in Lua follows the table below, from lower to higher 710 priority: 711 > 712 or 713 and 714 < > <= >= ~= == 715 .. 716 + - 717 * / 718 not # - (unary) 719 ^ 720 < 721 As usual, you can use parentheses to change the precedences in an expression. 722 The concatenation (`..`) and exponentiation (`^`) operators are right 723 associative. All other binary operators are left associative. 724 725 ------------------------------------------------------------------------------ 726 2.5.7 Table Constructors *lua-tableconstructor* 727 728 Table constructors are expressions that create tables. Every time a 729 constructor is evaluated, a new table is created. Constructors can be used to 730 create empty tables, or to create a table and initialize some of its fields. 731 The general syntax for constructors is 732 > 733 tableconstructor ::= { [ fieldlist ] } 734 fieldlist ::= field { fieldsep field } [ fieldsep ] 735 field ::= [ exp ] = exp | Name = exp | exp 736 fieldsep ::= , | ; 737 < 738 Each field of the form `[exp1] = exp2` adds to the new table an entry with 739 key `exp1` and value `exp2`. A field of the form `name = exp` is equivalent to 740 `["name"] = exp`. Finally, fields of the form `exp` are equivalent to 741 `[i] = exp`, where `i` are consecutive numerical integers, starting with 1. 742 Fields in the other formats do not affect this counting. For example, 743 >lua 744 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } 745 < 746 is equivalent to 747 >lua 748 do 749 local t = {} 750 t[f(1)] = g 751 t[1] = "x" -- 1st exp 752 t[2] = "y" -- 2nd exp 753 t.x = 1 -- temp["x"] = 1 754 t[3] = f(x) -- 3rd exp 755 t[30] = 23 756 t[4] = 45 -- 4th exp 757 a = t 758 end 759 < 760 If the last field in the list has the form `exp` and the expression is a 761 function call, then all values returned by the call enter the list 762 consecutively (see |lua-function|). To avoid this, enclose the function 763 call in parentheses (see |lua-expressions|). 764 765 The field list may have an optional trailing separator, as a convenience for 766 machine-generated code. 767 768 ------------------------------------------------------------------------------ 769 2.5.8 Function Calls *lua-function* 770 771 A function call in Lua has the following syntax: 772 > 773 functioncall ::= prefixexp args 774 < 775 In a function call, first `prefixexp` and `args` are evaluated. If the value 776 of `prefixexp` has type `function`, then this function is called with the given 777 arguments. Otherwise, the `prefixexp` "call" metamethod is called, having as 778 first parameter the value of `prefixexp`, followed by the original call 779 arguments (see |lua-metatable|). 780 781 The form 782 > 783 functioncall ::= prefixexp : Name args 784 < 785 can be used to call "methods". A call `v:name(` `args` `)` is syntactic sugar 786 for `v.name(v,` `args` `)`, except that `v` is evaluated only once. 787 788 Arguments have the following syntax: 789 > 790 args ::= ( [ explist1 ] ) 791 args ::= tableconstructor 792 args ::= String 793 < 794 All argument expressions are evaluated before the call. A call of the 795 form `f{` `fields` `}` is syntactic sugar for `f({` `fields` `})`, that is, the 796 argument list is a single new table. A call of the form `f'` `string` `'` 797 (or `f"` `string` `"` or `f[[` `string` `]]`) is syntactic sugar for 798 `f('` `string` `')`, that is, the argument list is a single literal string. 799 800 As an exception to the free-format syntax of Lua, you cannot put a line break 801 before the `(` in a function call. This restriction avoids some ambiguities 802 in the language. If you write 803 >lua 804 a = f 805 (g).x(a) 806 < 807 Lua would see that as a single statement, `a = f(g).x(a)`. So, if you want two 808 statements, you must add a semi-colon between them. If you actually want to 809 call `f`, you must remove the line break before `(g)`. 810 811 *lua-tailcall* 812 A call of the form `return` `functioncall` is called a tail call. Lua 813 implements proper tail calls (or proper tail recursion): in a tail call, the 814 called function reuses the stack entry of the calling function. Therefore, 815 there is no limit on the number of nested tail calls that a program can 816 execute. However, a tail call erases any debug information about the calling 817 function. Note that a tail call only happens with a particular syntax, where 818 the `return` has one single function call as argument; this syntax makes the 819 calling function return exactly the returns of the called function. So, none 820 of the following examples are tail calls: 821 >lua 822 return (f(x)) -- results adjusted to 1 823 return 2 * f(x) 824 return x, f(x) -- additional results 825 f(x); return -- results discarded 826 return x or f(x) -- results adjusted to 1 827 < 828 829 ------------------------------------------------------------------------------ 830 2.5.9 Function Definitions *lua-function-define* 831 832 The syntax for function definition is 833 > 834 function ::= function funcbody 835 funcbody ::= ( [ parlist1 ] ) block end 836 < 837 The following syntactic sugar simplifies function definitions: 838 > 839 stat ::= function funcname funcbody 840 stat ::= local function Name funcbody 841 funcname ::= Name { . Name } [ : Name ] 842 < 843 The statement 844 845 `function f ()` `body` `end` 846 847 translates to 848 849 `f = function ()` `body` `end` 850 851 The statement 852 853 `function t.a.b.c.f ()` `body` `end` 854 855 translates to 856 857 `t.a.b.c.f = function ()` `body` `end` 858 859 The statement 860 861 `local function f ()` `body` `end` 862 863 translates to 864 865 `local f; f = function f ()` `body` `end` 866 867 not to 868 869 `local f = function f ()` `body` `end` 870 871 (This only makes a difference when the body of the function contains 872 references to `f`.) 873 874 *lua-closure* 875 A function definition is an executable expression, whose value has type 876 `function`. When Lua pre-compiles a chunk, all its function bodies are 877 pre-compiled too. Then, whenever Lua executes the function definition, the 878 function is instantiated (or closed). This function instance (or closure) is 879 the final value of the expression. Different instances of the same function 880 may refer to different external local variables and may have different 881 environment tables. 882 883 Parameters act as local variables that are initialized with the argument 884 values: 885 > 886 parlist1 ::= namelist [ , ... ] | ... 887 < 888 *lua-vararg* 889 When a function is called, the list of arguments is adjusted to the length of 890 the list of parameters, unless the function is a variadic or vararg function, 891 which is indicated by three dots (`...`) at the end of its parameter list. A 892 vararg function does not adjust its argument list; instead, it collects all 893 extra arguments and supplies them to the function through a vararg expression, 894 which is also written as three dots. The value of this expression is a list of 895 all actual extra arguments, similar to a function with multiple results. If a 896 vararg expression is used inside another expression or in the middle of a list 897 of expressions, then its return list is adjusted to one element. If the 898 expression is used as the last element of a list of expressions, then no 899 adjustment is made (unless the call is enclosed in parentheses). 900 901 As an example, consider the following definitions: 902 >lua 903 function f(a, b) end 904 function g(a, b, ...) end 905 function r() return 1,2,3 end 906 < 907 Then, we have the following mapping from arguments to parameters and to the 908 vararg expression: 909 > 910 CALL PARAMETERS 911 912 f(3) a=3, b=nil 913 f(3, 4) a=3, b=4 914 f(3, 4, 5) a=3, b=4 915 f(r(), 10) a=1, b=10 916 f(r()) a=1, b=2 917 918 g(3) a=3, b=nil, ... --> (nothing) 919 g(3, 4) a=3, b=4, ... --> (nothing) 920 g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 921 g(5, r()) a=5, b=1, ... --> 2 3 922 < 923 Results are returned using the `return` statement (see |lua-control|). 924 If control reaches the end of a function without encountering 925 a `return` statement, then the function returns with no results. 926 927 *lua-colonsyntax* 928 The colon syntax is used for defining methods, that is, functions that have an 929 implicit extra parameter `self`. Thus, the statement 930 931 `function t.a.b.c:f (` `params` `)` `body` `end` 932 933 is syntactic sugar for 934 935 `t.a.b.c:f = function (` `self`, `params` `)` `body` `end` 936 937 ============================================================================== 938 2.6 Visibility Rules *lua-visibility* 939 940 Lua is a lexically scoped language. The scope of variables begins at the first 941 statement after their declaration and lasts until the end of the innermost 942 block that includes the declaration. Consider the following example: 943 >lua 944 x = 10 -- global variable 945 do -- new block 946 local x = x -- new `x`, with value 10 947 print(x) --> 10 948 x = x+1 949 do -- another block 950 local x = x+1 -- another `x` 951 print(x) --> 12 952 end 953 print(x) --> 11 954 end 955 print(x) --> 10 (the global one) 956 < 957 Notice that, in a declaration like `local x = x`, the new `x` being declared is 958 not in scope yet, and so the second `x` refers to the outside variable. 959 960 *lua-upvalue* 961 Because of the lexical scoping rules, local variables can be freely accessed 962 by functions defined inside their scope. A local variable used by an inner 963 function is called an upvalue, or external local variable, inside the inner 964 function. 965 966 Notice that each execution of a local statement defines new local variables. 967 Consider the following example: 968 >lua 969 a = {} 970 local x = 20 971 for i=1,10 do 972 local y = 0 973 a[i] = function () y=y+1; return x+y end 974 end 975 < 976 The loop creates ten closures (that is, ten instances of the anonymous 977 function). Each of these closures uses a different `y` variable, while all of 978 them share the same `x`. 979 980 ============================================================================== 981 2.7 Error Handling *lua-errors* 982 983 Because Lua is an embedded extension language, all Lua actions start from 984 C code in the host program calling a function from the Lua library (see 985 |lua_pcall()|). Whenever an error occurs during Lua compilation or 986 execution, control returns to C, which can take appropriate measures (such as 987 print an error message). 988 989 Lua code can explicitly generate an error by calling the `error` function (see 990 |error()|). If you need to catch errors in Lua, you can use the `pcall` 991 function (see |pcall()|). 992 993 ============================================================================== 994 2.8 Metatables *metatable* *lua-metatable* 995 996 Every value in Lua may have a metatable. This metatable is an ordinary Lua 997 table that defines the behavior of the original table and userdata under 998 certain special operations. You can change several aspects of the behavior of 999 an object by setting specific fields in its metatable. For instance, when a 1000 non-numeric value is the operand of an addition, Lua checks for a function in 1001 the field `"__add"` in its metatable. If it finds one, Lua calls that function 1002 to perform the addition. 1003 1004 We call the keys in a metatable events and the values metamethods. In the 1005 previous example, the event is "add" and the metamethod is the function that 1006 performs the addition. 1007 1008 You can query the metatable of any value through the `getmetatable` function 1009 (see |getmetatable()|). 1010 1011 You can replace the metatable of tables through the `setmetatable` function (see 1012 |setmetatable()|). You cannot change the metatable of other types from Lua 1013 (except using the debug library); you must use the C API for that. 1014 1015 Tables and userdata have individual metatables (although multiple tables and 1016 userdata can share a same table as their metatable); values of all other types 1017 share one single metatable per type. So, there is one single metatable for all 1018 numbers, and for all strings, etc. 1019 1020 A metatable may control how an object behaves in arithmetic operations, order 1021 comparisons, concatenation, length operation, and indexing. A metatable can 1022 also define a function to be called when a userdata is garbage collected. For 1023 each of those operations Lua associates a specific key called an event. When 1024 Lua performs one of those operations over a value, it checks whether this 1025 value has a metatable with the corresponding event. If so, the value 1026 associated with that key (the metamethod) controls how Lua will perform the 1027 operation. 1028 1029 Metatables control the operations listed next. Each operation is identified by 1030 its corresponding name. The key for each operation is a string with its name 1031 prefixed by two underscores, `__`; for instance, the key for operation "add" 1032 is the string "__add". The semantics of these operations is better explained 1033 by a Lua function describing how the interpreter executes that operation. 1034 1035 The code shown here in Lua is only illustrative; the real behavior is hard 1036 coded in the interpreter and it is much more efficient than this simulation. 1037 All functions used in these descriptions (`rawget`, `tonumber`, etc.) are 1038 described in |lua-lib-core|. In particular, to retrieve the metamethod of a 1039 given object, we use the expression 1040 > 1041 metatable(obj)[event] 1042 < 1043 This should be read as 1044 >lua 1045 rawget(metatable(obj) or {}, event) 1046 < 1047 That is, the access to a metamethod does not invoke other metamethods, and the 1048 access to objects with no metatables does not fail (it simply results 1049 in `nil`). 1050 1051 "add": *__add()* 1052 ------ 1053 the `+` operation. 1054 1055 The function `getbinhandler` below defines how Lua chooses a handler for a 1056 binary operation. First, Lua tries the first operand. If its type does not 1057 define a handler for the operation, then Lua tries the second operand. 1058 >lua 1059 function getbinhandler (op1, op2, event) 1060 return metatable(op1)[event] or metatable(op2)[event] 1061 end 1062 < 1063 By using this function, the behavior of the `op1 + op2` is 1064 >lua 1065 function add_event (op1, op2) 1066 local o1, o2 = tonumber(op1), tonumber(op2) 1067 if o1 and o2 then -- both operands are numeric? 1068 return o1 + o2 -- `+` here is the primitive `add` 1069 else -- at least one of the operands is not numeric 1070 local h = getbinhandler(op1, op2, "__add") 1071 if h then 1072 -- call the handler with both operands 1073 return h(op1, op2) 1074 else -- no handler available: default behavior 1075 error(...) 1076 end 1077 end 1078 end 1079 < 1080 "sub": *__sub()* 1081 ------ 1082 the `-` operation. Behavior similar to the "add" operation. 1083 1084 "mul": *__mul()* 1085 ------ 1086 the `*` operation. Behavior similar to the "add" operation. 1087 1088 "div": *__div()* 1089 ------ 1090 the `/` operation. Behavior similar to the "add" operation. 1091 1092 "mod": *__mod()* 1093 ------ 1094 the `%` operation. Behavior similar to the "add" operation, with the 1095 operation `o1 - floor(o1/o2)*o2` as the primitive operation. 1096 1097 "pow": *__pow()* 1098 ------ 1099 the `^` (exponentiation) operation. Behavior similar to the "add" operation, 1100 with the function `pow` (from the C math library) as the primitive operation. 1101 1102 "unm": *__unm()* 1103 ------ 1104 the unary `-` operation. 1105 >lua 1106 function unm_event (op) 1107 local o = tonumber(op) 1108 if o then -- operand is numeric? 1109 return -o -- `-` here is the primitive `unm` 1110 else -- the operand is not numeric. 1111 -- Try to get a handler from the operand 1112 local h = metatable(op).__unm 1113 if h then 1114 -- call the handler with the operand 1115 return h(op) 1116 else -- no handler available: default behavior 1117 error(...) 1118 end 1119 end 1120 end 1121 < 1122 "concat": *__concat()* 1123 --------- 1124 the `..` (concatenation) operation. 1125 >lua 1126 function concat_event (op1, op2) 1127 if (type(op1) == "string" or type(op1) == "number") and 1128 (type(op2) == "string" or type(op2) == "number") then 1129 return op1 .. op2 -- primitive string concatenation 1130 else 1131 local h = getbinhandler(op1, op2, "__concat") 1132 if h then 1133 return h(op1, op2) 1134 else 1135 error(...) 1136 end 1137 end 1138 end 1139 < 1140 "len": *__len()* 1141 ------ 1142 the `#` operation. 1143 >lua 1144 function len_event (op) 1145 if type(op) == "string" then 1146 return strlen(op) -- primitive string length 1147 elseif type(op) == "table" then 1148 return #op -- primitive table length 1149 else 1150 local h = metatable(op).__len 1151 if h then 1152 -- call the handler with the operand 1153 return h(op) 1154 else -- no handler available: default behavior 1155 error(...) 1156 end 1157 end 1158 end 1159 < 1160 "eq": *__eq()* 1161 ----- 1162 the `==` operation. 1163 1164 The function `getcomphandler` defines how Lua chooses a metamethod for 1165 comparison operators. A metamethod only is selected when both objects being 1166 compared have the same type and the same metamethod for the selected 1167 operation. 1168 >lua 1169 function getcomphandler (op1, op2, event) 1170 if type(op1) ~= type(op2) then return nil end 1171 local mm1 = metatable(op1)[event] 1172 local mm2 = metatable(op2)[event] 1173 if mm1 == mm2 then return mm1 else return nil end 1174 end 1175 < 1176 The "eq" event is defined as follows: 1177 >lua 1178 function eq_event (op1, op2) 1179 if type(op1) ~= type(op2) then -- different types? 1180 return false -- different objects 1181 end 1182 if op1 == op2 then -- primitive equal? 1183 return true -- objects are equal 1184 end 1185 -- try metamethod 1186 local h = getcomphandler(op1, op2, "__eq") 1187 if h then 1188 return h(op1, op2) 1189 else 1190 return false 1191 end 1192 end 1193 < 1194 `a ~= b` is equivalent to `not (a == b)`. 1195 1196 "lt": *__lt()* 1197 ----- 1198 the `<` operation. 1199 >lua 1200 function lt_event (op1, op2) 1201 if type(op1) == "number" and type(op2) == "number" then 1202 return op1 < op2 -- numeric comparison 1203 elseif type(op1) == "string" and type(op2) == "string" then 1204 return op1 < op2 -- lexicographic comparison 1205 else 1206 local h = getcomphandler(op1, op2, "__lt") 1207 if h then 1208 return h(op1, op2) 1209 else 1210 error(...); 1211 end 1212 end 1213 end 1214 < 1215 `a > b` is equivalent to `b < a`. 1216 1217 "le": *__le()* 1218 ----- 1219 the `<=` operation. 1220 >lua 1221 function le_event (op1, op2) 1222 if type(op1) == "number" and type(op2) == "number" then 1223 return op1 <= op2 -- numeric comparison 1224 elseif type(op1) == "string" and type(op2) == "string" then 1225 return op1 <= op2 -- lexicographic comparison 1226 else 1227 local h = getcomphandler(op1, op2, "__le") 1228 if h then 1229 return h(op1, op2) 1230 else 1231 h = getcomphandler(op1, op2, "__lt") 1232 if h then 1233 return not h(op2, op1) 1234 else 1235 error(...); 1236 end 1237 end 1238 end 1239 end 1240 < 1241 `a >= b` is equivalent to `b <= a`. Note that, in the absence of a "le" 1242 metamethod, Lua tries the "lt", assuming that `a <= b` is equivalent 1243 to `not (b < a)`. 1244 1245 "index": *__index()* 1246 -------- 1247 The indexing access `table[key]`. 1248 >lua 1249 function gettable_event (table, key) 1250 local h 1251 if type(table) == "table" then 1252 local v = rawget(table, key) 1253 if v ~= nil then return v end 1254 h = metatable(table).__index 1255 if h == nil then return nil end 1256 else 1257 h = metatable(table).__index 1258 if h == nil then 1259 error(...); 1260 end 1261 end 1262 if type(h) == "function" then 1263 return h(table, key) -- call the handler 1264 else return h[key] -- or repeat operation on it 1265 end 1266 < 1267 "newindex": *__newindex()* 1268 ----------- 1269 The indexing assignment `table[key] = value`. 1270 >lua 1271 function settable_event (table, key, value) 1272 local h 1273 if type(table) == "table" then 1274 local v = rawget(table, key) 1275 if v ~= nil then rawset(table, key, value); return end 1276 h = metatable(table).__newindex 1277 if h == nil then rawset(table, key, value); return end 1278 else 1279 h = metatable(table).__newindex 1280 if h == nil then 1281 error(...); 1282 end 1283 end 1284 if type(h) == "function" then 1285 return h(table, key,value) -- call the handler 1286 else h[key] = value -- or repeat operation on it 1287 end 1288 < 1289 "call": *__call()* 1290 ------- 1291 called when Lua calls a value. 1292 >lua 1293 function function_event (func, ...) 1294 if type(func) == "function" then 1295 return func(...) -- primitive call 1296 else 1297 local h = metatable(func).__call 1298 if h then 1299 return h(func, ...) 1300 else 1301 error(...) 1302 end 1303 end 1304 end 1305 < 1306 1307 ============================================================================== 1308 2.9 Environments *lua-environments* 1309 1310 Besides metatables, objects of types thread, function, and userdata have 1311 another table associated with them, called their environment. Like metatables, 1312 environments are regular tables and multiple objects can share the same 1313 environment. 1314 1315 Environments associated with userdata have no meaning for Lua. It is only a 1316 convenience feature for programmers to associate a table to a userdata. 1317 1318 Environments associated with threads are called global environments. They are 1319 used as the default environment for their threads and non-nested functions 1320 created by the thread (through |loadfile()|, |loadstring()| or |load()|) and 1321 can be directly accessed by C code (see |lua-pseudoindex|). 1322 1323 Environments associated with C functions can be directly accessed by C code 1324 (see |lua-pseudoindex|). They are used as the default environment for 1325 other C functions created by the function. 1326 1327 Environments associated with Lua functions are used to resolve all accesses to 1328 global variables within the function (see |lua-variables|). They are 1329 used as the default environment for other Lua functions created by the 1330 function. 1331 1332 You can change the environment of a Lua function or the running thread by 1333 calling `setfenv`. You can get the environment of a Lua function or the 1334 running thread by calling `getfenv` (see |lua_getfenv()|). To manipulate the 1335 environment of other objects (userdata, C functions, other threads) you must 1336 use the C API. 1337 1338 ============================================================================== 1339 2.10 Garbage Collection *lua-gc* 1340 1341 Lua performs automatic memory management. This means that you do not have to 1342 worry neither about allocating memory for new objects nor about freeing it 1343 when the objects are no longer needed. Lua manages memory automatically by 1344 running a garbage collector from time to time to collect all dead objects 1345 (that is, these objects that are no longer accessible from Lua). All objects 1346 in Lua are subject to automatic management: tables, userdata, functions, 1347 threads, and strings. 1348 1349 Lua implements an incremental mark-and-sweep collector. It uses two numbers to 1350 control its garbage-collection cycles: the garbage-collector pause and the 1351 garbage-collector step multiplier. 1352 1353 The garbage-collector pause controls how long the collector waits before 1354 starting a new cycle. Larger values make the collector less aggressive. Values 1355 smaller than 1 mean the collector will not wait to start a new cycle. A value 1356 of 2 means that the collector waits for the total memory in use to double 1357 before starting a new cycle. 1358 1359 The step multiplier controls the relative speed of the collector relative to 1360 memory allocation. Larger values make the collector more aggressive but also 1361 increase the size of each incremental step. Values smaller than 1 make the 1362 collector too slow and may result in the collector never finishing a cycle. 1363 The default, 2, means that the collector runs at "twice" the speed of memory 1364 allocation. 1365 1366 You can change these numbers by calling `lua_gc` (see |lua_gc()|) in C or 1367 `collectgarbage` (see |collectgarbage()|) in Lua. Both get percentage points 1368 as arguments (so an argument of 100 means a real value of 1). With these 1369 functions you can also control the collector directly (e.g., stop and restart 1370 it). 1371 1372 ------------------------------------------------------------------------------ 1373 2.10.1 Garbage-Collection Metamethods *lua-gc-meta* 1374 1375 Using the C API, you can set garbage-collector metamethods for userdata (see 1376 |lua-metatable|). These metamethods are also called finalizers. 1377 Finalizers allow you to coordinate Lua's garbage collection with external 1378 resource management (such as closing files, network or database connections, 1379 or freeing your own memory). 1380 1381 *__gc* 1382 Garbage userdata with a field `__gc` in their metatables are not collected 1383 immediately by the garbage collector. Instead, Lua puts them in a list. After 1384 the collection, Lua does the equivalent of the following function for each 1385 userdata in that list: 1386 >lua 1387 function gc_event (udata) 1388 local h = metatable(udata).__gc 1389 if h then 1390 h(udata) 1391 end 1392 end 1393 < 1394 At the end of each garbage-collection cycle, the finalizers for userdata are 1395 called in reverse order of their creation, among these collected in that 1396 cycle. That is, the first finalizer to be called is the one associated with 1397 the userdata created last in the program. 1398 1399 ------------------------------------------------------------------------------ 1400 2.10.2 - Weak Tables *lua-weaktable* 1401 1402 A weak table is a table whose elements are weak references. A weak reference 1403 is ignored by the garbage collector. In other words, if the only references to 1404 an object are weak references, then the garbage collector will collect this 1405 object. 1406 1407 *__mode* 1408 A weak table can have weak keys, weak values, or both. A table with weak keys 1409 allows the collection of its keys, but prevents the collection of its values. 1410 A table with both weak keys and weak values allows the collection of both keys 1411 and values. In any case, if either the key or the value is collected, the 1412 whole pair is removed from the table. The weakness of a table is controlled by 1413 the value of the `__mode` field of its metatable. If the `__mode` field is a 1414 string containing the character `k`, the keys in the table are weak. 1415 If `__mode` contains `v`, the values in the table are weak. 1416 1417 After you use a table as a metatable, you should not change the value of its 1418 field `__mode`. Otherwise, the weak behavior of the tables controlled by this 1419 metatable is undefined. 1420 1421 ============================================================================== 1422 2.11 Coroutines *lua-coroutine* 1423 1424 Lua supports coroutines, also called collaborative multithreading. A coroutine 1425 in Lua represents an independent thread of execution. Unlike threads in 1426 multithread systems, however, a coroutine only suspends its execution by 1427 explicitly calling a yield function. 1428 1429 You create a coroutine with a call to `coroutine.create` (see 1430 |coroutine.create()|). Its sole argument is a function that is the main 1431 function of the coroutine. The `create` function only creates a new coroutine 1432 and returns a handle to it (an object of type `thread`); it does not start the 1433 coroutine execution. 1434 1435 When you first call `coroutine.resume` (see |coroutine.resume()|), 1436 passing as its first argument the thread returned by `coroutine.create`, the 1437 coroutine starts its execution, at the first line of its main function. Extra 1438 arguments passed to `coroutine.resume` are passed on to the coroutine main 1439 function. After the coroutine starts running, it runs until it terminates or 1440 `yields`. 1441 1442 A coroutine can terminate its execution in two ways: normally, when its main 1443 function returns (explicitly or implicitly, after the last instruction); and 1444 abnormally, if there is an unprotected error. In the first case, 1445 `coroutine.resume` returns `true`, plus any values returned by the coroutine 1446 main function. In case of errors, `coroutine.resume` returns `false` plus an 1447 error message. 1448 1449 A coroutine yields by calling `coroutine.yield` (see 1450 |coroutine.yield()|). When a coroutine yields, the corresponding 1451 `coroutine.resume` returns immediately, even if the yield happens inside 1452 nested function calls (that is, not in the main function, but in a function 1453 directly or indirectly called by the main function). In the case of a yield, 1454 `coroutine.resume` also returns `true`, plus any values passed to 1455 `coroutine.yield`. The next time you resume the same coroutine, it continues 1456 its execution from the point where it yielded, with the call to 1457 `coroutine.yield` returning any extra arguments passed to `coroutine.resume`. 1458 1459 Like `coroutine.create`, the `coroutine.wrap` function (see 1460 |coroutine.wrap()|) also creates a coroutine, but instead of returning 1461 the coroutine itself, it returns a function that, when called, resumes the 1462 coroutine. Any arguments passed to this function go as extra arguments to 1463 `coroutine.resume`. `coroutine.wrap` returns all the values returned by 1464 `coroutine.resume`, except the first one (the boolean error code). Unlike 1465 `coroutine.resume`, `coroutine.wrap` does not catch errors; any error is 1466 propagated to the caller. 1467 1468 As an example, consider the next code: 1469 >lua 1470 function foo1 (a) 1471 print("foo", a) 1472 return coroutine.yield(2*a) 1473 end 1474 1475 co = coroutine.create(function (a,b) 1476 print("co-body", a, b) 1477 local r = foo1(a+1) 1478 print("co-body", r) 1479 local r, s = coroutine.yield(a+b, a-b) 1480 print("co-body", r, s) 1481 return b, "end" 1482 end) 1483 1484 print("main", coroutine.resume(co, 1, 10)) 1485 print("main", coroutine.resume(co, "r")) 1486 print("main", coroutine.resume(co, "x", "y")) 1487 print("main", coroutine.resume(co, "x", "y")) 1488 < 1489 When you run it, it produces the following output: 1490 > 1491 co-body 1 10 1492 foo 2 1493 main true 4 1494 co-body r 1495 main true 11 -9 1496 co-body x y 1497 main true 10 end 1498 main false cannot resume dead coroutine 1499 < 1500 1501 ============================================================================== 1502 3 THE APPLICATION PROGRAM INTERFACE *lua-API* 1503 1504 This section describes the C API for Lua, that is, the set of C functions 1505 available to the host program to communicate with Lua. All API functions and 1506 related types and constants are declared in the header file `lua.h`. 1507 1508 Even when we use the term "function", any facility in the API may be provided 1509 as a `macro` instead. All such macros use each of its arguments exactly once 1510 (except for the first argument, which is always a Lua state), and so do not 1511 generate hidden side-effects. 1512 1513 As in most C libraries, the Lua API functions do not check their arguments for 1514 validity or consistency. However, you can change this behavior by compiling 1515 Lua with a proper definition for the macro `luai_apicheck`,in file 1516 `luaconf.h`. 1517 1518 ============================================================================== 1519 3.1 The Stack *lua-stack* *lua-apiStack* 1520 1521 Lua uses a virtual stack to pass values to and from C. Each element in this 1522 stack represents a Lua value (`nil`, number, string, etc.). 1523 1524 Whenever Lua calls C, the called function gets a new stack, which is 1525 independent of previous stacks and of stacks of C functions that are still 1526 active. This stack initially contains any arguments to the C function and it 1527 is where the C function pushes its results to be returned to the caller (see 1528 |lua_CFunction|). 1529 1530 *lua-stackindex* 1531 For convenience, most query operations in the API do not follow a strict stack 1532 discipline. Instead, they can refer to any element in the stack by using an 1533 index: a positive index represents an absolute stack position (starting at 1); 1534 a negative index represents an offset from the top of the stack. More 1535 specifically, if the stack has `n` elements, then index 1 represents the first 1536 element (that is, the element that was pushed onto the stack first) and index 1537 `n` represents the last element; index `-1` also represents the last element 1538 (that is, the element at the top) and index `-n` represents the first element. 1539 We say that an index is valid if it lies between 1 and the stack top (that is, 1540 if `1 <= abs(index) <= top`). 1541 1542 ============================================================================== 1543 3.2 Stack Size *lua-apiStackSize* 1544 1545 When you interact with Lua API, you are responsible for ensuring consistency. 1546 In particular, you are responsible for controlling stack overflow. You can 1547 use the function `lua_checkstack` to grow the stack size (see 1548 |lua_checkstack()|). 1549 1550 Whenever Lua calls C, it ensures that at least `LUA_MINSTACK` stack positions 1551 are available. `LUA_MINSTACK` is defined as 20, so that usually you do not 1552 have to worry about stack space unless your code has loops pushing elements 1553 onto the stack. 1554 1555 Most query functions accept as indices any value inside the available stack 1556 space, that is, indices up to the maximum stack size you have set through 1557 `lua_checkstack`. Such indices are called acceptable indices. More formally, 1558 we define an acceptable index as follows: 1559 >lua 1560 (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) 1561 < 1562 Note that 0 is never an acceptable index. 1563 1564 ============================================================================== 1565 3.3 Pseudo-Indices *lua-pseudoindex* 1566 1567 Unless otherwise noted, any function that accepts valid indices can also be 1568 called with pseudo-indices, which represent some Lua values that are 1569 accessible to the C code but which are not in the stack. Pseudo-indices are 1570 used to access the thread environment, the function environment, the registry, 1571 and the upvalues of a C function (see |lua-cclosure|). 1572 1573 The thread environment (where global variables live) is always at pseudo-index 1574 `LUA_GLOBALSINDEX`. The environment of the running C function is always at 1575 pseudo-index `LUA_ENVIRONINDEX`. 1576 1577 To access and change the value of global variables, you can use regular table 1578 operations over an environment table. For instance, to access the value of a 1579 global variable, do 1580 >c 1581 lua_getfield(L, LUA_GLOBALSINDEX, varname); 1582 < 1583 1584 ============================================================================== 1585 3.4 C Closures *lua-cclosure* 1586 1587 When a C function is created, it is possible to associate some values with it, 1588 thus creating a C closure; these values are called upvalues and are accessible 1589 to the function whenever it is called (see |lua_pushcclosure()|). 1590 1591 Whenever a C function is called, its upvalues are located at specific 1592 pseudo-indices. These pseudo-indices are produced by the macro 1593 `lua_upvalueindex`. The first value associated with a function is at position 1594 `lua_upvalueindex(1)`, and so on. Any access to `lua_upvalueindex(` `n` `)`, 1595 where `n` is greater than the number of upvalues of the current function, 1596 produces an acceptable (but invalid) index. 1597 1598 ============================================================================== 1599 3.5 Registry *lua-registry* 1600 1601 Lua provides a registry, a pre-defined table that can be used by any C code to 1602 store whatever Lua value it needs to store. This table is always located at 1603 pseudo-index `LUA_REGISTRYINDEX`. Any C library can store data into this 1604 table, but it should take care to choose keys different from those used by 1605 other libraries, to avoid collisions. Typically, you should use as key a 1606 string containing your library name or a light userdata with the address of a 1607 C object in your code. 1608 1609 The integer keys in the registry are used by the reference mechanism, 1610 implemented by the auxiliary library, and therefore should not be used for 1611 other purposes. 1612 1613 ============================================================================== 1614 3.6 Error Handling in C *lua-apiError* 1615 1616 Internally, Lua uses the C `longjmp` facility to handle errors. (You can also 1617 choose to use exceptions if you use C++; see file `luaconf.h`.) When Lua faces 1618 any error (such as memory allocation errors, type errors, syntax errors, and 1619 runtime errors) it raises an error; that is, it does a long jump. A protected 1620 environment uses `setjmp` to set a recover point; any error jumps to the most 1621 recent active recover point. 1622 1623 Almost any function in the API may raise an error, for instance due to a 1624 memory allocation error. The following functions run in protected mode (that 1625 is, they create a protected environment to run), so they never raise an error: 1626 `lua_newstate`, `lua_close`, `lua_load`, `lua_pcall`, and `lua_cpcall` (see 1627 |lua_newstate()|, |lua_close()|, |lua_load()|, 1628 |lua_pcall()|, and |lua_cpcall()|). 1629 1630 Inside a C function you can raise an error by calling `lua_error` (see 1631 |lua_error()|). 1632 1633 ============================================================================== 1634 3.7 Functions and Types *lua-apiFunctions* 1635 1636 Here we list all functions and types from the C API in alphabetical order. 1637 1638 lua_Alloc *lua_Alloc* 1639 >c 1640 typedef void * (*lua_Alloc) (void *ud, 1641 void *ptr, 1642 size_t osize, 1643 size_t nsize); 1644 < 1645 The type of the memory-allocation function used by Lua states. The 1646 allocator function must provide a functionality similar to `realloc`, 1647 but not exactly the same. Its arguments are `ud`, an opaque pointer 1648 passed to `lua_newstate` (see |lua_newstate()|); `ptr`, a pointer 1649 to the block being allocated/reallocated/freed; `osize`, the original 1650 size of the block; `nsize`, the new size of the block. `ptr` is `NULL` 1651 if and only if `osize` is zero. When `nsize` is zero, the allocator 1652 must return `NULL`; if `osize` is not zero, it should free the block 1653 pointed to by `ptr`. When `nsize` is not zero, the allocator returns 1654 `NULL` if and only if it cannot fill the request. When `nsize` is not 1655 zero and `osize` is zero, the allocator should behave like `malloc`. 1656 When `nsize` and `osize` are not zero, the allocator behaves like 1657 `realloc`. Lua assumes that the allocator never fails when 1658 `osize >= nsize`. 1659 1660 Here is a simple implementation for the allocator function. It is used 1661 in the auxiliary library by `luaL_newstate` (see 1662 |luaL_newstate()|). 1663 >c 1664 static void *l_alloc (void *ud, void *ptr, size_t osize, 1665 size_t nsize) { 1666 (void)ud; (void)osize; /* not used */ 1667 if (nsize == 0) { 1668 free(ptr); 1669 return NULL; 1670 } 1671 else 1672 return realloc(ptr, nsize); 1673 } 1674 < 1675 This code assumes that `free(NULL)` has no effect and that 1676 `realloc(NULL, size)` is equivalent to `malloc(size)`. ANSI C ensures both 1677 behaviors. 1678 1679 lua_atpanic *lua_atpanic()* 1680 >c 1681 lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); 1682 < 1683 Sets a new panic function and returns the old one. 1684 1685 If an error happens outside any protected environment, Lua calls a 1686 `panic` `function` and then calls `exit(EXIT_FAILURE)`, thus exiting 1687 the host application. Your panic function may avoid this exit by never 1688 returning (e.g., doing a long jump). 1689 1690 The panic function can access the error message at the top of the 1691 stack. 1692 1693 lua_call *lua_call()* 1694 >c 1695 void lua_call (lua_State *L, int nargs, int nresults); 1696 < 1697 Calls a function. 1698 1699 To call a function you must use the following protocol: first, the 1700 function to be called is pushed onto the stack; then, the arguments to 1701 the function are pushed in direct order; that is, the first argument 1702 is pushed first. Finally you call `lua_call`; `nargs` is the number of 1703 arguments that you pushed onto the stack. All arguments and the 1704 function value are popped from the stack when the function is called. 1705 The function results are pushed onto the stack when the function 1706 returns. The number of results is adjusted to `nresults`, unless 1707 `nresults` is `LUA_MULTRET`. In this case, `all` results from the 1708 function are pushed. Lua takes care that the returned values fit into 1709 the stack space. The function results are pushed onto the stack in 1710 direct order (the first result is pushed first), so that after the 1711 call the last result is on the top of the stack. 1712 1713 Any error inside the called function is propagated upwards (with a 1714 `longjmp`). 1715 1716 The following example shows how the host program may do the equivalent 1717 to this Lua code: 1718 >lua 1719 a = f("how", t.x, 14) 1720 < 1721 Here it is in C: 1722 >c 1723 lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called 1724 lua_pushstring(L, "how"); // 1st argument 1725 lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed 1726 lua_getfield(L, -1, "x"); // push result of t.x (2nd arg) 1727 lua_remove(L, -2); // remove 't' from the stack 1728 lua_pushinteger(L, 14); // 3rd argument 1729 lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result 1730 lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a' 1731 < 1732 Note that the code above is "balanced": at its end, the stack is back 1733 to its original configuration. This is considered good programming 1734 practice. 1735 1736 lua_CFunction *lua-cfunction* *lua_CFunction* 1737 >c 1738 typedef int (*lua_CFunction) (lua_State *L); 1739 < 1740 Type for C functions. 1741 1742 In order to communicate properly with Lua, a C function must use the 1743 following protocol, which defines the way parameters and results are 1744 passed: a C function receives its arguments from Lua in its stack in 1745 direct order (the first argument is pushed first). So, when the 1746 function starts, `lua_gettop(L)` (see |lua_gettop()|) returns the 1747 number of arguments received by the function. The first argument (if 1748 any) is at index 1 and its last argument is at index `lua_gettop(L)`. 1749 To return values to Lua, a C function just pushes them onto the stack, 1750 in direct order (the first result is pushed first), and returns the 1751 number of results. Any other value in the stack below the results will 1752 be properly discarded by Lua. Like a Lua function, a C function called 1753 by Lua can also return many results. 1754 1755 *lua-cfunctionexample* 1756 As an example, the following function receives a variable number of 1757 numerical arguments and returns their average and sum: 1758 >c 1759 static int foo (lua_State *L) { 1760 int n = lua_gettop(L); /* number of arguments */ 1761 lua_Number sum = 0; 1762 int i; 1763 for (i = 1; i <= n; i++) { 1764 if (!lua_isnumber(L, i)) { 1765 lua_pushstring(L, "incorrect argument"); 1766 lua_error(L); 1767 } 1768 sum += lua_tonumber(L, i); 1769 } 1770 lua_pushnumber(L, sum/n); /* first result */ 1771 lua_pushnumber(L, sum); /* second result */ 1772 return 2; /* number of results */ 1773 } 1774 < 1775 1776 lua_checkstack *lua_checkstack()* 1777 >c 1778 int lua_checkstack (lua_State *L, int extra); 1779 < 1780 Ensures that there are at least `extra` free stack slots in the stack. 1781 It returns false if it cannot grow the stack to that size. This 1782 function never shrinks the stack; if the stack is already larger than 1783 the new size, it is left unchanged. 1784 1785 lua_close *lua_close()* 1786 >c 1787 void lua_close (lua_State *L); 1788 < 1789 Destroys all objects in the given Lua state (calling the corresponding 1790 garbage-collection metamethods, if any) and frees all dynamic memory 1791 used by this state. On several platforms, you may not need to call 1792 this function, because all resources are naturally released when the 1793 host program ends. On the other hand, long-running programs, such as a 1794 daemon or a web server, might need to release states as soon as they 1795 are not needed, to avoid growing too large. 1796 1797 lua_concat *lua_concat()* 1798 >c 1799 void lua_concat (lua_State *L, int n); 1800 < 1801 Concatenates the `n` values at the top of the stack, pops them, and 1802 leaves the result at the top. If `n` is 1, the result is the single 1803 string on the stack (that is, the function does nothing); if `n` is 0, 1804 the result is the empty string. Concatenation is done following the 1805 usual semantics of Lua (see |lua-concat|). 1806 1807 lua_cpcall *lua_cpcall()* 1808 >c 1809 int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); 1810 < 1811 Calls the C function `func` in protected mode. `func` starts with only 1812 one element in its stack, a light userdata containing `ud`. In case of 1813 errors, `lua_cpcall` returns the same error codes as `lua_pcall` (see 1814 |lua_pcall()|), plus the error object on the top of the stack; 1815 otherwise, it returns zero, and does not change the stack. All values 1816 returned by `func` are discarded. 1817 1818 lua_createtable *lua_createtable()* 1819 >c 1820 void lua_createtable (lua_State *L, int narr, int nrec); 1821 < 1822 Creates a new empty table and pushes it onto the stack. The new table 1823 has space pre-allocated for `narr` array elements and `nrec` non-array 1824 elements. This pre-allocation is useful when you know exactly how many 1825 elements the table will have. Otherwise you can use the function 1826 `lua_newtable` (see |lua_newtable()|). 1827 1828 lua_dump *lua_dump()* 1829 >c 1830 int lua_dump (lua_State *L, lua_Writer writer, void *data); 1831 < 1832 Dumps a function as a binary chunk. Receives a Lua function on the top 1833 of the stack and produces a binary chunk that, if loaded again, 1834 results in a function equivalent to the one dumped. As it produces 1835 parts of the chunk, `lua_dump` calls function `writer` (see 1836 |lua_Writer|) with the given `data` to write them. 1837 1838 The value returned is the error code returned by the last call to the 1839 writer; 0 means no errors. 1840 1841 This function does not pop the Lua function from the stack. 1842 1843 lua_equal *lua_equal()* 1844 >c 1845 int lua_equal (lua_State *L, int index1, int index2); 1846 < 1847 Returns 1 if the two values in acceptable indices `index1` and 1848 `index2` are equal, following the semantics of the Lua `==` operator 1849 (that is, may call metamethods). Otherwise returns 0. Also returns 0 1850 if any of the indices is non valid. 1851 1852 lua_error *lua_error()* 1853 >c 1854 int lua_error (lua_State *L); 1855 < 1856 Generates a Lua error. The error message (which can actually be a Lua 1857 value of any type) must be on the stack top. This function does a long 1858 jump, and therefore never returns (see |luaL_error()|). 1859 1860 lua_gc *lua_gc()* 1861 >c 1862 int lua_gc (lua_State *L, int what, int data); 1863 < 1864 Controls the garbage collector. 1865 1866 This function performs several tasks, according to the value of the 1867 parameter `what`: 1868 1869 - `LUA_GCSTOP` stops the garbage collector. 1870 - `LUA_GCRESTART` restarts the garbage collector. 1871 - `LUA_GCCOLLECT` performs a full garbage-collection cycle. 1872 - `LUA_GCCOUNT` returns the current amount of memory (in Kbytes) in 1873 use by Lua. 1874 - `LUA_GCCOUNTB` returns the remainder of dividing the current 1875 amount of bytes of memory in use by Lua by 1024. 1876 - `LUA_GCSTEP` performs an incremental step of garbage collection. 1877 The step "size" is controlled by `data` (larger 1878 values mean more steps) in a non-specified way. If 1879 you want to control the step size you must 1880 experimentally tune the value of `data`. The 1881 function returns 1 if the step finished a 1882 garbage-collection cycle. 1883 - `LUA_GCSETPAUSE` sets `data` /100 as the new value for the 1884 `pause` of the collector (see |lua-gc|). 1885 The function returns the previous value of the 1886 pause. 1887 - `LUA_GCSETSTEPMUL`sets `data` /100 as the new value for the 1888 `step` `multiplier` of the collector (see 1889 |lua-gc|). The function returns the 1890 previous value of the step multiplier. 1891 1892 lua_getallocf *lua_getallocf()* 1893 >c 1894 lua_Alloc lua_getallocf (lua_State *L, void **ud); 1895 < 1896 Returns the memory-allocation function of a given state. If `ud` is 1897 not `NULL`, Lua stores in `*ud` the opaque pointer passed to 1898 `lua_newstate` (see |lua_newstate()|). 1899 1900 lua_getfenv *lua_getfenv()* 1901 >c 1902 void lua_getfenv (lua_State *L, int index); 1903 < 1904 Pushes onto the stack the environment table of the value at the given 1905 index. 1906 1907 lua_getfield *lua_getfield()* 1908 >c 1909 void lua_getfield (lua_State *L, int index, const char *k); 1910 < 1911 Pushes onto the stack the value `t[k]`, where `t` is the value at the 1912 given valid index `index`. As in Lua, this function may trigger a 1913 metamethod for the "index" event (see |lua-metatable|). 1914 1915 lua_getglobal *lua_getglobal()* 1916 >c 1917 void lua_getglobal (lua_State *L, const char *name); 1918 < 1919 Pushes onto the stack the value of the global `name`. It is defined as 1920 a macro: 1921 >c 1922 #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) 1923 < 1924 1925 lua_getmetatable *lua_getmetatable()* 1926 >c 1927 int lua_getmetatable (lua_State *L, int index); 1928 < 1929 Pushes onto the stack the metatable of the value at the given 1930 acceptable index. If the index is not valid, or if the value does not 1931 have a metatable, the function returns 0 and pushes nothing on the 1932 stack. 1933 1934 lua_gettable *lua_gettable()* 1935 >c 1936 void lua_gettable (lua_State *L, int index); 1937 < 1938 Pushes onto the stack the value `t[k]`, where `t` is the value at the 1939 given valid index `index` and `k` is the value at the top of the 1940 stack. 1941 1942 This function pops the key from the stack (putting the resulting value 1943 in its place). As in Lua, this function may trigger a metamethod for 1944 the "index" event (see |lua-metatable|). 1945 1946 lua_gettop *lua_gettop()* 1947 >c 1948 int lua_gettop (lua_State *L); 1949 < 1950 Returns the index of the top element in the stack. Because indices 1951 start at 1, this result is equal to the number of elements in the 1952 stack (and so 1953 0 means an empty stack). 1954 1955 lua_insert *lua_insert()* 1956 >c 1957 void lua_insert (lua_State *L, int index); 1958 < 1959 Moves the top element into the given valid index, shifting up the 1960 elements above this index to open space. Cannot be called with a 1961 pseudo-index, because a pseudo-index is not an actual stack position. 1962 1963 lua_Integer *lua_Integer* 1964 >c 1965 typedef ptrdiff_t lua_Integer; 1966 < 1967 The type used by the Lua API to represent integral values. 1968 1969 By default it is a `ptrdiff_t`, which is usually the largest integral 1970 type the machine handles "comfortably". 1971 1972 lua_isboolean *lua_isboolean()* 1973 >c 1974 int lua_isboolean (lua_State *L, int index); 1975 < 1976 Returns 1 if the value at the given acceptable index has type boolean, 1977 and 0 otherwise. 1978 1979 lua_iscfunction *lua_iscfunction()* 1980 >c 1981 int lua_iscfunction (lua_State *L, int index); 1982 < 1983 Returns 1 if the value at the given acceptable index is a C function, 1984 and 0 otherwise. 1985 1986 lua_isfunction *lua_isfunction()* 1987 >c 1988 int lua_isfunction (lua_State *L, int index); 1989 < 1990 Returns 1 if the value at the given acceptable index is a function 1991 (either C or Lua), and 0 otherwise. 1992 1993 lua_islightuserdata *lua_islightuserdata()* 1994 >c 1995 int lua_islightuserdata (lua_State *L, int index); 1996 < 1997 Returns 1 if the value at the given acceptable index is a light 1998 userdata, and 0 otherwise. 1999 2000 lua_isnil *lua_isnil()* 2001 >c 2002 int lua_isnil (lua_State *L, int index); 2003 < 2004 Returns 1 if the value at the given acceptable index is `nil`, and 0 2005 otherwise. 2006 2007 lua_isnumber *lua_isnumber()* 2008 >c 2009 int lua_isnumber (lua_State *L, int index); 2010 < 2011 Returns 1 if the value at the given acceptable index is a number or a 2012 string convertible to a number, and 0 otherwise. 2013 2014 lua_isstring *lua_isstring()* 2015 >c 2016 int lua_isstring (lua_State *L, int index); 2017 < 2018 Returns 1 if the value at the given acceptable index is a string or a 2019 number (which is always convertible to a string), and 0 otherwise. 2020 2021 lua_istable *lua_istable()* 2022 >c 2023 int lua_istable (lua_State *L, int index); 2024 < 2025 Returns 1 if the value at the given acceptable index is a table, and 2026 0 otherwise. 2027 2028 lua_isthread *lua_isthread()* 2029 >c 2030 int lua_isthread (lua_State *L, int index); 2031 < 2032 Returns 1 if the value at the given acceptable index is a thread, and 2033 0 otherwise. 2034 2035 lua_isuserdata *lua_isuserdata()* 2036 >c 2037 int lua_isuserdata (lua_State *L, int index); 2038 < 2039 Returns 1 if the value at the given acceptable index is a userdata 2040 (either full or light), and 0 otherwise. 2041 2042 lua_lessthan *lua_lessthan()* 2043 >c 2044 int lua_lessthan (lua_State *L, int index1, int index2); 2045 < 2046 Returns 1 if the value at acceptable index `index1` is smaller than 2047 the value at acceptable index `index2`, following the semantics of the 2048 Lua `<` operator (that is, may call metamethods). Otherwise returns 0. 2049 Also returns 0 if any of the indices is non valid. 2050 2051 lua_load *lua_load()* 2052 >c 2053 int lua_load (lua_State *L, 2054 lua_Reader reader, 2055 void *data, 2056 const char *chunkname); 2057 < 2058 Loads a Lua chunk. If there are no errors, `lua_load` pushes the 2059 compiled chunk as a Lua function on top of the stack. Otherwise, it 2060 pushes an error message. The return values of `lua_load` are: 2061 2062 - `0`: no errors; 2063 - `LUA_ERRSYNTAX` : syntax error during pre-compilation; 2064 - `LUA_ERRMEM` : memory allocation error. 2065 2066 This function only loads a chunk; it does not run it. 2067 2068 `lua_load` automatically detects whether the chunk is text or binary, 2069 and loads it accordingly (see program `luac`). 2070 2071 The `lua_load` function uses a user-supplied `reader` function to read 2072 the chunk (see |lua_Reader|). The `data` argument is an opaque 2073 value passed to the reader function. 2074 2075 The `chunkname` argument gives a name to the chunk, which is used for 2076 error messages and in debug information (see |lua-apiDebug|). 2077 2078 lua_newstate *lua_newstate()* 2079 >c 2080 lua_State *lua_newstate (lua_Alloc f, void *ud); 2081 < 2082 Creates a new, independent state. Returns `NULL` if cannot create the 2083 state (due to lack of memory). The argument `f` is the allocator 2084 function; Lua does all memory allocation for this state through this 2085 function. The second argument, `ud`, is an opaque pointer that Lua 2086 simply passes to the allocator in every call. 2087 2088 lua_newtable *lua_newtable()* 2089 >c 2090 void lua_newtable (lua_State *L); 2091 < 2092 Creates a new empty table and pushes it onto the stack. It is 2093 equivalent to `lua_createtable(L, 0, 0)` (see 2094 |lua_createtable()|). 2095 2096 lua_newthread *lua_newthread()* 2097 >c 2098 lua_State *lua_newthread (lua_State *L); 2099 < 2100 Creates a new thread, pushes it on the stack, and returns a pointer to 2101 a `lua_State` (see |lua_State|) that represents this new 2102 thread. The new state returned by this function shares with the 2103 original state all global objects (such as tables), but has an 2104 independent execution stack. 2105 2106 There is no explicit function to close or to destroy a thread. Threads 2107 are subject to garbage collection, like any Lua object. 2108 2109 lua_newuserdata *lua_newuserdata()* 2110 >c 2111 void *lua_newuserdata (lua_State *L, size_t size); 2112 < 2113 This function allocates a new block of memory with the given size, 2114 pushes onto the stack a new full userdata with the block address, and 2115 returns this address. 2116 *userdata* 2117 Userdata represents C values in Lua. A full userdata represents a 2118 block of memory. It is an object (like a table): you must create it, 2119 it can have its own metatable, and you can detect when it is being 2120 collected. A full userdata is only equal to itself (under raw 2121 equality). 2122 2123 When Lua collects a full userdata with a `gc` metamethod, Lua calls 2124 the metamethod and marks the userdata as finalized. When this userdata 2125 is collected again then Lua frees its corresponding memory. 2126 2127 lua_next *lua_next()* 2128 >c 2129 int lua_next (lua_State *L, int index); 2130 < 2131 Pops a key from the stack, and pushes a key-value pair from the table 2132 at the given index (the "next" pair after the given key). If there are 2133 no more elements in the table, then `lua_next` returns 0 (and pushes 2134 nothing). 2135 2136 *lua-tabletraversal* 2137 A typical traversal looks like this: 2138 >c 2139 /* table is in the stack at index 't' */ 2140 lua_pushnil(L); /* first key */ 2141 while (lua_next(L, t) != 0) { 2142 /* uses 'key' (at index -2) and 'value' (at index -1) */ 2143 printf("%s - %s\n", 2144 lua_typename(L, lua_type(L, -2)), 2145 lua_typename(L, lua_type(L, -1))); 2146 /* removes 'value'; keeps 'key' for next iteration */ 2147 lua_pop(L, 1); 2148 } 2149 < 2150 While traversing a table, do not call `lua_tolstring` (see 2151 |lua_tolstring()|) directly on a key, unless you know that the 2152 key is actually a string. Recall that `lua_tolstring` `changes` the 2153 value at the given index; this confuses the next call to `lua_next`. 2154 2155 lua_Number *lua_Number* 2156 >c 2157 typedef double lua_Number; 2158 < 2159 The type of numbers in Lua. By default, it is double, but that can be 2160 changed in `luaconf.h`. 2161 2162 Through the configuration file you can change Lua to operate with 2163 another type for numbers (e.g., float or long). 2164 2165 lua_objlen *lua_objlen()* 2166 >c 2167 size_t lua_objlen (lua_State *L, int index); 2168 < 2169 Returns the "length" of the value at the given acceptable index: for 2170 strings, this is the string length; for tables, this is the result of 2171 the length operator (`#`); for userdata, this is the size of the 2172 block of memory allocated for the userdata; for other values, it is 0. 2173 2174 lua_pcall *lua_pcall()* 2175 >c 2176 lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); 2177 < 2178 Calls a function in protected mode. 2179 2180 Both `nargs` and `nresults` have the same meaning as in `lua_call` 2181 (see |lua_call()|). If there are no errors during the call, 2182 `lua_pcall` behaves exactly like `lua_call`. However, if there is any 2183 error, `lua_pcall` catches it, pushes a single value on the stack (the 2184 error message), and returns an error code. Like `lua_call`, 2185 `lua_pcall` always removes the function and its arguments from the 2186 stack. 2187 2188 If `errfunc` is 0, then the error message returned on the stack is 2189 exactly the original error message. Otherwise, `errfunc` is the stack 2190 index of an `error` `handler function`. (In the current 2191 implementation, this index cannot be a pseudo-index.) In case of 2192 runtime errors, this function will be called with the error message 2193 and its return value will be the message returned on the stack by 2194 `lua_pcall`. 2195 2196 Typically, the error handler function is used to add more debug 2197 information to the error message, such as a stack traceback. Such 2198 information cannot be gathered after the return of `lua_pcall`, since 2199 by then the stack has unwound. 2200 2201 The `lua_pcall` function returns 0 in case of success or one of the 2202 following error codes (defined in `lua.h`): 2203 2204 - `LUA_ERRRUN` a runtime error. 2205 - `LUA_ERRMEM` memory allocation error. For such errors, Lua does 2206 not call the error handler function. 2207 - `LUA_ERRERR` error while running the error handler function. 2208 2209 lua_pop *lua_pop()* 2210 >c 2211 void lua_pop (lua_State *L, int n); 2212 < 2213 Pops `n` elements from the stack. 2214 2215 lua_pushboolean *lua_pushboolean()* 2216 >c 2217 void lua_pushboolean (lua_State *L, int b); 2218 < 2219 Pushes a boolean value with value `b` onto the stack. 2220 2221 lua_pushcclosure *lua_pushcclosure()* 2222 >c 2223 void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); 2224 < 2225 Pushes a new C closure onto the stack. 2226 2227 When a C function is created, it is possible to associate some values 2228 with it, thus creating a C closure (see |lua-cclosure|); these 2229 values are then accessible to the function whenever it is called. To 2230 associate values with a C function, first these values should be 2231 pushed onto the stack (when there are multiple values, the first value 2232 is pushed first). Then `lua_pushcclosure` is called to create and push 2233 the C function onto the stack, with the argument `n` telling how many 2234 values should be associated with the function. `lua_pushcclosure` also 2235 pops these values from the stack. 2236 2237 lua_pushcfunction *lua_pushcfunction()* 2238 >c 2239 void lua_pushcfunction (lua_State *L, lua_CFunction f); 2240 < 2241 Pushes a C function onto the stack. This function receives a pointer 2242 to a C function and pushes onto the stack a Lua value of type 2243 `function` that, when called, invokes the corresponding C function. 2244 2245 Any function to be registered in Lua must follow the correct protocol 2246 to receive its parameters and return its results (see 2247 |lua_CFunction|). 2248 2249 `lua_pushcfunction` is defined as a macro: 2250 >c 2251 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0) 2252 < 2253 2254 lua_pushfstring *lua_pushfstring()* 2255 >c 2256 const char *lua_pushfstring (lua_State *L, const char *fmt, ...); 2257 < 2258 Pushes onto the stack a formatted string and returns a pointer to this 2259 string. It is similar to the C function `sprintf`, but has some 2260 important differences: 2261 2262 - You do not have to allocate space for the result: the result is a 2263 Lua string and Lua takes care of memory allocation (and 2264 deallocation, through garbage collection). 2265 - The conversion specifiers are quite restricted. There are no flags, 2266 widths, or precisions. The conversion specifiers can only be `%%` 2267 (inserts a `%` in the string), `%s` (inserts a zero-terminated 2268 string, with no size restrictions), `%f` (inserts a 2269 `lua_Number`), `%p` (inserts a pointer as a hexadecimal numeral), 2270 `%d` (inserts an `int`), and `%c` (inserts an `int` as a 2271 character). 2272 2273 lua_pushinteger *lua_pushinteger()* 2274 >c 2275 void lua_pushinteger (lua_State *L, lua_Integer n); 2276 < 2277 Pushes a number with value `n` onto the stack. 2278 2279 lua_pushlightuserdata *lua_pushlightuserdata()* 2280 >c 2281 void lua_pushlightuserdata (lua_State *L, void *p); 2282 < 2283 Pushes a light userdata onto the stack. 2284 *lua-lightuserdata* 2285 Userdata represents C values in Lua. A light userdata represents a 2286 pointer. It is a value (like a number): you do not create it, it has 2287 no individual metatable, and it is not collected (as it was never 2288 created). A light userdata is equal to "any" light userdata with the 2289 same C address. 2290 2291 lua_pushlstring *lua_pushlstring()* 2292 >c 2293 void lua_pushlstring (lua_State *L, const char *s, size_t len); 2294 < 2295 Pushes the string pointed to by `s` with size `len` onto the stack. 2296 Lua makes (or reuses) an internal copy of the given string, so the 2297 memory at `s` can be freed or reused immediately after the function 2298 returns. The string can contain embedded zeros. 2299 2300 lua_pushnil *lua_pushnil()* 2301 >c 2302 void lua_pushnil (lua_State *L); 2303 < 2304 Pushes a nil value onto the stack. 2305 2306 lua_pushnumber *lua_pushnumber()* 2307 >c 2308 void lua_pushnumber (lua_State *L, lua_Number n); 2309 < 2310 Pushes a number with value `n` onto the stack. 2311 2312 lua_pushstring *lua_pushstring()* 2313 >c 2314 void lua_pushstring (lua_State *L, const char *s); 2315 < 2316 Pushes the zero-terminated string pointed to by `s` onto the stack. 2317 Lua makes (or reuses) an internal copy of the given string, so the 2318 memory at `s` can be freed or reused immediately after the function 2319 returns. The string cannot contain embedded zeros; it is assumed to 2320 end at the first zero. 2321 2322 lua_pushthread *lua_pushthread()* 2323 >c 2324 int lua_pushthread (lua_State *L); 2325 < 2326 Pushes the thread represented by `L` onto the stack. Returns 1 if this 2327 thread is the main thread of its state. 2328 2329 lua_pushvalue *lua_pushvalue()* 2330 >c 2331 void lua_pushvalue (lua_State *L, int index); 2332 < 2333 Pushes a copy of the element at the given valid index onto the stack. 2334 2335 lua_pushvfstring *lua_pushvfstring()* 2336 >c 2337 const char *lua_pushvfstring (lua_State *L, 2338 const char *fmt, 2339 va_list argp); 2340 < 2341 Equivalent to `lua_pushfstring` (see |lua_pushfstring()|), except 2342 that it receives a `va_list` instead of a variable number of 2343 arguments. 2344 2345 lua_rawequal *lua_rawequal()* 2346 >c 2347 int lua_rawequal (lua_State *L, int index1, int index2); 2348 < 2349 Returns 1 if the two values in acceptable indices `index1` and 2350 `index2` are primitively equal (that is, without calling metamethods). 2351 Otherwise returns 0. Also returns 0 if any of the indices are non 2352 valid. 2353 2354 lua_rawget *lua_rawget()* 2355 >c 2356 void lua_rawget (lua_State *L, int index); 2357 < 2358 Similar to `lua_gettable` (see |lua_gettable()|), but does a raw 2359 access (i.e., without metamethods). 2360 2361 lua_rawgeti *lua_rawgeti()* 2362 >c 2363 void lua_rawgeti (lua_State *L, int index, int n); 2364 < 2365 Pushes onto the stack the value `t[n]`, where `t` is the value at the 2366 given valid index `index`. The access is raw; that is, it does not 2367 invoke metamethods. 2368 2369 lua_rawset *lua_rawset()* 2370 >c 2371 void lua_rawset (lua_State *L, int index); 2372 < 2373 Similar to `lua_settable` (see |lua_settable()|), but does a raw 2374 assignment (i.e., without metamethods). 2375 2376 lua_rawseti *lua_rawseti()* 2377 >c 2378 void lua_rawseti (lua_State *L, int index, int n); 2379 < 2380 Does the equivalent of `t[n] = v`, where `t` is the value at the given 2381 valid index `index` and `v` is the value at the top of the stack. 2382 2383 This function pops the value from the stack. The assignment is raw; 2384 that is, it does not invoke metamethods. 2385 2386 lua_Reader *lua_Reader* 2387 >c 2388 typedef const char * (*lua_Reader) (lua_State *L, 2389 void *data, 2390 size_t *size); 2391 < 2392 The reader function used by `lua_load` (see |lua_load()|). Every 2393 time it needs another piece of the chunk, `lua_load` calls the reader, 2394 passing along its `data` parameter. The reader must return a pointer 2395 to a block of memory with a new piece of the chunk and set `size` to 2396 the block size. The block must exist until the reader function is 2397 called again. To signal the end of the chunk, the reader must return 2398 `NULL`. The reader function may return pieces of any size greater than 2399 zero. 2400 2401 lua_register *lua_register()* 2402 >c 2403 void lua_register (lua_State *L, 2404 const char *name, 2405 lua_CFunction f); 2406 < 2407 Sets the C function `f` as the new value of global `name`. It is 2408 defined as a macro: 2409 >c 2410 #define lua_register(L,n,f) \ 2411 (lua_pushcfunction(L, f), lua_setglobal(L, n)) 2412 < 2413 2414 lua_remove *lua_remove()* 2415 >c 2416 void lua_remove (lua_State *L, int index); 2417 < 2418 Removes the element at the given valid index, shifting down the 2419 elements above this index to fill the gap. Cannot be called with a 2420 pseudo-index, because a pseudo-index is not an actual stack position. 2421 2422 lua_replace *lua_replace()* 2423 >c 2424 void lua_replace (lua_State *L, int index); 2425 < 2426 Moves the top element into the given position (and pops it), without 2427 shifting any element (therefore replacing the value at the given 2428 position). 2429 2430 lua_resume *lua_resume()* 2431 >c 2432 int lua_resume (lua_State *L, int narg); 2433 < 2434 Starts and resumes a coroutine in a given thread. 2435 2436 To start a coroutine, you first create a new thread (see 2437 |lua_newthread()|); then you push onto its stack the main 2438 function plus any arguments; then you call `lua_resume` (see 2439 |lua_resume()|) with `narg` being the number of arguments. This 2440 call returns when the coroutine suspends or finishes its execution. 2441 When it returns, the stack contains all values passed to `lua_yield` 2442 (see |lua_yield()|), or all values returned by the body function. 2443 `lua_resume` returns `LUA_YIELD` if the coroutine yields, 0 if the 2444 coroutine finishes its execution without errors, or an error code in 2445 case of errors (see |lua_pcall()|). In case of errors, the stack 2446 is not unwound, so you can use the debug API over it. The error 2447 message is on the top of the stack. To restart a coroutine, you put on 2448 its stack only the values to be passed as results from `lua_yield`, 2449 and then call `lua_resume`. 2450 2451 lua_setallocf *lua_setallocf()* 2452 >c 2453 void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); 2454 < 2455 Changes the allocator function of a given state to `f` with user data 2456 `ud`. 2457 2458 lua_setfenv *lua_setfenv()* 2459 >c 2460 int lua_setfenv (lua_State *L, int index); 2461 < 2462 Pops a table from the stack and sets it as the new environment for the 2463 value at the given index. If the value at the given index is neither a 2464 function nor a thread nor a userdata, `lua_setfenv` returns 0. 2465 Otherwise it returns 1. 2466 2467 lua_setfield *lua_setfield()* 2468 >c 2469 void lua_setfield (lua_State *L, int index, const char *k); 2470 < 2471 Does the equivalent to `t[k] = v`, where `t` is the value at the given 2472 valid index `index` and `v` is the value at the top of the stack. 2473 2474 This function pops the value from the stack. As in Lua, this function 2475 may trigger a metamethod for the "newindex" event (see 2476 |lua-metatable|). 2477 2478 lua_setglobal *lua_setglobal()* 2479 >c 2480 void lua_setglobal (lua_State *L, const char *name); 2481 < 2482 Pops a value from the stack and sets it as the new value of global 2483 `name`. It is defined as a macro: 2484 >c 2485 #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) 2486 < 2487 2488 lua_setmetatable *lua_setmetatable()* 2489 >c 2490 int lua_setmetatable (lua_State *L, int index); 2491 < 2492 Pops a table from the stack and sets it as the new metatable for the 2493 value at the given acceptable index. 2494 2495 lua_settable *lua_settable()* 2496 >c 2497 void lua_settable (lua_State *L, int index); 2498 < 2499 Does the equivalent to `t[k] = v`, where `t` is the value at the given 2500 valid index `index`, `v` is the value at the top of the stack, and `k` 2501 is the value just below the top. 2502 2503 This function pops both the key and the value from the stack. As in 2504 Lua, this function may trigger a metamethod for the "newindex" event 2505 (see |lua-metatable|). 2506 2507 lua_settop *lua_settop()* 2508 >c 2509 void lua_settop (lua_State *L, int index); 2510 < 2511 Accepts any acceptable index, or 0, and sets the stack top to this 2512 index. If the new top is larger than the old one, then the new 2513 elements are filled with `nil`. If `index` is 0, then all stack 2514 elements are removed. 2515 2516 lua_State *lua_State* 2517 >c 2518 typedef struct lua_State lua_State; 2519 < 2520 Opaque structure that keeps the whole state of a Lua interpreter. The 2521 Lua library is fully reentrant: it has no global variables. All 2522 information about a state is kept in this structure. 2523 2524 A pointer to this state must be passed as the first argument to every 2525 function in the library, except to `lua_newstate` (see 2526 |lua_newstate()|), which creates a Lua state from scratch. 2527 2528 lua_status *lua_status()* 2529 >c 2530 int lua_status (lua_State *L); 2531 < 2532 Returns the status of the thread `L`. 2533 2534 The status can be 0 for a normal thread, an error code if the thread 2535 finished its execution with an error, or `LUA_YIELD` if the thread is 2536 suspended. 2537 2538 lua_toboolean *lua_toboolean()* 2539 >c 2540 int lua_toboolean (lua_State *L, int index); 2541 < 2542 Converts the Lua value at the given acceptable index to a C boolean 2543 value (0 or 1). Like all tests in Lua, `lua_toboolean` returns 1 for 2544 any Lua value different from `false` and `nil`; otherwise it returns 0. 2545 It also returns 0 when called with a non-valid index. (If you want to 2546 accept only actual boolean values, use `lua_isboolean` 2547 |lua_isboolean()| to test the value's type.) 2548 2549 lua_tocfunction *lua_tocfunction()* 2550 >c 2551 lua_CFunction lua_tocfunction (lua_State *L, int index); 2552 < 2553 Converts a value at the given acceptable index to a C function. That 2554 value must be a C function; otherwise it returns `NULL`. 2555 2556 lua_tointeger *lua_tointeger()* 2557 >c 2558 lua_Integer lua_tointeger (lua_State *L, int idx); 2559 < 2560 Converts the Lua value at the given acceptable index to the signed 2561 integral type `lua_Integer` (see |lua_Integer|). The Lua value 2562 must be a number or a string convertible to a number (see 2563 |lua-coercion|); otherwise, `lua_tointeger` returns 0. 2564 2565 If the number is not an integer, it is truncated in some non-specified 2566 way. 2567 2568 lua_tolstring *lua_tolstring()* 2569 >c 2570 const char *lua_tolstring (lua_State *L, int index, size_t *len); 2571 < 2572 Converts the Lua value at the given acceptable index to a C string. If 2573 `len` is not `NULL`, it also sets `*len` with the string length. The 2574 Lua value must be a string or a number; otherwise, the function 2575 returns `NULL`. If the value is a number, then `lua_tolstring` also 2576 `changes the actual value in the stack to a` `string`. (This change 2577 confuses `lua_next` |lua_next()| when `lua_tolstring` is applied 2578 to keys during a table traversal.) 2579 2580 `lua_tolstring` returns a fully aligned pointer to a string inside the 2581 Lua state. This string always has a zero (`\0`) after its last 2582 character (as in C), but may contain other zeros in its body. Because 2583 Lua has garbage collection, there is no guarantee that the pointer 2584 returned by `lua_tolstring` will be valid after the corresponding 2585 value is removed from the stack. 2586 2587 lua_tonumber *lua_tonumber()* 2588 >c 2589 lua_Number lua_tonumber (lua_State *L, int index); 2590 < 2591 Converts the Lua value at the given acceptable index to the C type 2592 `lua_Number` (see |lua_Number|). The Lua value must be a number 2593 or a string convertible to a number (see |lua-coercion|); 2594 otherwise, `lua_tonumber` returns 0. 2595 2596 lua_topointer *lua_topointer()* 2597 >c 2598 const void *lua_topointer (lua_State *L, int index); 2599 < 2600 Converts the value at the given acceptable index to a generic C 2601 pointer (`void*`). The value may be a userdata, a table, a thread, or 2602 a function; otherwise, `lua_topointer` returns `NULL`. Different 2603 objects will give different pointers. There is no way to convert the 2604 pointer back to its original value. 2605 2606 Typically this function is used only for debug information. 2607 2608 lua_tostring *lua_tostring()* 2609 >c 2610 const char *lua_tostring (lua_State *L, int index); 2611 < 2612 Equivalent to `lua_tolstring` (see |lua_tolstring()|) with `len` 2613 equal to `NULL`. 2614 2615 lua_tothread *lua_tothread()* 2616 >c 2617 lua_State *lua_tothread (lua_State *L, int index); 2618 < 2619 Converts the value at the given acceptable index to a Lua thread 2620 (represented as `lua_State*` |lua_State|). This value must be a 2621 thread; otherwise, the function returns `NULL`. 2622 2623 lua_touserdata *lua_touserdata()* 2624 >c 2625 void *lua_touserdata (lua_State *L, int index); 2626 < 2627 If the value at the given acceptable index is a full userdata, returns 2628 its block address. If the value is a light userdata, returns its 2629 pointer. Otherwise, it returns `NULL`. 2630 2631 lua_type *lua_type()* 2632 >c 2633 int lua_type (lua_State *L, int index); 2634 < 2635 Returns the type of the value in the given acceptable index, or 2636 `LUA_TNONE` for a non-valid index (that is, an index to an "empty" 2637 stack position). The types returned by `lua_type` are coded by the 2638 following constants defined in `lua.h` : `LUA_TNIL`, `LUA_TNUMBER`, 2639 `LUA_TBOOLEAN`, `LUA_TSTRING`, `LUA_TTABLE`, `LUA_TFUNCTION`, 2640 `LUA_TUSERDATA`, `LUA_TTHREAD`, and `LUA_TLIGHTUSERDATA`. 2641 2642 lua_typename *lua_typename()* 2643 >c 2644 const char *lua_typename (lua_State *L, int tp); 2645 < 2646 Returns the name of the type encoded by the value `tp`, which must be 2647 one the values returned by `lua_type`. 2648 2649 lua_Writer *lua_Writer* 2650 >c 2651 typedef int (*lua_Writer) (lua_State *L, 2652 const void* p, 2653 size_t sz, 2654 void* ud); 2655 < 2656 The writer function used by `lua_dump` (see |lua_dump()|). Every 2657 time it produces another piece of chunk, `lua_dump` calls the writer, 2658 passing along the buffer to be written (`p`), its size (`sz`), and the 2659 `data` parameter supplied to `lua_dump`. 2660 2661 The writer returns an error code: 0 means no errors; any other value 2662 means an error and stops `lua_dump` from calling the writer again. 2663 2664 lua_xmove *lua_xmove()* 2665 >c 2666 void lua_xmove (lua_State *from, lua_State *to, int n); 2667 < 2668 Exchange values between different threads of the `same` global state. 2669 2670 This function pops `n` values from the stack `from`, and pushes them 2671 onto the stack `to`. 2672 2673 lua_yield *lua_yield()* 2674 >c 2675 int lua_yield (lua_State *L, int nresults); 2676 < 2677 Yields a coroutine. 2678 2679 This function should only be called as the return expression of a C 2680 function, as follows: 2681 >c 2682 return lua_yield (L, nresults); 2683 < 2684 When a C function calls `lua_yield` in that way, the running coroutine 2685 suspends its execution, and the call to `lua_resume` (see 2686 |lua_resume()|) that started this coroutine returns. The 2687 parameter `nresults` is the number of values from the stack that are 2688 passed as results to `lua_resume`. 2689 2690 *lua-stackexample* 2691 As an example of stack manipulation, if the stack starts as 2692 `10 20 30 40 50*` (from bottom to top; the `*` marks the top), then 2693 > 2694 lua_pushvalue(L, 3) --> 10 20 30 40 50 30* 2695 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* 2696 lua_remove(L, -3) --> 10 20 30 40 30 30* 2697 lua_remove(L, 6) --> 10 20 30 40 30* 2698 lua_insert(L, 1) --> 30 10 20 30 40* 2699 lua_insert(L, -1) --> 30 10 20 30 40* (no effect) 2700 lua_replace(L, 2) --> 30 40 20 30* 2701 lua_settop(L, -3) --> 30 40* 2702 lua_settop(L, 6) --> 30 40 nil nil nil nil* 2703 < 2704 2705 ============================================================================== 2706 3.8 The Debug Interface *lua-apiDebug* 2707 2708 Lua has no built-in debugging facilities. Instead, it offers a special 2709 interface by means of functions and hooks. This interface allows the 2710 construction of different kinds of debuggers, profilers, and other tools that 2711 need "inside information" from the interpreter. 2712 2713 lua_Debug *lua_Debug* 2714 2715 >c 2716 typedef struct lua_Debug { 2717 int event; 2718 const char *name; /* (n) */ 2719 const char *namewhat; /* (n) */ 2720 const char *what; /* (S) */ 2721 const char *source; /* (S) */ 2722 int currentline; /* (l) */ 2723 int nups; /* (u) number of upvalues */ 2724 int linedefined; /* (S) */ 2725 int lastlinedefined; /* (S) */ 2726 char short_src[LUA_IDSIZE]; /* (S) */ 2727 /* private part */ 2728 other fields 2729 } lua_Debug; 2730 < 2731 2732 A structure used to carry different pieces of information about an active 2733 function. `lua_getstack` (see |lua_getstack()|) fills only the private part 2734 of this structure, for later use. To fill the other fields of `lua_Debug` with 2735 useful information, call `lua_getinfo` (see |lua_getinfo()|). 2736 2737 The fields of `lua_Debug` have the following meaning: 2738 2739 - `source` If the function was defined in a string, then `source` is 2740 that string. If the function was defined in a file, then 2741 `source` starts with a `@` followed by the file name. 2742 - `short_src` a "printable" version of `source`, to be used in error messages. 2743 - `linedefined` the line number where the definition of the function starts. 2744 - `lastlinedefined` the line number where the definition of the function ends. 2745 - `what` the string `"Lua"` if the function is a Lua function, 2746 `"C"` if it is a C function, `"main"` if it is the main 2747 part of a chunk, and `"tail"` if it was a function that 2748 did a tail call. In the latter case, Lua has no other 2749 information about the function. 2750 - `currentline` the current line where the given function is executing. 2751 When no line information is available, `currentline` is 2752 set to -1. 2753 - `name` a reasonable name for the given function. Because 2754 functions in Lua are first-class values, they do not have 2755 a fixed name: some functions may be the value of multiple 2756 global variables, while others may be stored only in a 2757 table field. The `lua_getinfo` function checks how the 2758 function was called to find a suitable name. If it cannot 2759 find a name, then `name` is set to `NULL`. 2760 - `namewhat` explains the `name` field. The value of `namewhat` can be 2761 `"global"`, `"local"`, `"method"`, `"field"`, 2762 `"upvalue"`, or `""` (the empty string), according to how 2763 the function was called. (Lua uses the empty string when 2764 no other option seems to apply.) `nups` the number of 2765 upvalues of the function. 2766 2767 lua_gethook *lua_gethook()* 2768 >c 2769 lua_Hook lua_gethook (lua_State *L); 2770 < 2771 Returns the current hook function. 2772 2773 lua_gethookcount *lua_gethookcount()* 2774 >c 2775 int lua_gethookcount (lua_State *L); 2776 < 2777 Returns the current hook count. 2778 2779 lua_gethookmask *lua_gethookmask()* 2780 >c 2781 int lua_gethookmask (lua_State *L); 2782 < 2783 Returns the current hook mask. 2784 2785 lua_getinfo *lua_getinfo()* 2786 >c 2787 int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); 2788 < 2789 Returns information about a specific function or function invocation. 2790 2791 To get information about a function invocation, the parameter `ar` 2792 must be a valid activation record that was filled by a previous call 2793 to `lua_getstack` (see |lua_getstack()|) or given as argument to 2794 a hook (see |lua_Hook|). 2795 2796 To get information about a function you push it onto the stack and 2797 start the `what` string with the character `>`. (In that case, 2798 `lua_getinfo` pops the function in the top of the stack.) For 2799 instance, to know in which line a function `f` was defined, you can 2800 write the following code: 2801 >c 2802 lua_Debug ar; 2803 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ 2804 lua_getinfo(L, ">S", &ar); 2805 printf("%d\n", ar.linedefined); 2806 < 2807 Each character in the string `what` selects some fields of the 2808 structure `ar` to be filled or a value to be pushed on the stack: 2809 2810 `'n'` fills in the field `name` and `namewhat` 2811 `'S'` fills in the fields `source`, `short_src`, `linedefined`, 2812 `lastlinedefined`, and `what` 2813 `'l'` fills in the field `currentline` 2814 `'u'` fills in the field `nups` 2815 `'f'` pushes onto the stack the function that is running at the 2816 given level 2817 `'L'` pushes onto the stack a table whose indices are the numbers 2818 of the lines that are valid on the function. (A `valid line` is a 2819 line with some associated code, that is, a line where you can put 2820 a break point. Non-valid lines include empty lines and comments.) 2821 2822 This function returns 0 on error (for instance, an invalid option in 2823 `what`). 2824 2825 lua_getlocal *lua_getlocal()* 2826 >c 2827 const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); 2828 < 2829 Gets information about a local variable of a given activation record. 2830 The parameter `ar` must be a valid activation record that was filled 2831 by a previous call to `lua_getstack` (see |lua_getstack()|) or 2832 given as argument to a hook (see |lua_Hook|). The index `n` 2833 selects which local variable to inspect (1 is the first parameter or 2834 active local variable, and so on, until the last active local 2835 variable). `lua_getlocal` pushes the variable's value onto the stack 2836 and returns its name. 2837 2838 Variable names starting with `(` (open parentheses) represent 2839 internal variables (loop control variables, temporaries, and C 2840 function locals). 2841 2842 Returns `NULL` (and pushes nothing) when the index is greater than the 2843 number of active local variables. 2844 2845 lua_getstack *lua_getstack()* 2846 >c 2847 int lua_getstack (lua_State *L, int level, lua_Debug *ar); 2848 < 2849 Gets information about the interpreter runtime stack. 2850 2851 This function fills parts of a `lua_Debug` (see |lua_Debug|) 2852 structure with an identification of the `activation record` of the 2853 function executing at a given level. Level 0 is the current running 2854 function, whereas level `n+1` is the function that has called level 2855 `n`. When there are no errors, `lua_getstack` returns 1; when called 2856 with a level greater than the stack depth, it returns 0. 2857 2858 lua_getupvalue *lua_getupvalue()* 2859 >c 2860 const char *lua_getupvalue (lua_State *L, int funcindex, int n); 2861 < 2862 Gets information about a closure's upvalue. (For Lua functions, 2863 upvalues are the external local variables that the function uses, and 2864 that are consequently included in its closure.) `lua_getupvalue` gets 2865 the index `n` of an upvalue, pushes the upvalue's value onto the 2866 stack, and returns its name. `funcindex` points to the closure in the 2867 stack. (Upvalues have no particular order, as they are active through 2868 the whole function. So, they are numbered in an arbitrary order.) 2869 2870 Returns `NULL` (and pushes nothing) when the index is greater than the 2871 number of upvalues. For C functions, this function uses the empty 2872 string `""` as a name for all upvalues. 2873 2874 lua_Hook *lua_Hook* 2875 >c 2876 typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); 2877 < 2878 Type for debugging hook functions. 2879 2880 Whenever a hook is called, its `ar` argument has its field `event` set 2881 to the specific event that triggered the hook. Lua identifies these 2882 events with the following constants: `LUA_HOOKCALL`, `LUA_HOOKRET`, 2883 `LUA_HOOKTAILRET`, `LUA_HOOKLINE`, and `LUA_HOOKCOUNT`. Moreover, for 2884 line events, the field `currentline` is also set. To get the value of 2885 any other field in `ar`, the hook must call `lua_getinfo` (see 2886 |lua_getinfo()|). For return events, `event` may be 2887 `LUA_HOOKRET`, the normal value, or `LUA_HOOKTAILRET`. In the latter 2888 case, Lua is simulating a return from a function that did a tail call; 2889 in this case, it is useless to call `lua_getinfo`. 2890 2891 While Lua is running a hook, it disables other calls to hooks. 2892 Therefore, if a hook calls back Lua to execute a function or a chunk, 2893 this execution occurs without any calls to hooks. 2894 2895 2896 lua_sethook *lua_sethook()* 2897 >c 2898 int lua_sethook (lua_State *L, lua_Hook f, int mask, int count); 2899 < 2900 Sets the debugging hook function. 2901 2902 Argument `f` is the hook function. `mask` specifies on which events 2903 the hook will be called: it is formed by a bitwise `or` of the 2904 constants `LUA_MASKCALL`, `LUA_MASKRET`, `LUA_MASKLINE`, and 2905 `LUA_MASKCOUNT`. The `count` argument is only meaningful when the mask 2906 includes `LUA_MASKCOUNT`. For each event, the hook is called as 2907 explained below: 2908 2909 - `The call hook`: is called when the interpreter calls a function. 2910 The hook is called just after Lua enters the new function, before 2911 the function gets its arguments. 2912 - `The return hook`: is called when the interpreter returns from a 2913 function. The hook is called just before Lua leaves the function. 2914 You have no access to the values to be returned by the function. 2915 - `The line hook`: is called when the interpreter is about to start 2916 the execution of a new line of code, or when it jumps back in the 2917 code (even to the same line). (This event only happens while Lua is 2918 executing a Lua function.) 2919 - `The count hook`: is called after the interpreter executes every 2920 `count` instructions. (This event only happens while Lua is 2921 executing a Lua function.) 2922 2923 A hook is disabled by setting `mask` to zero. 2924 2925 lua_setlocal *lua_setlocal()* 2926 >c 2927 const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n); 2928 < 2929 Sets the value of a local variable of a given activation record. 2930 Parameters `ar` and `n` are as in `lua_getlocal` (see 2931 |lua_getlocal()|). `lua_setlocal` assigns the value at the top of 2932 the stack to the variable and returns its name. It also pops the value 2933 from the stack. 2934 2935 Returns `NULL` (and pops nothing) when the index is greater than the 2936 number of active local variables. 2937 2938 lua_setupvalue *lua_setupvalue()* 2939 >c 2940 const char *lua_setupvalue (lua_State *L, int funcindex, int n); 2941 < 2942 Sets the value of a closure's upvalue. It assigns the value at the top 2943 of the stack to the upvalue and returns its name. It also pops the 2944 value from the stack. Parameters `funcindex` and `n` are as in the 2945 `lua_getupvalue` (see |lua_getupvalue()|). 2946 2947 Returns `NULL` (and pops nothing) when the index is greater than the 2948 number of upvalues. 2949 2950 *lua-debugexample* 2951 As an example, the following function lists the names of all local 2952 variables and upvalues for a function at a given level of the stack: 2953 >c 2954 int listvars (lua_State *L, int level) { 2955 lua_Debug ar; 2956 int i; 2957 const char *name; 2958 if (lua_getstack(L, level, &ar) == 0) 2959 return 0; /* failure: no such level in the stack */ 2960 i = 1; 2961 while ((name = lua_getlocal(L, &ar, i++)) != NULL) { 2962 printf("local %d %s\n", i-1, name); 2963 lua_pop(L, 1); /* remove variable value */ 2964 } 2965 lua_getinfo(L, "f", &ar); /* retrieves function */ 2966 i = 1; 2967 while ((name = lua_getupvalue(L, -1, i++)) != NULL) { 2968 printf("upvalue %d %s\n", i-1, name); 2969 lua_pop(L, 1); /* remove upvalue value */ 2970 } 2971 return 1; 2972 } 2973 < 2974 2975 ============================================================================== 2976 4 THE AUXILIARY LIBRARY *lua-aux* 2977 2978 The auxiliary library provides several convenient functions to interface C 2979 with Lua. While the basic API provides the primitive functions for all 2980 interactions between C and Lua, the auxiliary library provides higher-level 2981 functions for some common tasks. 2982 2983 All functions from the auxiliary library are defined in header file `lauxlib.h` 2984 and have a prefix `luaL_`. 2985 2986 All functions in the auxiliary library are built on top of the basic API, and 2987 so they provide nothing that cannot be done with this API. 2988 2989 Several functions in the auxiliary library are used to check C function 2990 arguments. Their names are always `luaL_check*` or `luaL_opt*`. All of these 2991 functions raise an error if the check is not satisfied. Because the error 2992 message is formatted for arguments (e.g., "bad argument #1"), you should not 2993 use these functions for other stack values. 2994 2995 ============================================================================== 2996 4.1 Functions and Types *lua-auxFunctions* 2997 2998 Here we list all functions and types from the auxiliary library in 2999 alphabetical order. 3000 3001 luaL_addchar *luaL_addchar()* 3002 >c 3003 void luaL_addchar (luaL_Buffer *B, char c); 3004 < 3005 Adds the character `c` to the buffer `B` (see |luaL_Buffer|). 3006 3007 luaL_addlstring *luaL_addlstring()* 3008 >c 3009 void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); 3010 < 3011 Adds the string pointed to by `s` with length `l` to the buffer `B` 3012 (see |luaL_Buffer|). The string may contain embedded zeros. 3013 3014 luaL_addsize *luaL_addsize()* 3015 >c 3016 void luaL_addsize (luaL_Buffer *B, size_t n); 3017 < 3018 Adds to the buffer `B` (see |luaL_Buffer|) a string of length 3019 `n` previously copied to the buffer area (see 3020 |luaL_prepbuffer()|). 3021 3022 luaL_addstring *luaL_addstring()* 3023 >c 3024 void luaL_addstring (luaL_Buffer *B, const char *s); 3025 < 3026 Adds the zero-terminated string pointed to by `s` to the buffer `B` 3027 (see |luaL_Buffer|). The string may not contain embedded zeros. 3028 3029 luaL_addvalue *luaL_addvalue()* 3030 >c 3031 void luaL_addvalue (luaL_Buffer *B); 3032 < 3033 Adds the value at the top of the stack to the buffer `B` (see 3034 |luaL_Buffer|). Pops the value. 3035 3036 This is the only function on string buffers that can (and must) be 3037 called with an extra element on the stack, which is the value to be 3038 added to the buffer. 3039 3040 luaL_argcheck *luaL_argcheck()* 3041 >c 3042 void luaL_argcheck (lua_State *L, 3043 int cond, 3044 int narg, 3045 const char *extramsg); 3046 < 3047 Checks whether `cond` is true. If not, raises an error with the 3048 following message, where `func` is retrieved from the call stack: 3049 > 3050 bad argument #<narg> to <func> (<extramsg>) 3051 < 3052 3053 luaL_argerror *luaL_argerror()* 3054 >c 3055 int luaL_argerror (lua_State *L, int narg, const char *extramsg); 3056 < 3057 Raises an error with the following message, where `func` is retrieved 3058 from the call stack: 3059 > 3060 bad argument #<narg> to <func> (<extramsg>) 3061 < 3062 This function never returns, but it is an idiom to use it in C 3063 functions as `return luaL_argerror(` `args` `)`. 3064 3065 luaL_Buffer *luaL_Buffer* 3066 >c 3067 typedef struct luaL_Buffer luaL_Buffer; 3068 < 3069 Type for a `string buffer`. 3070 3071 A string buffer allows C code to build Lua strings piecemeal. Its 3072 pattern of use is as follows: 3073 3074 - First you declare a variable `b` of type `luaL_Buffer`. 3075 - Then you initialize it with a call `luaL_buffinit(L, &b)` (see 3076 |luaL_buffinit()|). 3077 - Then you add string pieces to the buffer calling any of the 3078 `luaL_add*` functions. 3079 - You finish by calling `luaL_pushresult(&b)` (see 3080 |luaL_pushresult()|). This call leaves the final string on the 3081 top of the stack. 3082 3083 During its normal operation, a string buffer uses a variable number of 3084 stack slots. So, while using a buffer, you cannot assume that you know 3085 where the top of the stack is. You can use the stack between 3086 successive calls to buffer operations as long as that use is balanced; 3087 that is, when you call a buffer operation, the stack is at the same 3088 level it was immediately after the previous buffer operation. (The 3089 only exception to this rule is `luaL_addvalue` 3090 |luaL_addvalue()|.) After calling `luaL_pushresult` the stack is 3091 back to its level when the buffer was initialized, plus the final 3092 string on its top. 3093 3094 luaL_buffinit *luaL_buffinit()* 3095 >c 3096 void luaL_buffinit (lua_State *L, luaL_Buffer *B); 3097 < 3098 Initializes a buffer `B`. This function does not allocate any space; 3099 the buffer must be declared as a variable (see |luaL_Buffer|). 3100 3101 luaL_callmeta *luaL_callmeta()* 3102 >c 3103 int luaL_callmeta (lua_State *L, int obj, const char *e); 3104 < 3105 Calls a metamethod. 3106 3107 If the object at index `obj` has a metatable and this metatable has a 3108 field `e`, this function calls this field and passes the object as its 3109 only argument. In this case this function returns 1 and pushes onto 3110 the stack the value returned by the call. If there is no metatable or 3111 no metamethod, this function returns 3112 0 (without pushing any value on the stack). 3113 3114 luaL_checkany *luaL_checkany()* 3115 >c 3116 void luaL_checkany (lua_State *L, int narg); 3117 < 3118 Checks whether the function has an argument of any type (including 3119 `nil`) at position `narg`. 3120 3121 luaL_checkint *luaL_checkint()* 3122 >c 3123 int luaL_checkint (lua_State *L, int narg); 3124 < 3125 Checks whether the function argument `narg` is a number and returns 3126 this number cast to an `int`. 3127 3128 luaL_checkinteger *luaL_checkinteger()* 3129 >c 3130 lua_Integer luaL_checkinteger (lua_State *L, int narg); 3131 < 3132 Checks whether the function argument `narg` is a number and returns 3133 this number cast to a `lua_Integer` (see |lua_Integer|). 3134 3135 luaL_checklong *luaL_checklong()* 3136 >c 3137 long luaL_checklong (lua_State *L, int narg); 3138 < 3139 Checks whether the function argument `narg` is a number and returns 3140 this number cast to a `long`. 3141 3142 luaL_checklstring *luaL_checklstring()* 3143 >c 3144 const char *luaL_checklstring (lua_State *L, int narg, size_t *l); 3145 < 3146 Checks whether the function argument `narg` is a string and returns 3147 this string; if `l` is not `NULL` fills `*l` with the string's length. 3148 3149 luaL_checknumber *luaL_checknumber()* 3150 >c 3151 lua_Number luaL_checknumber (lua_State *L, int narg); 3152 < 3153 Checks whether the function argument `narg` is a number and returns 3154 this number (see |lua_Number|). 3155 3156 luaL_checkoption *luaL_checkoption()* 3157 >c 3158 int luaL_checkoption (lua_State *L, 3159 int narg, 3160 const char *def, 3161 const char *const lst[]); 3162 < 3163 Checks whether the function argument `narg` is a string and searches 3164 for this string in the array `lst` (which must be NULL-terminated). 3165 Returns the index in the array where the string was found. Raises an 3166 error if the argument is not a string or if the string cannot be 3167 found. 3168 3169 If `def` is not `NULL`, the function uses `def` as a default value 3170 when there is no argument `narg` or if this argument is `nil`. 3171 3172 This is a useful function for mapping strings to C enums. (The usual 3173 convention in Lua libraries is to use strings instead of numbers to 3174 select options.) 3175 3176 luaL_checkstack *luaL_checkstack()* 3177 >c 3178 void luaL_checkstack (lua_State *L, int sz, const char *msg); 3179 < 3180 Grows the stack size to `top + sz` elements, raising an error if the 3181 stack cannot grow to that size. `msg` is an additional text to go into 3182 the error message. 3183 3184 luaL_checkstring *luaL_checkstring()* 3185 >c 3186 const char *luaL_checkstring (lua_State *L, int narg); 3187 < 3188 Checks whether the function argument `narg` is a string and returns 3189 this string. 3190 3191 luaL_checktype *luaL_checktype()* 3192 >c 3193 void luaL_checktype (lua_State *L, int narg, int t); 3194 < 3195 Checks whether the function argument `narg` has type `t` (see 3196 |lua_type()|). 3197 3198 luaL_checkudata *luaL_checkudata()* 3199 >c 3200 void *luaL_checkudata (lua_State *L, int narg, const char *tname); 3201 < 3202 Checks whether the function argument `narg` is a userdata of the type 3203 `tname` (see |luaL_newmetatable()|). 3204 3205 luaL_dofile *luaL_dofile()* 3206 >c 3207 int luaL_dofile (lua_State *L, const char *filename); 3208 < 3209 Loads and runs the given file. It is defined as the following macro: 3210 >c 3211 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) 3212 < 3213 It returns 0 if there are no errors or 1 in case of errors. 3214 3215 luaL_dostring *luaL_dostring()* 3216 >c 3217 int luaL_dostring (lua_State *L, const char *str); 3218 < 3219 Loads and runs the given string. It is defined as the following macro: 3220 >c 3221 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) 3222 < 3223 It returns 0 if there are no errors or 1 in case of errors. 3224 3225 luaL_error *luaL_error()* 3226 >c 3227 int luaL_error (lua_State *L, const char *fmt, ...); 3228 < 3229 Raises an error. The error message format is given by `fmt` plus any 3230 extra arguments, following the same rules of `lua_pushfstring` (see 3231 |lua_pushfstring()|). It also adds at the beginning of the 3232 message the file name and the line number where the error occurred, if 3233 this information is available. 3234 3235 This function never returns, but it is an idiom to use it in C 3236 functions as `return luaL_error(` `args` `)`. 3237 3238 luaL_getmetafield *luaL_getmetafield()* 3239 >c 3240 int luaL_getmetafield (lua_State *L, int obj, const char *e); 3241 < 3242 Pushes onto the stack the field `e` from the metatable of the object 3243 at index `obj`. If the object does not have a metatable, or if the 3244 metatable does not have this field, returns 0 and pushes nothing. 3245 3246 luaL_getmetatable *luaL_getmetatable()* 3247 >c 3248 void luaL_getmetatable (lua_State *L, const char *tname); 3249 < 3250 Pushes onto the stack the metatable associated with name `tname` in 3251 the registry (see |luaL_newmetatable()|). 3252 3253 luaL_gsub *luaL_gsub()* 3254 >c 3255 const char *luaL_gsub (lua_State *L, 3256 const char *s, 3257 const char *p, 3258 const char *r); 3259 < 3260 Creates a copy of string `s` by replacing any occurrence of the string 3261 `p` with the string `r`. Pushes the resulting string on the stack and 3262 returns it. 3263 3264 luaL_loadbuffer *luaL_loadbuffer()* 3265 >c 3266 int luaL_loadbuffer (lua_State *L, 3267 const char *buff, 3268 size_t sz, 3269 const char *name); 3270 < 3271 Loads a buffer as a Lua chunk. This function uses `lua_load` (see 3272 |lua_load()|) to load the chunk in the buffer pointed to by 3273 `buff` with size `sz`. 3274 3275 This function returns the same results as `lua_load`. `name` is the 3276 chunk name, used for debug information and error messages. 3277 3278 luaL_loadfile *luaL_loadfile()* 3279 >c 3280 int luaL_loadfile (lua_State *L, const char *filename); 3281 < 3282 Loads a file as a Lua chunk. This function uses `lua_load` (see 3283 |lua_load()|) to load the chunk in the file named `filename`. If 3284 `filename` is `NULL`, then it loads from the standard input. The first 3285 line in the file is ignored if it starts with a `#`. 3286 3287 This function returns the same results as `lua_load`, but it has an 3288 extra error code `LUA_ERRFILE` if it cannot open/read the file. 3289 3290 As `lua_load`, this function only loads the chunk; it does not run it. 3291 3292 luaL_loadstring *luaL_loadstring()* 3293 >c 3294 int luaL_loadstring (lua_State *L, const char *s); 3295 < 3296 Loads a string as a Lua chunk. This function uses `lua_load` (see 3297 |lua_load()|) to load the chunk in the zero-terminated string 3298 `s`. 3299 3300 This function returns the same results as `lua_load`. 3301 3302 Also as `lua_load`, this function only loads the chunk; it does not 3303 run it. 3304 3305 luaL_newmetatable *luaL_newmetatable()* 3306 >c 3307 int luaL_newmetatable (lua_State *L, const char *tname); 3308 < 3309 If the registry already has the key `tname`, returns 0. Otherwise, 3310 creates a new table to be used as a metatable for userdata, adds it to 3311 the registry with key `tname`, and returns 1. 3312 3313 In both cases pushes onto the stack the final value associated with 3314 `tname` in the registry. 3315 3316 luaL_newstate *luaL_newstate()* 3317 >c 3318 lua_State *luaL_newstate (void); 3319 < 3320 Creates a new Lua state. It calls `lua_newstate` (see 3321 |lua_newstate()|) with an allocator based on the standard C 3322 `realloc` function and then sets a panic function (see 3323 |lua_atpanic()|) that prints an error message to the standard 3324 error output in case of fatal errors. 3325 3326 Returns the new state, or `NULL` if there is a memory allocation 3327 error. 3328 3329 luaL_openlibs *luaL_openlibs()* 3330 >c 3331 void luaL_openlibs (lua_State *L); 3332 < 3333 Opens all standard Lua libraries into the given state. See also 3334 |lua-openlibs| for details on how to open individual libraries. 3335 3336 luaL_optint *luaL_optint()* 3337 >c 3338 int luaL_optint (lua_State *L, int narg, int d); 3339 < 3340 If the function argument `narg` is a number, returns this number cast 3341 to an `int`. If this argument is absent or is `nil`, returns `d`. 3342 Otherwise, raises an error. 3343 3344 luaL_optinteger *luaL_optinteger()* 3345 >c 3346 lua_Integer luaL_optinteger (lua_State *L, 3347 int narg, 3348 lua_Integer d); 3349 < 3350 If the function argument `narg` is a number, returns this number cast 3351 to a `lua_Integer` (see |lua_Integer|). If this argument is 3352 absent or is `nil`, returns `d`. Otherwise, raises an error. 3353 3354 luaL_optlong *luaL_optlong()* 3355 >c 3356 long luaL_optlong (lua_State *L, int narg, long d); 3357 < 3358 If the function argument `narg` is a number, returns this number cast 3359 to a `long`. If this argument is absent or is `nil`, returns `d`. 3360 Otherwise, raises an error. 3361 3362 luaL_optlstring *luaL_optlstring()* 3363 >c 3364 const char *luaL_optlstring (lua_State *L, 3365 int narg, 3366 const char *d, 3367 size_t *l); 3368 < 3369 If the function argument `narg` is a string, returns this string. If 3370 this argument is absent or is `nil`, returns `d`. Otherwise, raises an 3371 error. 3372 3373 If `l` is not `NULL`, fills the position `*l` with the results' length. 3374 3375 luaL_optnumber *luaL_optnumber()* 3376 >c 3377 lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d); 3378 < 3379 If the function argument `narg` is a number, returns this number. If 3380 this argument is absent or is `nil`, returns `d`. Otherwise, raises an 3381 error. 3382 3383 luaL_optstring *luaL_optstring()* 3384 >c 3385 const char *luaL_optstring (lua_State *L, 3386 int narg, 3387 const char *d); 3388 < 3389 If the function argument `narg` is a string, returns this string. If 3390 this argument is absent or is `nil`, returns `d`. Otherwise, raises an 3391 error. 3392 3393 luaL_prepbuffer *luaL_prepbuffer()* 3394 >c 3395 char *luaL_prepbuffer (luaL_Buffer *B); 3396 < 3397 Returns an address to a space of size `LUAL_BUFFERSIZE` where you can 3398 copy a string to be added to buffer `B` (see |luaL_Buffer|). 3399 After copying the string into this space you must call `luaL_addsize` 3400 (see |luaL_addsize()|) with the size of the string to actually 3401 add it to the buffer. 3402 3403 luaL_pushresult *luaL_pushresult()* 3404 >c 3405 void luaL_pushresult (luaL_Buffer *B); 3406 < 3407 Finishes the use of buffer `B` leaving the final string on the top of 3408 the stack. 3409 3410 luaL_ref *luaL_ref()* 3411 >c 3412 int luaL_ref (lua_State *L, int t); 3413 < 3414 Creates and returns a `reference`, in the table at index `t`, for the 3415 object at the top of the stack (and pops the object). 3416 3417 A reference is a unique integer key. As long as you do not manually 3418 add integer keys into table `t`, `luaL_ref` ensures the uniqueness of 3419 the key it returns. You can retrieve an object referred by reference 3420 `r` by calling `lua_rawgeti(L, t, r)` (see |lua_rawgeti()|). 3421 Function `luaL_unref` (see |luaL_unref()|) frees a reference and 3422 its associated object. 3423 3424 If the object at the top of the stack is `nil`, `luaL_ref` returns the 3425 constant `LUA_REFNIL`. The constant `LUA_NOREF` is guaranteed to be 3426 different from any reference returned by `luaL_ref`. 3427 3428 luaL_Reg *luaL_Reg* 3429 >c 3430 typedef struct luaL_Reg { 3431 const char *name; 3432 lua_CFunction func; 3433 } luaL_Reg; 3434 < 3435 Type for arrays of functions to be registered by `luaL_register` (see 3436 |luaL_register()|). `name` is the function name and `func` is a 3437 pointer to the function. Any array of `luaL_Reg` must end with a 3438 sentinel entry in which both `name` and `func` are `NULL`. 3439 3440 luaL_register *luaL_register()* 3441 >c 3442 void luaL_register (lua_State *L, 3443 const char *libname, 3444 const luaL_Reg *l); 3445 < 3446 Opens a library. 3447 3448 When called with `libname` equal to `NULL`, it simply registers all 3449 functions in the list `l` (see |luaL_Reg|) into the table on 3450 the top of the stack. 3451 3452 When called with a non-null `libname`, `luaL_register` creates a new 3453 table `t`, sets it as the value of the global variable `libname`, sets 3454 it as the value of `package.loaded[libname]`, and registers on it all 3455 functions in the list `l`. If there is a table in 3456 `package.loaded[libname]` or in variable `libname`, reuses this table 3457 instead of creating a new one. 3458 3459 In any case the function leaves the table on the top of the stack. 3460 3461 luaL_typename *luaL_typename()* 3462 >c 3463 const char *luaL_typename (lua_State *L, int idx); 3464 < 3465 Returns the name of the type of the value at index `idx`. 3466 3467 luaL_typerror *luaL_typerror()* 3468 >c 3469 int luaL_typerror (lua_State *L, int narg, const char *tname); 3470 < 3471 Generates an error with a message like the following: 3472 3473 `location` `: bad argument` `narg` `to` `'func'` `(` `tname` 3474 `expected, got` `rt` `)` 3475 3476 where `location` is produced by `luaL_where` (see 3477 |luaL_where()|), `func` is the name of the current function, and 3478 `rt` is the type name of the actual argument. 3479 3480 luaL_unref *luaL_unref()* 3481 >c 3482 void luaL_unref (lua_State *L, int t, int ref); 3483 < 3484 Releases reference `ref` from the table at index `t` (see 3485 |luaL_ref()|). The entry is removed from the table, so that the 3486 referred object can be collected. The reference `ref` is also freed to 3487 be used again. 3488 3489 If `ref` is `LUA_NOREF` or `LUA_REFNIL`, `luaL_unref` does nothing. 3490 3491 luaL_where *luaL_where()* 3492 >c 3493 void luaL_where (lua_State *L, int lvl); 3494 < 3495 Pushes onto the stack a string identifying the current position of the 3496 control at level `lvl` in the call stack. Typically this string has 3497 the following format: 3498 3499 `chunkname:currentline:` 3500 3501 Level 0 is the running function, level 1 is the function that called 3502 the running function, etc. 3503 3504 This function is used to build a prefix for error messages. 3505 3506 ============================================================================== 3507 5 STANDARD LIBRARIES *lua-lib* 3508 3509 The standard libraries provide useful functions that are implemented directly 3510 through the C API. Some of these functions provide essential services to the 3511 language (e.g., `type` and `getmetatable`); others provide access to "outside" 3512 services (e.g., I/O); and others could be implemented in Lua itself, but are 3513 quite useful or have critical performance requirements that deserve an 3514 implementation in C (e.g., `sort`). 3515 3516 All libraries are implemented through the official C API and are provided as 3517 separate C modules. Currently, Lua has the following standard libraries: 3518 3519 - basic library; 3520 - package library; 3521 - string manipulation; 3522 - table manipulation; 3523 - mathematical functions (sin, log, etc.); 3524 - input and output; 3525 - operating system facilities; 3526 - debug facilities. 3527 3528 Except for the basic and package libraries, each library provides all its 3529 functions as fields of a global table or as methods of its objects. 3530 3531 *lua-openlibs* 3532 To have access to these libraries, the C host program should call the 3533 `luaL_openlibs` function, which opens all standard libraries (see 3534 |luaL_openlibs()|). Alternatively, the host program can open the libraries 3535 individually by calling `luaopen_base` (for the basic library), 3536 `luaopen_package` (for the package library), `luaopen_string` (for the string 3537 library), `luaopen_table` (for the table library), `luaopen_math` (for the 3538 mathematical library), `luaopen_io` (for the I/O and the Operating System 3539 libraries), and `luaopen_debug` (for the debug library). These functions are 3540 declared in `lualib.h` and should not be called directly: you must call them 3541 like any other Lua C function, e.g., by using `lua_call` (see |lua_call()|). 3542 3543 ============================================================================== 3544 5.1 Basic Functions *lua-lib-core* 3545 3546 The basic library provides some core functions to Lua. If you do not include 3547 this library in your application, you should check carefully whether you need 3548 to provide implementations for some of its facilities. 3549 3550 assert({v} [, {message}]) *assert()* 3551 Issues an error when the value of its argument `v` is false (i.e., `nil` or 3552 `false`); otherwise, returns all its arguments. `message` is an error message; 3553 when absent, it defaults to "assertion failed!" 3554 3555 collectgarbage({opt} [, {arg}]) *collectgarbage()* 3556 This function is a generic interface to the garbage collector. It 3557 performs different functions according to its first argument, {opt}: 3558 3559 `"stop"` stops the garbage collector. 3560 `"restart"` restarts the garbage collector. 3561 `"collect"` performs a full garbage-collection cycle. 3562 `"count"` returns the total memory in use by Lua (in Kbytes). 3563 `"step"` performs a garbage-collection step. The step "size" is 3564 controlled by {arg} (larger values mean more steps) in a 3565 non-specified way. If you want to control the step size 3566 you must experimentally tune the value of {arg}. Returns 3567 `true` if the step finished a collection cycle. 3568 `"setpause"` sets {arg} /100 as the new value for the `pause` of 3569 the collector (see |lua-gc|). 3570 `"setstepmul"` sets {arg} /100 as the new value for the 3571 `step multiplier` of the collector (see |lua-gc|). 3572 3573 dofile({filename}) *dofile()* 3574 Opens the named file and executes its contents as a Lua chunk. When 3575 called without arguments, `dofile` executes the contents of the 3576 standard input (`stdin`). Returns all values returned by the chunk. In 3577 case of errors, `dofile` propagates the error to its caller (that is, 3578 `dofile` does not run in protected mode). 3579 3580 error({message} [, {level}]) *error()* 3581 Terminates the last protected function called and returns `message` as 3582 the error message. Function {error} never returns. 3583 3584 Usually, {error} adds some information about the error position at the 3585 beginning of the message. The {level} argument specifies how to get 3586 the error position. With level 1 (the default), the error position is 3587 where the {error} function was called. Level 2 points the error to 3588 where the function that called {error} was called; and so on. Passing 3589 a level 0 avoids the addition of error position information to the 3590 message. 3591 3592 _G *_G* 3593 A global variable (not a function) that holds the global environment 3594 (that is, `_G._G = _G`). Lua itself does not use this variable; 3595 changing its value does not affect any environment, nor vice-versa. 3596 (Use `setfenv` to change environments.) 3597 3598 getfenv({f}) *getfenv()* 3599 Returns the current environment in use by the function. {f} can be a 3600 Lua function or a number that specifies the function at that stack 3601 level: Level 1 is the function calling `getfenv`. If the given 3602 function is not a Lua function, or if {f} is 0, `getfenv` returns the 3603 global environment. The default for {f} is 1. 3604 3605 getmetatable({object}) *getmetatable()* 3606 If {object} does not have a metatable, returns `nil`. Otherwise, if 3607 the object's metatable has a `"__metatable"` field, returns the 3608 associated value. Otherwise, returns the metatable of the given 3609 object. 3610 3611 ipairs({t}) *ipairs()* 3612 Returns three values: an |iterator| function, the table {t}, and 0, so 3613 that the construction 3614 3615 `for i,v in ipairs(t) do` `body` `end` 3616 3617 will iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the 3618 first integer key absent from the table. 3619 3620 load({func} [, {chunkname}]) *load()* 3621 Loads a chunk using function {func} to get its pieces. Each call to 3622 {func} must return a string that concatenates with previous results. A 3623 return of `nil` (or no value) signals the end of the chunk. 3624 3625 If there are no errors, returns the compiled chunk as a function; 3626 otherwise, returns `nil` plus the error message. The environment of 3627 the returned function is the global environment. 3628 3629 {chunkname} is used as the chunk name for error messages and debug 3630 information. 3631 3632 loadfile([{filename}]) *loadfile()* 3633 Similar to `load` (see |load()|), but gets the chunk from file 3634 {filename} or from the standard input, if no file name is given. 3635 3636 loadstring({string} [, {chunkname}]) *loadstring()* 3637 Similar to `load` (see |load()|), but gets the chunk from the 3638 given {string}. 3639 3640 To load and run a given string, use the idiom 3641 >lua 3642 assert(loadstring(s))() 3643 < 3644 3645 next({table} [, {index}]) *next()* 3646 Allows a program to traverse all fields of a table. Its first argument 3647 is a table and its second argument is an index in this table. `next` 3648 returns the next index of the table and its associated value. When 3649 called with `nil` as its second argument, `next` returns an initial 3650 index and its associated value. When called with the last index, or 3651 with `nil` in an empty table, `next` returns `nil`. If the second 3652 argument is absent, then it is interpreted as `nil`. In particular, 3653 you can use `next(t)` to check whether a table is empty. 3654 3655 The order in which the indices are enumerated is not specified, even 3656 for numeric indices. (To traverse a table in numeric order, use a 3657 numerical `for` or the |ipairs()| function.) 3658 3659 The behavior of `next` is `undefined` if, during the traversal, you 3660 assign any value to a non-existent field in the table. You may however 3661 modify existing fields. In particular, you may clear existing fields. 3662 3663 pairs({t}) *pairs()* 3664 Returns three values: the |next()| function, the table {t}, and `nil`, 3665 so that the construction 3666 3667 `for k,v in pairs(t) do` `body` `end` 3668 3669 will iterate over all key-value pairs of table {t}. 3670 3671 pcall({f}, {arg1}, {...}) *pcall()* 3672 Calls function {f} with the given arguments in `protected mode`. This 3673 means that any error inside {f} is not propagated; instead, `pcall` 3674 catches the error and returns a status code. Its first result is the 3675 status code (a boolean), which is `true` if the call succeeds without 3676 errors. In such case, `pcall` also returns all results from the call, 3677 after this first result. In case of any error, `pcall` returns `false` 3678 plus the error message. 3679 3680 print({...}) *print()* 3681 Receives any number of arguments, and prints their values to `stdout`, 3682 using the `tostring` |tostring()| function to convert them to 3683 strings. `print` is not intended for formatted output, but only as a 3684 quick way to show a value, typically for debugging. For formatted 3685 output, use `string.format` (see |string.format()|). 3686 3687 rawequal({v1}, {v2}) *rawequal()* 3688 Checks whether {v1} is equal to {v2}, without invoking any metamethod. 3689 Returns a boolean. 3690 3691 rawget({table}, {index}) *rawget()* 3692 Gets the real value of `table[index]`, without invoking any 3693 metamethod. {table} must be a table; {index} may be any value. 3694 3695 rawset({table}, {index}, {value}) *rawset()* 3696 Sets the real value of `table[index]` to {value}, without invoking any 3697 metamethod. {table} must be a table, {index} any value different from 3698 `nil`, and {value} any Lua value. 3699 3700 This function returns {table}. 3701 3702 select({index}, {...}) *select()* 3703 If {index} is a number, returns all arguments after argument number 3704 {index}. Otherwise, {index} must be the string `"#"`, and `select` 3705 returns the total number of extra arguments it received. 3706 3707 setfenv({f}, {table}) *setfenv()* 3708 Sets the environment to be used by the given function. {f} can be a 3709 Lua function or a number that specifies the function at that stack 3710 level: Level 1 is the function calling `setfenv`. `setfenv` returns 3711 the given function. 3712 3713 As a special case, when {f} is 0 `setfenv` changes the environment of 3714 the running thread. In this case, `setfenv` returns no values. 3715 3716 setmetatable({table}, {metatable}) *setmetatable()* 3717 Sets the metatable for the given table. (You cannot change the 3718 metatable of other types from Lua, only from C.) If {metatable} is 3719 `nil`, removes the metatable of the given table. If the original 3720 metatable has a `"__metatable"` field, raises an error. 3721 3722 This function returns {table}. 3723 3724 tonumber({e} [, {base}]) *tonumber()* 3725 Tries to convert its argument to a number. If the argument is already 3726 a number or a string convertible to a number, then `tonumber` returns 3727 this number; otherwise, it returns `nil`. 3728 3729 An optional argument specifies the base to interpret the numeral. The 3730 base may be any integer between 2 and 36, inclusive. In bases above 3731 10, the letter `A` (in either upper or lower case) represents 10, `B` 3732 represents 11, and so forth, with `Z'` representing 35. In base 10 3733 (the default), the number may have a decimal part, as well as an 3734 optional exponent part (see |lua-lexical|). In other bases, 3735 only unsigned integers are accepted. 3736 3737 tostring({e}) *tostring()* 3738 Receives an argument of any type and converts it to a string in a 3739 reasonable format. For complete control of how numbers are converted, 3740 use `string.format` (see |string.format()|). 3741 3742 *__tostring* 3743 If the metatable of {e} has a `"__tostring"` field, `tostring` calls 3744 the corresponding value with {e} as argument, and uses the result of 3745 the call as its result. 3746 3747 type({v}) *lua-type()* 3748 Returns the type of its only argument, coded as a string. The possible 3749 results of this function are `"nil"` (a string, not the value `nil`), 3750 `"number"`, `"string"`, `"boolean`, `"table"`, `"function"`, 3751 `"thread"`, and `"userdata"`. 3752 3753 unpack({list} [, {i} [, {j}]]) *unpack()* 3754 Returns the elements from the given table. This function is equivalent 3755 to 3756 >lua 3757 return list[i], list[i+1], ..., list[j] 3758 < 3759 except that the above code can be written only for a fixed number of 3760 elements. By default, {i} is 1 and {j} is the length of the list, as 3761 defined by the length operator (see |lua-length|). 3762 3763 _VERSION *_VERSION* 3764 A global variable (not a function) that holds a string containing the 3765 current interpreter version. The current contents of this string is 3766 `"Lua 5.1"` . 3767 3768 xpcall({f}, {err}) *xpcall()* 3769 This function is similar to `pcall` (see |pcall()|), except that you 3770 can set a new error handler. 3771 3772 `xpcall` calls function {f} in protected mode, using {err} as the 3773 error handler. Any error inside {f} is not propagated; instead, 3774 `xpcall` catches the error, calls the {err} function with the original 3775 error object, and returns a status code. Its first result is the 3776 status code (a boolean), which is true if the call succeeds without 3777 errors. In this case, `xpcall` also returns all results from the call, 3778 after this first result. In case of any error, `xpcall` returns 3779 `false` plus the result from {err}. 3780 3781 ============================================================================== 3782 5.2 Coroutine Manipulation *lua-lib-coroutine* 3783 3784 The operations related to coroutines comprise a sub-library of the basic 3785 library and come inside the table `coroutine`. See |lua-coroutine| for a 3786 general description of coroutines. 3787 3788 coroutine.create({f}) *coroutine.create()* 3789 Creates a new coroutine, with body {f}. {f} must be a Lua function. 3790 Returns this new coroutine, an object with type `"thread"`. 3791 3792 coroutine.resume({co} [, {val1}, {...}]) *coroutine.resume()* 3793 Starts or continues the execution of coroutine {co}. The first time 3794 you resume a coroutine, it starts running its body. The values {val1}, 3795 {...} are passed as arguments to the body function. If the coroutine has 3796 yielded, `resume` restarts it; the values {val1}, {...} are passed as 3797 the results from the yield. 3798 3799 If the coroutine runs without any errors, `resume` returns `true` plus 3800 any values passed to `yield` (if the coroutine yields) or any values 3801 returned by the body function(if the coroutine terminates). If there 3802 is any error, `resume` returns `false` plus the error message. 3803 3804 coroutine.running() *coroutine.running()* 3805 Returns the running coroutine, or `nil` when called by the main 3806 thread. 3807 3808 coroutine.status({co}) *coroutine.status()* 3809 Returns the status of coroutine {co}, as a string: `"running"`, if the 3810 coroutine is running (that is, it called `status`); `"suspended"`, if 3811 the coroutine is suspended in a call to `yield`, or if it has not 3812 started running yet; `"normal"` if the coroutine is active but not 3813 running (that is, it has resumed another coroutine); and `"dead"` if 3814 the coroutine has finished its body function, or if it has stopped 3815 with an error. 3816 3817 coroutine.wrap({f}) *coroutine.wrap()* 3818 Creates a new coroutine, with body {f}. {f} must be a Lua function. 3819 Returns a function that resumes the coroutine each time it is called. 3820 Any arguments passed to the function behave as the extra arguments to 3821 `resume`. Returns the same values returned by `resume`, except the 3822 first boolean. In case of error, propagates the error. 3823 3824 coroutine.yield({...}) *coroutine.yield()* 3825 Suspends the execution of the calling coroutine. The coroutine cannot 3826 be running a C function, a metamethod, or an |iterator|. Any arguments 3827 to `yield` are passed as extra results to `resume`. 3828 3829 ============================================================================== 3830 5.3 Modules *lua-modules* 3831 3832 The package library provides basic facilities for loading and building modules 3833 in Lua. It exports two of its functions directly in the global environment: 3834 `require` and `module` (see |require()| and |module()|). Everything else is 3835 exported in a table `package`. 3836 3837 module({name} [, {...}]) *module()* 3838 Creates a module. If there is a table in `package.loaded[name]`, this 3839 table is the module. Otherwise, if there is a global table `t` with 3840 the given name, this table is the module. Otherwise creates a new 3841 table `t` and sets it as the value of the global {name} and the value 3842 of `package.loaded[name]`. This function also initializes `t._NAME` 3843 with the given name, `t._M` with the module (`t` itself), and 3844 `t._PACKAGE` with the package name (the full module name minus last 3845 component; see below). Finally, `module` sets `t` as the new 3846 environment of the current function and the new value of 3847 `package.loaded[name]`, so that |require()| returns `t`. 3848 3849 If {name} is a compound name (that is, one with components separated 3850 by dots), `module` creates (or reuses, if they already exist) tables 3851 for each component. For instance, if {name} is `a.b.c`, then `module` 3852 stores the module table in field `c` of field `b` of global `a`. 3853 3854 This function may receive optional `options` after the module name, 3855 where each option is a function to be applied over the module. 3856 3857 require({modname}) *require()* 3858 Loads the given module. The function starts by looking into the 3859 `package.loaded` table to determine whether {modname} is already 3860 loaded. If it is, then `require` returns the value stored at 3861 `package.loaded[modname]`. Otherwise, it tries to find a `loader` for 3862 the module. 3863 3864 To find a loader, first `require` queries `package.preload[modname]`. 3865 If it has a value, this value (which should be a function) is the 3866 loader. Otherwise `require` searches for a Lua loader using the path 3867 stored in `package.path`. If that also fails, it searches for a C 3868 loader using the path stored in `package.cpath`. If that also fails, 3869 it tries an `all-in-one` loader (see below). 3870 3871 When loading a C library, `require` first uses a dynamic link facility 3872 to link the application with the library. Then it tries to find a C 3873 function inside this library to be used as the loader. The name of 3874 this C function is the string `"luaopen_"` concatenated with a copy of 3875 the module name where each dot is replaced by an underscore. Moreover, 3876 if the module name has a hyphen, its prefix up to (and including) the 3877 first hyphen is removed. For instance, if the module name is 3878 `a.v1-b.c`, the function name will be `luaopen_b_c`. 3879 3880 If `require` finds neither a Lua library nor a C library for a module, 3881 it calls the `all-in-one loader`. This loader searches the C path for 3882 a library for the root name of the given module. For instance, when 3883 requiring `a.b.c`, it will search for a C library for `a`. If found, 3884 it looks into it for an open function for the submodule; in our 3885 example, that would be `luaopen_a_b_c`. With this facility, a package 3886 can pack several C submodules into one single library, with each 3887 submodule keeping its original open function. 3888 3889 Once a loader is found, `require` calls the loader with a single 3890 argument, {modname}. If the loader returns any value, `require` 3891 assigns the returned value to `package.loaded[modname]`. If the loader 3892 returns no value and has not assigned any value to 3893 `package.loaded[modname]`, then `require` assigns `true` to this 3894 entry. In any case, `require` returns the final value of 3895 `package.loaded[modname]`. 3896 3897 If there is any error loading or running the module, or if it cannot 3898 find any loader for the module, then `require` signals an error. 3899 3900 package.cpath *package.cpath* 3901 The path used by `require` to search for a C loader. 3902 3903 Lua initializes the C path `package.cpath` in the same way it 3904 initializes the Lua path `package.path`, using the environment 3905 variable `LUA_CPATH` (plus another default path defined in 3906 `luaconf.h`). 3907 3908 package.loaded *package.loaded* 3909 A table used by `require` to control which modules are already loaded. 3910 When you require a module `modname` and `package.loaded[modname]` is 3911 not false, `require` simply returns the value stored there. 3912 3913 package.loadlib({libname}, {funcname}) *package.loadlib()* 3914 Dynamically links the host program with the C library {libname}. 3915 Inside this library, looks for a function {funcname} and returns this 3916 function as a C function. (So, {funcname} must follow the protocol 3917 (see |lua_CFunction|)). 3918 3919 This is a low-level function. It completely bypasses the package and 3920 module system. Unlike `require`, it does not perform any path 3921 searching and does not automatically adds extensions. {libname} must 3922 be the complete file name of the C library, including if necessary a 3923 path and extension. {funcname} must be the exact name exported by the 3924 C library (which may depend on the C compiler and linker used). 3925 3926 This function is not supported by ANSI C. As such, it is only 3927 available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, 3928 plus other Unix systems that support the `dlfcn` standard). 3929 3930 package.path *package.path* 3931 The path used by `require` to search for a Lua loader. 3932 3933 At start-up, Lua initializes this variable with the value of the 3934 environment variable `LUA_PATH` or with a default path defined in 3935 `luaconf.h`, if the environment variable is not defined. Any `";;"` in 3936 the value of the environment variable is replaced by the default path. 3937 3938 A path is a sequence of `templates` separated by semicolons. For each 3939 template, `require` will change each interrogation mark in the 3940 template by `filename`, which is `modname` with each dot replaced by a 3941 "directory separator" (such as `"/"` in Unix); then it will try to 3942 load the resulting file name. So, for instance, if the Lua path is 3943 > 3944 "./?.lua;./?.lc;/usr/local/?/init.lua" 3945 < 3946 the search for a Lua loader for module `foo` will try to load the 3947 files `./foo.lua`, `./foo.lc`, and `/usr/local/foo/init.lua`, in that 3948 order. 3949 3950 package.preload *package.preload* 3951 A table to store loaders for specific modules (see |require()|). 3952 3953 package.seeall({module}) *package.seeall()* 3954 Sets a metatable for {module} with its `__index` field referring to 3955 the global environment, so that this module inherits values from the 3956 global environment. To be used as an option to function {module}. 3957 3958 ============================================================================== 3959 5.4 String Manipulation *lua-lib-string* 3960 3961 This library provides generic functions for string manipulation, such as 3962 finding and extracting substrings, and pattern matching. When indexing a 3963 string in Lua, the first character is at position 1 (not at 0, as in C). 3964 Indices are allowed to be negative and are interpreted as indexing backwards, 3965 from the end of the string. Thus, the last character is at position -1, and 3966 so on. 3967 3968 The string library provides all its functions inside the table `string`. 3969 It also sets a metatable for strings where the `__index` field points to the 3970 `string` table. Therefore, you can use the string functions in object-oriented 3971 style. For instance, `string.byte(s, i)` can be written as `s:byte(i)`. 3972 3973 string.byte({s} [, {i} [, {j}]]) *string.byte()* 3974 Returns the internal numerical codes of the characters `s[i]`, 3975 `s[i+1]`,..., `s[j]`. The default value for {i} is 1; the default 3976 value for {j} is {i}. 3977 3978 Note that numerical codes are not necessarily portable across 3979 platforms. 3980 3981 string.char({...}) *string.char()* 3982 Receives zero or more integers. Returns a string with length equal to 3983 the number of arguments, in which each character has the internal 3984 numerical code equal to its correspondent argument. 3985 3986 Note that numerical codes are not necessarily portable across 3987 platforms. 3988 3989 string.dump({function}) *string.dump()* 3990 Returns a string containing a binary representation of the given 3991 function, so that a later |loadstring()| on this string returns a 3992 copy of the function. {function} must be a Lua function without 3993 upvalues. 3994 3995 string.find({s}, {pattern} [, {init} [, {plain}]]) *string.find()* 3996 Looks for the first match of {pattern} in the string {s}. If it finds 3997 a match, then {find} returns the indices of {s} where this occurrence 3998 starts and ends; otherwise, it returns `nil`. A third, optional 3999 numerical argument {init} specifies where to start the search; its 4000 default value is 1 and may be negative. A value of {true} as a fourth, 4001 optional argument {plain} turns off the pattern matching facilities, 4002 so the function does a plain "find substring" operation, with no 4003 characters in {pattern} being considered "magic". Note that if {plain} 4004 is given, then {init} must be given as well. 4005 4006 If the pattern has captures, then in a successful match the captured 4007 values are also returned, after the two indices. 4008 4009 string.format({formatstring}, {...}) *string.format()* 4010 Returns a formatted version of its variable number of arguments 4011 following the description given in its first argument (which must be a 4012 string). The format string follows the same rules as the `printf` 4013 family of standard C functions. The only differences are that the 4014 options/modifiers `*`, `l`, `L`, `n`, `p`, and `h` are not supported 4015 and that there is an extra option, `q`. The `q` option formats a 4016 string in a form suitable to be safely read back by the Lua 4017 interpreter: the string is written between double quotes, and all 4018 double quotes, newlines, embedded zeros, and backslashes in the string 4019 are correctly escaped when written. For instance, the call 4020 >lua 4021 string.format('%q', 'a string with "quotes" and \n new line') 4022 < 4023 will produce the string: 4024 >lua 4025 "a string with \"quotes\" and \ 4026 new line" 4027 < 4028 The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and 4029 `x` all expect a number as argument, whereas `q` and `s` expect a 4030 string. 4031 4032 This function does not accept string values containing embedded zeros. 4033 4034 string.gmatch({s}, {pattern}) *string.gmatch()* 4035 Returns an |iterator| function that, each time it is called, returns the 4036 next captures from {pattern} over string {s}. 4037 4038 If {pattern} specifies no captures, then the whole match is produced 4039 in each call. 4040 4041 As an example, the following loop 4042 >lua 4043 s = "hello world from Lua" 4044 for w in string.gmatch(s, "%a+") do 4045 print(w) 4046 end 4047 < 4048 will iterate over all the words from string {s}, printing one per 4049 line. The next example collects all pairs `key=value` from the given 4050 string into a table: 4051 >lua 4052 t = {} 4053 s = "from=world, to=Lua" 4054 for k, v in string.gmatch(s, "(%w+)=(%w+)") do 4055 t[k] = v 4056 end 4057 < 4058 4059 string.gsub({s}, {pattern}, {repl} [, {n}]) *string.gsub()* 4060 Returns a copy of {s} in which all occurrences of the {pattern} have 4061 been replaced by a replacement string specified by {repl}, which may 4062 be a string, a table, or a function. `gsub` also returns, as its 4063 second value, the total number of substitutions made. 4064 4065 If {repl} is a string, then its value is used for replacement. The 4066 character `%` works as an escape character: any sequence in {repl} of 4067 the form `%n`, with {n} between 1 and 9, stands for the value of the 4068 {n} -th captured substring (see below). The sequence `%0` stands for 4069 the whole match. The sequence `%%` stands for a single `%`. 4070 4071 If {repl} is a table, then the table is queried for every match, using 4072 the first capture as the key; if the pattern specifies no captures, 4073 then the whole match is used as the key. 4074 4075 If {repl} is a function, then this function is called every time a 4076 match occurs, with all captured substrings passed as arguments, in 4077 order; if the pattern specifies no captures, then the whole match is 4078 passed as a sole argument. 4079 4080 If the value returned by the table query or by the function call is a 4081 string or a number, then it is used as the replacement string; 4082 otherwise, if it is `false` or `nil`, then there is no replacement 4083 (that is, the original match is kept in the string). 4084 4085 The optional last parameter {n} limits the maximum number of 4086 substitutions to occur. For instance, when {n} is 1 only the first 4087 occurrence of `pattern` is replaced. 4088 4089 Here are some examples: 4090 >lua 4091 x = string.gsub("hello world", "(%w+)", "%1 %1") 4092 --> x="hello hello world world" 4093 4094 x = string.gsub("hello world", "%w+", "%0 %0", 1) 4095 --> x="hello hello world" 4096 4097 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") 4098 --> x="world hello Lua from" 4099 4100 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) 4101 --> x="home = /home/roberto, user = roberto" 4102 4103 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) 4104 return loadstring(s)() 4105 end) 4106 --> x="4+5 = 9" 4107 4108 local t = {name="lua", version="5.1"} 4109 x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t) 4110 --> x="lua-5.1.tar.gz" 4111 < 4112 4113 string.len({s}) *string.len()* 4114 Receives a string and returns its length. The empty string `""` has 4115 length 0. Embedded zeros are counted, so `"a\000b\000c"` has length 5. 4116 4117 string.lower({s}) *string.lower()* 4118 Receives a string and returns a copy of this string with all uppercase 4119 letters changed to lowercase. All other characters are left unchanged. 4120 The definition of what an uppercase letter is depends on the current 4121 locale. 4122 4123 string.match({s}, {pattern} [, {init}]) *string.match()* 4124 Looks for the first `match` of {pattern} in the string {s}. If it 4125 finds one, then `match` returns the captures from the pattern; 4126 otherwise it returns `nil`. If {pattern} specifies no captures, then 4127 the whole match is returned. A third, optional numerical argument 4128 {init} specifies where to start the search; its default value is 1 and 4129 may be negative. 4130 4131 string.rep({s}, {n}) *string.rep()* 4132 Returns a string that is the concatenation of {n} copies of the string 4133 {s}. 4134 4135 string.reverse({s}) *string.reverse()* 4136 Returns a string that is the string {s} reversed. 4137 4138 string.sub({s}, {i} [, {j}]) *string.sub()* 4139 Returns the substring of {s} that starts at {i} and continues until 4140 {j}; {i} and {j} may be negative. If {j} is absent, then it is assumed 4141 to be equal to `-1` (which is the same as the string length). In 4142 particular, the call `string.sub(s,1,j)` returns a prefix of {s} with 4143 length {j}, and `string.sub(s,-i)` returns a suffix of {s} with length 4144 {i}. 4145 4146 string.upper({s}) *string.upper()* 4147 Receives a string and returns a copy of that string with all lowercase 4148 letters changed to uppercase. All other characters are left unchanged. 4149 The definition of what a lowercase letter is depends on the current 4150 locale. 4151 4152 ------------------------------------------------------------------------------ 4153 5.4.1 Patterns *lua-pattern* 4154 4155 A character class is used to represent a set of characters. The following 4156 combinations are allowed in describing a character class: 4157 4158 - `x` (where `x` is not one of the magic characters `^$()%.[]*+-?`) 4159 represents the character `x` itself. 4160 - `.` (a dot) represents all characters. 4161 - `%a` represents all letters. 4162 - `%c` represents all control characters. 4163 - `%d` represents all digits. 4164 - `%l` represents all lowercase letters. 4165 - `%p` represents all punctuation characters. 4166 - `%s` represents all space characters. 4167 - `%u` represents all uppercase letters. 4168 - `%w` represents all alphanumeric characters. 4169 - `%x` represents all hexadecimal digits. 4170 - `%z` represents the character with representation `0`. 4171 - `%x` (where `x` is any non-alphanumeric character) represents the 4172 character `x`. This is the standard way to escape the magic 4173 characters. Any punctuation character (even the non-magic) can be 4174 preceded by a `%` when used to represent itself in a pattern. 4175 4176 - `[set]` represents the class which is the union of all characters in 4177 `set`. A range of characters may be specified by separating the end 4178 characters of the range with a `-`. All classes `%x` described 4179 above may also be used as components in `set`. All other characters 4180 in `set` represent themselves. For example, `[%w_]` (or `[_%w]`) 4181 represents all alphanumeric characters plus the underscore, `[0-7]` 4182 represents the octal digits, and `[0-7%l%-]` represents the octal 4183 digits plus the lowercase letters plus the `-` character. 4184 4185 The interaction between ranges and classes is not defined. Therefore, 4186 patterns like `[%a-z]` or `[a-%%]` have no meaning. 4187 4188 - `[^set]` represents the complement of `set`, where `set` is interpreted 4189 as above. 4190 4191 For all classes represented by single letters (`%a`, `%c`, etc.), the 4192 corresponding uppercase letter represents the complement of the class. For 4193 instance, `%S` represents all non-space characters. 4194 4195 The definitions of letter, space, and other character groups depend on the 4196 current locale. In particular, the class `[a-z]` may not be equivalent to `%l`. 4197 4198 PATTERN ITEM *lua-patternitem* 4199 4200 A pattern item may be 4201 4202 - a single character class, which matches any single character in the 4203 class; 4204 - a single character class followed by `*`, which matches 0 or more 4205 repetitions of characters in the class. These repetition items will 4206 always match the longest possible sequence; 4207 - a single character class followed by `+`, which matches 1 or more 4208 repetitions of characters in the class. These repetition items will 4209 always match the longest possible sequence; 4210 *lua-nongreedy* 4211 - a single character class followed by `-`, which also matches 0 or 4212 more repetitions of characters in the class. Unlike `*`, these 4213 repetition items will always match the shortest possible sequence; 4214 - a single character class followed by `?`, which matches 0 or 1 4215 occurrences of a character in the class; 4216 - `%n`, for `n` between 1 and 9; such item matches a substring equal to the 4217 `n` -th captured string (see below); 4218 - `%bxy`, where `x` and `y` are two distinct characters; such item matches 4219 strings that start with `x`, end with `y`, and where the `x` and `y` 4220 are balanced. This means that, if one reads the string from left to 4221 right, counting `+1` for an `x` and `-1` for a `y`, the ending `y` is the first 4222 `y` where the count reaches 0. For instance, the item `%b()` matches 4223 expressions with balanced parentheses. 4224 4225 PATTERN 4226 4227 A pattern is a sequence of pattern items. A `^` at the beginning of a pattern 4228 anchors the match at the beginning of the subject string. A `$` at the end of 4229 a pattern anchors the match at the end of the subject string. At other 4230 positions, `^` and `$` have no special meaning and represent themselves. 4231 4232 CAPTURES *lua-capture* 4233 4234 A pattern may contain sub-patterns enclosed in parentheses; they describe 4235 captures. When a match succeeds, the substrings of the subject string that 4236 match captures are stored (captured) for future use. Captures are numbered 4237 according to their left parentheses. For instance, in the pattern 4238 `"(a*(.)%w(%s*))"`, the part of the string matching `"a*(.)%w(%s*)"` is stored 4239 as the first capture (and therefore has number 1); the character matching `.` 4240 is captured with number 2, and the part matching `%s*` has number 3. 4241 4242 As a special case, the empty capture `()` captures the current string position 4243 (a number). For instance, if we apply the pattern `"()aa()"` on the 4244 string `"flaaap"`, there will be two captures: 3 and 5. 4245 4246 A pattern cannot contain embedded zeros. Use `%z` instead. 4247 4248 ============================================================================== 4249 5.5 Table Manipulation *lua-lib-table* 4250 4251 This library provides generic functions for table manipulation. It provides 4252 all its functions inside the table `table`. 4253 4254 Most functions in the table library assume that the table represents an array 4255 or a list. For those functions, when we talk about the "length" of a table we 4256 mean the result of the length operator. 4257 4258 table.concat({table} [, {sep} [, {i} [, {j}]]]) *table.concat()* 4259 Given an array where all elements are strings or numbers, returns 4260 `table[i]..sep..table[i+1] ... sep..table[j]`. The default value for 4261 {sep} is the empty string, the default for {i} is 1, and the default 4262 for {j} is the length of the table. If {i} is greater than {j}, 4263 returns the empty string. 4264 4265 table.foreach({table}, {f}) *table.foreach()* 4266 Executes the given {f} over all elements of {table}. For each element, 4267 {f} is called with the index and respective value as arguments. If {f} 4268 returns a non-`nil` value, then the loop is broken, and this value is 4269 returned as the final value of `table.foreach`. 4270 4271 See |next()| for extra information about table traversals. 4272 4273 table.foreachi({table}, {f}) *table.foreachi()* 4274 Executes the given {f} over the numerical indices of {table}. For each 4275 index, {f} is called with the index and respective value as arguments. 4276 Indices are visited in sequential order, from 1 to `n`, where `n` is 4277 the length of the table. If {f} returns a non-`nil` value, then the 4278 loop is broken and this value is returned as the result of 4279 `table.foreachi`. 4280 4281 table.insert({table}, [{pos},] {value}) *table.insert()* 4282 Inserts element {value} at position {pos} in {table}, shifting up 4283 other elements to open space, if necessary. The default value for 4284 {pos} is `n+1`, where `n` is the length of the table (see 4285 |lua-length|), so that a call `table.insert(t,x)` inserts `x` 4286 at the end of table `t`. 4287 4288 table.maxn({table}) *table.maxn()* 4289 Returns the largest positive numerical index of the given table, or 4290 zero if the table has no positive numerical indices. (To do its job 4291 this function does a linear traversal of the whole table.) 4292 4293 table.remove({table} [, {pos}]) *table.remove()* 4294 Removes from {table} the element at position {pos}, shifting down 4295 other elements to close the space, if necessary. Returns the value of 4296 the removed element. The default value for {pos} is `n`, where `n` is 4297 the length of the table (see |lua-length|), so that a call 4298 `table.remove(t)` removes the last element of table `t`. 4299 4300 table.sort({table} [, {comp}]) *table.sort()* 4301 Sorts table elements in a given order, `in-place`, from `table[1]` to 4302 `table[n]`, where `n` is the length of the table (see |lua-length|). 4303 If {comp} is given, then it must be a function that receives two table 4304 elements, and returns true when the first is less than the second (so 4305 that `not comp(a[i+1],a[i])` will be true after the sort). If {comp} 4306 is not given, then the standard Lua operator `<` is used instead. 4307 4308 The sort algorithm is `not` stable, that is, elements considered equal by the 4309 given order may have their relative positions changed by the sort. 4310 4311 ============================================================================== 4312 5.6 Mathematical Functions *lua-lib-math* 4313 4314 This library is an interface to most of the functions of the standard C math 4315 library. It provides all its functions inside the table `math`. 4316 4317 math.abs({x}) *math.abs()* 4318 Returns the absolute value of {x}. 4319 4320 math.acos({x}) *math.acos()* 4321 Returns the arc cosine of {x} (in radians). 4322 4323 math.asin({x}) *math.asin()* 4324 Returns the arc sine of {x} (in radians). 4325 4326 math.atan({x}) *math.atan()* 4327 Returns the arc tangent of {x} (in radians). 4328 4329 math.atan2({x}, {y}) *math.atan2()* 4330 Returns the arc tangent of `x/y` (in radians), but uses the signs of 4331 both parameters to find the quadrant of the result. (It also handles 4332 correctly the case of {y} being zero.) 4333 4334 math.ceil({x}) *math.ceil()* 4335 Returns the smallest integer larger than or equal to {x}. 4336 4337 math.cos({x}) *math.cos()* 4338 Returns the cosine of {x} (assumed to be in radians). 4339 4340 math.cosh({x}) *math.cosh()* 4341 Returns the hyperbolic cosine of {x}. 4342 4343 math.deg({x}) *math.deg()* 4344 Returns the angle {x} (given in radians) in degrees. 4345 4346 math.exp({x}) *math.exp()* 4347 Returns the value `e^x`. 4348 4349 math.floor({x}) *math.floor()* 4350 Returns the largest integer smaller than or equal to {x}. 4351 4352 math.fmod({x}, {y}) *math.fmod()* 4353 Returns the remainder of the division of {x} by {y}. 4354 4355 math.frexp({x}) *math.frexp()* 4356 Returns `m` and `e` such that `x = m * 2^e`, `e` is an integer and the 4357 absolute value of `m` is in the range `[0.5, 1)` (or zero when {x} is 4358 zero). 4359 4360 math.huge *math.huge* 4361 The value `HUGE_VAL`, a value larger than or equal to any other 4362 numerical value. 4363 4364 math.ldexp({m}, {e}) *math.ldexp()* 4365 Returns `m * 2^e` (`e` should be an integer). 4366 4367 math.log({x}) *math.log()* 4368 Returns the natural logarithm of {x}. 4369 4370 math.log10({x}) *math.log10()* 4371 Returns the base-10 logarithm of {x}. 4372 4373 math.max({x}, {...}) *math.max()* 4374 Returns the maximum value among its arguments. 4375 4376 math.min({x}, {...}) *math.min()* 4377 Returns the minimum value among its arguments. 4378 4379 math.modf({x}) *math.modf()* 4380 Returns two numbers, the integral part of {x} and the fractional part 4381 of {x}. 4382 4383 math.pi *math.pi* 4384 The value of `pi`. 4385 4386 math.pow({x}, {y}) *math.pow()* 4387 Returns `x^y`. (You can also use the expression `x^y` to compute this 4388 value.) 4389 4390 math.rad({x}) *math.rad()* 4391 Returns the angle {x} (given in degrees) in radians. 4392 4393 math.random([{m} [, {n}]]) *math.random()* 4394 This function is an interface to the simple pseudo-random generator 4395 function `rand` provided by ANSI C. (No guarantees can be given for 4396 its statistical properties.) 4397 4398 When called without arguments, returns a pseudo-random real number in 4399 the range `[0,1)`. When called with a number {m}, `math.random` 4400 returns a pseudo-random integer in the range `[1, m]`. When called 4401 with two numbers {m} and {n}, `math.random` returns a pseudo-random 4402 integer in the range `[m, n]`. 4403 4404 math.randomseed({x}) *math.randomseed()* 4405 Sets {x} as the "seed" for the pseudo-random generator: equal seeds 4406 produce equal sequences of numbers. 4407 4408 math.sin({x}) *math.sin()* 4409 Returns the sine of {x} (assumed to be in radians). 4410 4411 math.sinh({x}) *math.sinh()* 4412 Returns the hyperbolic sine of {x}. 4413 4414 math.sqrt({x}) *math.sqrt()* 4415 Returns the square root of {x}. (You can also use the expression 4416 `x^0.5` to compute this value.) 4417 4418 math.tan({x}) *math.tan()* 4419 Returns the tangent of {x} (assumed to be in radians). 4420 4421 math.tanh({x}) *math.tanh()* 4422 Returns the hyperbolic tangent of {x}. 4423 4424 ============================================================================== 4425 5.6 Input and Output Facilities *lua-lib-io* 4426 4427 The I/O library provides two different styles for file manipulation. The first 4428 one uses implicit file descriptors; that is, there are operations to set a 4429 default input file and a default output file, and all input/output operations 4430 are over these default files. The second style uses explicit file 4431 descriptors. 4432 4433 When using implicit file descriptors, all operations are supplied by 4434 table `io`. When using explicit file descriptors, the operation `io.open` returns 4435 a file descriptor and then all operations are supplied as methods of the file 4436 descriptor. 4437 4438 The table `io` also provides three predefined file descriptors with their usual 4439 meanings from C: `io.stdin`, `io.stdout`, and `io.stderr`. 4440 4441 Unless otherwise stated, all I/O functions return `nil` on failure (plus an 4442 error message as a second result) and some value different from `nil` on 4443 success. 4444 4445 io.close([{file}]) *io.close()* 4446 Equivalent to `file:close`. Without a {file}, closes the default 4447 output file. 4448 4449 io.flush() *io.flush()* 4450 Equivalent to `file:flush` over the default output file. 4451 4452 io.input([{file}]) *io.input()* 4453 When called with a file name, it opens the named file (in text mode), 4454 and sets its handle as the default input file. When called with a file 4455 handle, it simply sets this file handle as the default input file. 4456 When called without parameters, it returns the current default input 4457 file. 4458 4459 In case of errors this function raises the error, instead of returning 4460 an error code. 4461 4462 io.lines([{filename}]) *io.lines()* 4463 Opens the given file name in read mode and returns an |iterator| 4464 function that, each time it is called, returns a new line from the 4465 file. Therefore, the construction 4466 4467 `for line in io.lines(filename) do` `body` `end` 4468 4469 will iterate over all lines of the file. When the iterator function 4470 detects the end of file, it returns `nil` (to finish the loop) and 4471 automatically closes the file. 4472 4473 The call `io.lines()` (without a file name) is equivalent to 4474 `io.input():lines()`; that is, it iterates over the lines of the 4475 default input file. In this case it does not close the file when the 4476 loop ends. 4477 4478 io.open({filename} [, {mode}]) *io.open()* 4479 This function opens a file, in the mode specified in the string 4480 {mode}. It returns a new file handle, or, in case of errors, `nil` 4481 plus an error message. 4482 4483 The {mode} string can be any of the following: 4484 4485 - `"r"` read mode (the default); 4486 - `"w"` write mode; 4487 - `"a"` append mode; 4488 - `"r+"` update mode, all previous data is preserved; 4489 - `"w+"` update mode, all previous data is erased; 4490 - `"a+"` append update mode, previous data is preserved, writing is 4491 only allowed at the end of file. 4492 4493 The {mode} string may also have a `b` at the end, which is needed in 4494 some systems to open the file in binary mode. This string is exactly 4495 what is used in the standard C function `fopen`. 4496 4497 io.output([{file}]) *io.output()* 4498 Similar to `io.input`, but operates over the default output file. 4499 4500 io.popen({prog} [, {mode}]) *io.popen()* 4501 Starts program {prog} in a separated process and returns a file handle 4502 that you can use to read data from this program (if {mode} is `"r"`, 4503 the default) or to write data to this program (if {mode} is `"w"`). 4504 4505 This function is system dependent and is not available on all 4506 platforms. 4507 4508 io.read({...}) *io.read()* 4509 Equivalent to `io.input():read`. 4510 4511 io.tmpfile() *io.tmpfile()* 4512 Returns a handle for a temporary file. This file is opened in update 4513 mode and it is automatically removed when the program ends. 4514 4515 io.type({obj}) *io.type()* 4516 Checks whether {obj} is a valid file handle. Returns the string 4517 `"file"` if {obj} is an open file handle, `"closed file"` if {obj} is 4518 a closed file handle, or `nil` if {obj} is not a file handle. 4519 4520 io.write({...}) *io.write()* 4521 Equivalent to `io.output():write`. 4522 4523 file:close() *file:close()* 4524 Closes `file`. Note that files are automatically closed when their 4525 handles are garbage collected, but that takes an unpredictable amount 4526 of time to happen. 4527 4528 file:flush() *file:flush()* 4529 Saves any written data to `file`. 4530 4531 file:lines() *file:lines()* 4532 Returns an |iterator| function that, each time it is called, returns a 4533 new line from the file. Therefore, the construction 4534 4535 `for line in file:lines() do` `body` `end` 4536 4537 will iterate over all lines of the file. (Unlike `io.lines`, this 4538 function does not close the file when the loop ends.) 4539 4540 file:read({...}) *file:read()* 4541 Reads the file `file`, according to the given formats, which specify 4542 what to read. For each format, the function returns a string (or a 4543 number) with the characters read, or `nil` if it cannot read data with 4544 the specified format. When called without formats, it uses a default 4545 format that reads the entire next line (see below). 4546 4547 The available formats are 4548 4549 `"*n"` reads a number; this is the only format that returns a 4550 number instead of a string. 4551 `"*a"` reads the whole file, starting at the current position. On 4552 end of file, it returns the empty string. 4553 `"*l"` reads the next line (skipping the end of line), returning 4554 `nil` on end of file. This is the default format. 4555 `number` reads a string with up to that number of characters, 4556 returning `nil` on end of file. If number is zero, it reads 4557 nothing and returns an empty string, or `nil` on end of file. 4558 4559 file:seek([{whence}] [, {offset}]) *file:seek()* 4560 Sets and gets the file position, measured from the beginning of the 4561 file, to the position given by {offset} plus a base specified by the 4562 string {whence}, as follows: 4563 4564 - `"set"`: base is position 0 (beginning of the file); 4565 - `"cur"`: base is current position; 4566 - `"end"`: base is end of file; 4567 4568 In case of success, function `seek` returns the final file position, 4569 measured in bytes from the beginning of the file. If this function 4570 fails, it returns `nil`, plus a string describing the error. 4571 4572 The default value for {whence} is `"cur"`, and for {offset} is 0. 4573 Therefore, the call `file:seek()` returns the current file position, 4574 without changing it; the call `file:seek("set")` sets the position to 4575 the beginning of the file (and returns 0); and the call 4576 `file:seek("end")` sets the position to the end of the file, and 4577 returns its size. 4578 4579 file:setvbuf({mode} [, {size}]) *file:setvbuf()* 4580 Sets the buffering mode for an output file. There are three available 4581 modes: 4582 4583 `"no"` no buffering; the result of any output operation appears 4584 immediately. 4585 `"full"` full buffering; output operation is performed only when 4586 the buffer is full (or when you explicitly `flush` the file 4587 (see |io.flush()|). 4588 `"line"` line buffering; output is buffered until a newline is 4589 output or there is any input from some special files (such as 4590 a terminal device). 4591 4592 For the last two cases, {size} specifies the size of the buffer, in 4593 bytes. The default is an appropriate size. 4594 4595 file:write({...}) *file:write()* 4596 Writes the value of each of its arguments to `file`. The arguments 4597 must be strings or numbers. To write other values, use `tostring` 4598 |tostring()| or `string.format` |string.format()| before 4599 `write`. 4600 4601 ============================================================================== 4602 5.8 Operating System Facilities *lua-lib-os* 4603 4604 This library is implemented through table `os`. 4605 4606 os.clock() *os.clock()* 4607 Returns an approximation of the amount in seconds of CPU time used by 4608 the program. 4609 4610 os.date([{format} [, {time}]]) *os.date()* 4611 Returns a string or a table containing date and time, formatted 4612 according to the given string {format}. 4613 4614 If the {time} argument is present, this is the time to be formatted 4615 (see the `os.time` function |os.time()| for a description of this 4616 value). Otherwise, `date` formats the current time. 4617 4618 If {format} starts with `!`, then the date is formatted in 4619 Coordinated Universal Time. After this optional character, if {format} 4620 is the string `"*t"`, then `date` returns a table with the following 4621 fields: `year` (four digits), `month` (1-12), `day` (1-31), `hour` 4622 (0-23), `min` (0-59), `sec` (0-61), `wday` (weekday, Sunday is 1), 4623 `yday` (day of the year), and `isdst` (daylight saving flag, a 4624 boolean). 4625 4626 If {format} is not `"*t"`, then `date` returns the date as a string, 4627 formatted according to the same rules as the C function `strftime`. 4628 4629 When called without arguments, `date` returns a reasonable date and 4630 time representation that depends on the host system and on the current 4631 locale (that is, `os.date()` is equivalent to `os.date("%c")`). 4632 4633 os.difftime({t2}, {t1}) *os.difftime()* 4634 Returns the number of seconds from time {t1} to time {t2}. In POSIX, 4635 Windows, and some other systems, this value is exactly `t2 - t1` . 4636 4637 os.execute([{command}]) *os.execute()* 4638 This function is equivalent to the C function `system`. It passes 4639 {command} to be executed by an operating system shell. It returns a 4640 status code, which is system-dependent. If {command} is absent, then 4641 it returns nonzero if a shell is available and zero otherwise. 4642 4643 os.exit([{code}]) *os.exit()* 4644 Calls the C function `exit`, with an optional {code}, to terminate the 4645 host program. The default value for {code} is the success code. 4646 4647 os.getenv({varname}) *os.getenv()* 4648 Returns the value of the process environment variable {varname}, or 4649 `nil` if the variable is not defined. 4650 4651 os.remove({filename}) *os.remove()* 4652 Deletes the file with the given name. Directories must be empty to be 4653 removed. If this function fails, it returns `nil`, plus a string 4654 describing the error. 4655 4656 os.rename({oldname}, {newname}) *os.rename()* 4657 Renames file named {oldname} to {newname}. If this function fails, it 4658 returns `nil`, plus a string describing the error. 4659 4660 os.setlocale({locale} [, {category}]) *os.setlocale()* 4661 Sets the current locale of the program. {locale} is a string 4662 specifying a locale; {category} is an optional string describing which 4663 category to change: `"all"`, `"collate"`, `"ctype"`, `"monetary"`, 4664 `"numeric"`, or `"time"`; the default category is `"all"`. The 4665 function returns the name of the new locale, or `nil` if the request 4666 cannot be honored. 4667 4668 os.time([{table}]) *os.time()* 4669 Returns the current time when called without arguments, or a time 4670 representing the date and time specified by the given table. This 4671 table must have fields `year`, `month`, and `day`, and may have fields 4672 `hour`, `min`, `sec`, and `isdst` (for a description of these fields, 4673 see the `os.date` function |os.date()|). 4674 4675 The returned value is a number, whose meaning depends on your system. 4676 In POSIX, Windows, and some other systems, this number counts the 4677 number of seconds since some given start time (the "epoch"). In other 4678 systems, the meaning is not specified, and the number returned by 4679 `time` can be used only as an argument to `date` and `difftime`. 4680 4681 os.tmpname() *os.tmpname()* 4682 Returns a string with a file name that can be used for a temporary 4683 file. The file must be explicitly opened before its use and explicitly 4684 removed when no longer needed. 4685 4686 ============================================================================== 4687 5.9 The Debug Library *lua-lib-debug* 4688 4689 This library provides the functionality of the debug interface to Lua 4690 programs. You should exert care when using this library. The functions 4691 provided here should be used exclusively for debugging and similar tasks, such 4692 as profiling. Please resist the temptation to use them as a usual programming 4693 tool: they can be very slow. Moreover, several of its functions violate some 4694 assumptions about Lua code (e.g., that variables local to a function cannot be 4695 accessed from outside or that userdata metatables cannot be changed by Lua 4696 code) and therefore can compromise otherwise secure code. 4697 4698 All functions in this library are provided inside the `debug` table. All 4699 functions that operate over a thread have an optional first argument which is 4700 the thread to operate over. The default is always the current thread. 4701 4702 debug.debug() *debug.debug()* 4703 Enters an interactive mode with the user, running each string that the 4704 user enters. Using simple commands and other debug facilities, the 4705 user can inspect global and local variables, change their values, 4706 evaluate expressions, and so on. A line containing only the word 4707 `cont` finishes this function, so that the caller continues its 4708 execution. 4709 4710 Note that commands for `debug.debug` are not lexically nested within 4711 any function, and so have no direct access to local variables. 4712 4713 debug.getfenv(o) *debug.getfenv()* 4714 Returns the environment of object {o}. 4715 4716 debug.gethook([{thread}]) *debug.gethook()* 4717 Returns the current hook settings of the thread, as three values: the 4718 current hook function, the current hook mask, and the current hook 4719 count (as set by the `debug.sethook` function). 4720 4721 debug.getinfo([{thread},] {function} [, {what}]) *debug.getinfo()* 4722 Returns a table with information about a function. You can give the 4723 function directly, or you can give a number as the value of 4724 {function}, which means the function running at level {function} of 4725 the call stack of the given thread: level 0 is the current function 4726 (`getinfo` itself); level 1 is the function that called `getinfo`; and 4727 so on. If {function} is a number larger than the number of active 4728 functions, then `getinfo` returns `nil`. 4729 4730 The returned table may contain all the fields returned by 4731 `lua_getinfo` (see |lua_getinfo()|), with the string {what} 4732 describing which fields to fill in. The default for {what} is to get 4733 all information available, except the table of valid lines. If 4734 present, the option `f` adds a field named `func` with the function 4735 itself. If present, the option `L` adds a field named `activelines` 4736 with the table of valid lines. 4737 4738 For instance, the expression `debug.getinfo(1,"n").name` returns the 4739 name of the current function, if a reasonable name can be found, and 4740 `debug.getinfo(print)` returns a table with all available information 4741 about the `print` function. 4742 4743 debug.getlocal([{thread},] {level}, {local}) *debug.getlocal()* 4744 This function returns the name and the value of the local variable 4745 with index {local} of the function at level {level} of the stack. (The 4746 first parameter or local variable has index 1, and so on, until the 4747 last active local variable.) The function returns `nil` if there is no 4748 local variable with the given index, and raises an error when called 4749 with a {level} out of range. (You can call `debug.getinfo` 4750 |debug.getinfo()| to check whether the level is valid.) 4751 4752 Variable names starting with `(` (open parentheses) represent 4753 internal variables (loop control variables, temporaries, and C 4754 function locals). 4755 4756 debug.getmetatable({object}) *debug.getmetatable()* 4757 Returns the metatable of the given {object} or `nil` if it does not 4758 have a metatable. 4759 4760 debug.getregistry() *debug.getregistry()* 4761 Returns the registry table (see |lua-registry|). 4762 4763 debug.getupvalue({func}, {up}) *debug.getupvalue()* 4764 This function returns the name and the value of the upvalue with index 4765 {up} of the function {func}. The function returns `nil` if there is no 4766 upvalue with the given index. 4767 4768 debug.setfenv({object}, {table}) *debug.setfenv()* 4769 Sets the environment of the given {object} to the given {table}. 4770 Returns {object}. 4771 4772 debug.sethook([{thread},] {hook}, {mask} [, {count}]) *debug.sethook()* 4773 Sets the given function as a hook. The string {mask} and the number 4774 {count} describe when the hook will be called. The string mask may 4775 have the following characters, with the given meaning: 4776 4777 - `"c"` : The hook is called every time Lua calls a function; 4778 - `"r"` : The hook is called every time Lua returns from a function; 4779 - `"l"` : The hook is called every time Lua enters a new line of 4780 code. 4781 4782 With a {count} different from zero, the hook is called after every 4783 {count} instructions. 4784 4785 When called without arguments, the `debug.sethook` turns off the hook. 4786 4787 When the hook is called, its first parameter is a string describing 4788 the event that triggered its call: `"call"`, `"return"` (or 4789 `"tail return"`), `"line"`, and `"count"`. For line events, the hook also 4790 gets the new line number as its second parameter. Inside a hook, you 4791 can call `getinfo` with level 2 to get more information about the 4792 running function (level 0 is the `getinfo` function, and level 1 is 4793 the hook function), unless the event is `"tail return"`. In this case, 4794 Lua is only simulating the return, and a call to `getinfo` will return 4795 invalid data. 4796 4797 debug.setlocal([{thread},] {level}, {local}, {value}) *debug.setlocal()* 4798 This function assigns the value {value} to the local variable with 4799 index {local} of the function at level {level} of the stack. The 4800 function returns `nil` if there is no local variable with the given 4801 index, and raises an error when called with a {level} out of range. 4802 (You can call `getinfo` to check whether the level is valid.) 4803 Otherwise, it returns the name of the local variable. 4804 4805 debug.setmetatable({object}, {table}) *debug.setmetatable()* 4806 Sets the metatable for the given {object} to the given {table} (which 4807 can be `nil`). 4808 4809 debug.setupvalue({func}, {up}, {value}) *debug.setupvalue()* 4810 This function assigns the value {value} to the upvalue with index {up} 4811 of the function {func}. The function returns `nil` if there is no 4812 upvalue with the given index. Otherwise, it returns the name of the 4813 upvalue. 4814 4815 debug.traceback([{thread},] [{message} [,{level}]]) *debug.traceback()* 4816 Returns a string with a traceback of the call stack. An optional 4817 {message} string is appended at the beginning of the traceback. An 4818 optional {level} number tells at which level to start the traceback 4819 (default is 1, the function calling `traceback`). 4820 4821 ============================================================================== 4822 A BIBLIOGRAPHY *lua-ref-bibliography* 4823 4824 This help file is a minor adaptation from this main reference: 4825 4826 - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., 4827 "Lua: 5.1 reference manual", https://www.lua.org/manual/5.1/manual.html 4828 4829 Lua is discussed in these references: 4830 4831 - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., 4832 "Lua --- an extensible extension language". 4833 "Software: Practice & Experience" 26, 6 (1996) 635-652. 4834 4835 - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., 4836 "The design and implementation of a language for extending applications". 4837 "Proc. of XXI Brazilian Seminar on Software and Hardware" (1994) 273-283. 4838 4839 - L. H. de Figueiredo, R. Ierusalimschy, and W. Celes., 4840 "Lua: an extensible embedded language". 4841 "Dr. Dobb's Journal" 21, 12 (Dec 1996) 26-33. 4842 4843 - R. Ierusalimschy, L. H. de Figueiredo, and W. Celes., 4844 "The evolution of an extension language: a history of Lua". 4845 "Proc. of V Brazilian Symposium on Programming Languages" (2001) B-14-B-28. 4846 4847 ============================================================================== 4848 B COPYRIGHT AND LICENSES *lua-ref-copyright* 4849 4850 This help file has the same copyright and license as Lua 5.1 and the Lua 5.1 4851 manual: 4852 4853 Copyright (c) 1994-2006 Lua.org, PUC-Rio. 4854 4855 Permission is hereby granted, free of charge, to any person obtaining a copy 4856 of this software and associated documentation files (the "Software"), to deal 4857 in the Software without restriction, including without limitation the rights 4858 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 4859 copies of the Software, and to permit persons to whom the Software is 4860 furnished to do so, subject to the following conditions: 4861 4862 The above copyright notice and this permission notice shall be included in all 4863 copies or substantial portions of the Software. 4864 4865 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 4866 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 4867 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 4868 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 4869 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 4870 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 4871 SOFTWARE. 4872 4873 ============================================================================== 4874 C LUAREF DOC *lua-ref-doc* 4875 4876 This is a Vim help file containing a reference for Lua 5.1, and it is -- with 4877 a few exceptions and adaptations -- a copy of the Lua 5.1 Reference Manual 4878 (see |lua-ref-bibliography|). For usage information, refer to 4879 |lua-ref-doc|. For copyright information, see |lua-ref-copyright|. 4880 4881 The main ideas and concepts on how to implement this reference were taken from 4882 Christian Habermann's CRefVim project 4883 (https://www.vim.org/scripts/script.php?script_id=614). 4884 4885 Adapted for bundled Nvim documentation; the original plugin can be found at 4886 https://www.vim.org/scripts/script.php?script_id=1291 4887 4888 vim:tw=78:ts=4:ft=help:norl:et