1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2<HTML> 3<HEAD> 4<TITLE>Lua 5.3 Reference Manual</TITLE> 5<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css"> 6<LINK REL="stylesheet" TYPE="text/css" HREF="manual.css"> 7<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1"> 8</HEAD> 9 10<BODY> 11 12<H1> 13<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A> 14Lua 5.3 Reference Manual 15</H1> 16 17<P> 18by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes 19 20<P> 21<SMALL> 22Copyright © 2015 Lua.org, PUC-Rio. 23Freely available under the terms of the 24<a href="http://www.lua.org/license.html">Lua license</a>. 25</SMALL> 26 27<DIV CLASS="menubar"> 28<A HREF="contents.html#contents">contents</A> 29· 30<A HREF="contents.html#index">index</A> 31· 32<A HREF="http://www.lua.org/manual/">other versions</A> 33</DIV> 34 35<!-- ====================================================================== --> 36<p> 37 38<!-- Id: manual.of,v 1.151 2015/06/10 21:08:57 roberto Exp --> 39 40 41 42 43<h1>1 – <a name="1">Introduction</a></h1> 44 45<p> 46Lua is an extension programming language designed to support 47general procedural programming with data description 48facilities. 49Lua also offers good support for object-oriented programming, 50functional programming, and data-driven programming. 51Lua is intended to be used as a powerful, lightweight, 52embeddable scripting language for any program that needs one. 53Lua is implemented as a library, written in <em>clean C</em>, 54the common subset of Standard C and C++. 55 56 57<p> 58As an extension language, Lua has no notion of a "main" program: 59it only works <em>embedded</em> in a host client, 60called the <em>embedding program</em> or simply the <em>host</em>. 61The host program can invoke functions to execute a piece of Lua code, 62can write and read Lua variables, 63and can register C functions to be called by Lua code. 64Through the use of C functions, Lua can be augmented to cope with 65a wide range of different domains, 66thus creating customized programming languages sharing a syntactical framework. 67The Lua distribution includes a sample host program called <code>lua</code>, 68which uses the Lua library to offer a complete, standalone Lua interpreter, 69for interactive or batch use. 70 71 72<p> 73Lua is free software, 74and is provided as usual with no guarantees, 75as stated in its license. 76The implementation described in this manual is available 77at Lua's official web site, <code>www.lua.org</code>. 78 79 80<p> 81Like any other reference manual, 82this document is dry in places. 83For a discussion of the decisions behind the design of Lua, 84see the technical papers available at Lua's web site. 85For a detailed introduction to programming in Lua, 86see Roberto's book, <em>Programming in Lua</em>. 87 88 89 90<h1>2 – <a name="2">Basic Concepts</a></h1> 91 92<p> 93This section describes the basic concepts of the language. 94 95 96 97<h2>2.1 – <a name="2.1">Values and Types</a></h2> 98 99<p> 100Lua is a <em>dynamically typed language</em>. 101This means that 102variables do not have types; only values do. 103There are no type definitions in the language. 104All values carry their own type. 105 106 107<p> 108All values in Lua are <em>first-class values</em>. 109This means that all values can be stored in variables, 110passed as arguments to other functions, and returned as results. 111 112 113<p> 114There are eight basic types in Lua: 115<em>nil</em>, <em>boolean</em>, <em>number</em>, 116<em>string</em>, <em>function</em>, <em>userdata</em>, 117<em>thread</em>, and <em>table</em>. 118The type <em>nil</em> has one single value, <b>nil</b>, 119whose main property is to be different from any other value; 120it usually represents the absence of a useful value. 121The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>. 122Both <b>nil</b> and <b>false</b> make a condition false; 123any other value makes it true. 124The type <em>number</em> represents both 125integer numbers and real (floating-point) numbers. 126The type <em>string</em> represents immutable sequences of bytes. 127 128Lua is 8-bit clean: 129strings can contain any 8-bit value, 130including embedded zeros ('<code>\0</code>'). 131Lua is also encoding-agnostic; 132it makes no assumptions about the contents of a string. 133 134 135<p> 136The type <em>number</em> uses two internal representations, 137or two subtypes, 138one called <em>integer</em> and the other called <em>float</em>. 139Lua has explicit rules about when each representation is used, 140but it also converts between them automatically as needed (see <a href="#3.4.3">§3.4.3</a>). 141Therefore, 142the programmer may choose to mostly ignore the difference 143between integers and floats 144or to assume complete control over the representation of each number. 145Standard Lua uses 64-bit integers and double-precision (64-bit) floats, 146but you can also compile Lua so that it 147uses 32-bit integers and/or single-precision (32-bit) floats. 148The option with 32 bits for both integers and floats 149is particularly attractive 150for small machines and embedded systems. 151(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.) 152 153 154<p> 155Lua can call (and manipulate) functions written in Lua and 156functions written in C (see <a href="#3.4.10">§3.4.10</a>). 157Both are represented by the type <em>function</em>. 158 159 160<p> 161The type <em>userdata</em> is provided to allow arbitrary C data to 162be stored in Lua variables. 163A userdata value represents a block of raw memory. 164There are two kinds of userdata: 165<em>full userdata</em>, 166which is an object with a block of memory managed by Lua, 167and <em>light userdata</em>, 168which is simply a C pointer value. 169Userdata has no predefined operations in Lua, 170except assignment and identity test. 171By using <em>metatables</em>, 172the programmer can define operations for full userdata values 173(see <a href="#2.4">§2.4</a>). 174Userdata values cannot be created or modified in Lua, 175only through the C API. 176This guarantees the integrity of data owned by the host program. 177 178 179<p> 180The type <em>thread</em> represents independent threads of execution 181and it is used to implement coroutines (see <a href="#2.6">§2.6</a>). 182Lua threads are not related to operating-system threads. 183Lua supports coroutines on all systems, 184even those that do not support threads natively. 185 186 187<p> 188The type <em>table</em> implements associative arrays, 189that is, arrays that can be indexed not only with numbers, 190but with any Lua value except <b>nil</b> and NaN. 191(<em>Not a Number</em> is a special value used to represent 192undefined or unrepresentable numerical results, such as <code>0/0</code>.) 193Tables can be <em>heterogeneous</em>; 194that is, they can contain values of all types (except <b>nil</b>). 195Any key with value <b>nil</b> is not considered part of the table. 196Conversely, any key that is not part of a table has 197an associated value <b>nil</b>. 198 199 200<p> 201Tables are the sole data-structuring mechanism in Lua; 202they can be used to represent ordinary arrays, sequences, 203symbol tables, sets, records, graphs, trees, etc. 204To represent records, Lua uses the field name as an index. 205The language supports this representation by 206providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>. 207There are several convenient ways to create tables in Lua 208(see <a href="#3.4.9">§3.4.9</a>). 209 210 211<p> 212We use the term <em>sequence</em> to denote a table where 213the set of all positive numeric keys is equal to {1..<em>n</em>} 214for some non-negative integer <em>n</em>, 215which is called the length of the sequence (see <a href="#3.4.7">§3.4.7</a>). 216 217 218<p> 219Like indices, 220the values of table fields can be of any type. 221In particular, 222because functions are first-class values, 223table fields can contain functions. 224Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">§3.4.11</a>). 225 226 227<p> 228The indexing of tables follows 229the definition of raw equality in the language. 230The expressions <code>a[i]</code> and <code>a[j]</code> 231denote the same table element 232if and only if <code>i</code> and <code>j</code> are raw equal 233(that is, equal without metamethods). 234In particular, floats with integral values 235are equal to their respective integers 236(e.g., <code>1.0 == 1</code>). 237To avoid ambiguities, 238any float with integral value used as a key 239is converted to its respective integer. 240For instance, if you write <code>a[2.0] = true</code>, 241the actual key inserted into the table will be the 242integer <code>2</code>. 243(On the other hand, 2442 and "<code>2</code>" are different Lua values and therefore 245denote different table entries.) 246 247 248<p> 249Tables, functions, threads, and (full) userdata values are <em>objects</em>: 250variables do not actually <em>contain</em> these values, 251only <em>references</em> to them. 252Assignment, parameter passing, and function returns 253always manipulate references to such values; 254these operations do not imply any kind of copy. 255 256 257<p> 258The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type 259of a given value (see <a href="#6.1">§6.1</a>). 260 261 262 263 264 265<h2>2.2 – <a name="2.2">Environments and the Global Environment</a></h2> 266 267<p> 268As will be discussed in <a href="#3.2">§3.2</a> and <a href="#3.3.3">§3.3.3</a>, 269any reference to a free name 270(that is, a name not bound to any declaration) <code>var</code> 271is syntactically translated to <code>_ENV.var</code>. 272Moreover, every chunk is compiled in the scope of 273an external local variable named <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>), 274so <code>_ENV</code> itself is never a free name in a chunk. 275 276 277<p> 278Despite the existence of this external <code>_ENV</code> variable and 279the translation of free names, 280<code>_ENV</code> is a completely regular name. 281In particular, 282you can define new variables and parameters with that name. 283Each reference to a free name uses the <code>_ENV</code> that is 284visible at that point in the program, 285following the usual visibility rules of Lua (see <a href="#3.5">§3.5</a>). 286 287 288<p> 289Any table used as the value of <code>_ENV</code> is called an <em>environment</em>. 290 291 292<p> 293Lua keeps a distinguished environment called the <em>global environment</em>. 294This value is kept at a special index in the C registry (see <a href="#4.5">§4.5</a>). 295In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value. 296(<a href="#pdf-_G"><code>_G</code></a> is never used internally.) 297 298 299<p> 300When Lua loads a chunk, 301the default value for its <code>_ENV</code> upvalue 302is the global environment (see <a href="#pdf-load"><code>load</code></a>). 303Therefore, by default, 304free names in Lua code refer to entries in the global environment 305(and, therefore, they are also called <em>global variables</em>). 306Moreover, all standard libraries are loaded in the global environment 307and some functions there operate on that environment. 308You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>) 309to load a chunk with a different environment. 310(In C, you have to load the chunk and then change the value 311of its first upvalue.) 312 313 314 315 316 317<h2>2.3 – <a name="2.3">Error Handling</a></h2> 318 319<p> 320Because Lua is an embedded extension language, 321all Lua actions start from C code in the host program 322calling a function from the Lua library. 323(When you use Lua standalone, 324the <code>lua</code> application is the host program.) 325Whenever an error occurs during 326the compilation or execution of a Lua chunk, 327control returns to the host, 328which can take appropriate measures 329(such as printing an error message). 330 331 332<p> 333Lua code can explicitly generate an error by calling the 334<a href="#pdf-error"><code>error</code></a> function. 335If you need to catch errors in Lua, 336you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a> 337to call a given function in <em>protected mode</em>. 338 339 340<p> 341Whenever there is an error, 342an <em>error object</em> (also called an <em>error message</em>) 343is propagated with information about the error. 344Lua itself only generates errors whose error object is a string, 345but programs may generate errors with 346any value as the error object. 347It is up to the Lua program or its host to handle such error objects. 348 349 350<p> 351When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>, 352you may give a <em>message handler</em> 353to be called in case of errors. 354This function is called with the original error message 355and returns a new error message. 356It is called before the error unwinds the stack, 357so that it can gather more information about the error, 358for instance by inspecting the stack and creating a stack traceback. 359This message handler is still protected by the protected call; 360so, an error inside the message handler 361will call the message handler again. 362If this loop goes on for too long, 363Lua breaks it and returns an appropriate message. 364 365 366 367 368 369<h2>2.4 – <a name="2.4">Metatables and Metamethods</a></h2> 370 371<p> 372Every value in Lua can have a <em>metatable</em>. 373This <em>metatable</em> is an ordinary Lua table 374that defines the behavior of the original value 375under certain special operations. 376You can change several aspects of the behavior 377of operations over a value by setting specific fields in its metatable. 378For instance, when a non-numeric value is the operand of an addition, 379Lua checks for a function in the field "<code>__add</code>" of the value's metatable. 380If it finds one, 381Lua calls this function to perform the addition. 382 383 384<p> 385The keys in a metatable are derived from the <em>event</em> names; 386the corresponding values are called <em>metamethods</em>. 387In the previous example, the event is <code>"add"</code> 388and the metamethod is the function that performs the addition. 389 390 391<p> 392You can query the metatable of any value 393using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function. 394 395 396<p> 397You can replace the metatable of tables 398using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function. 399You cannot change the metatable of other types from Lua code 400(except by using the debug library (<a href="#6.10">§6.10</a>)); 401you must use the C API for that. 402 403 404<p> 405Tables and full userdata have individual metatables 406(although multiple tables and userdata can share their metatables). 407Values of all other types share one single metatable per type; 408that is, there is one single metatable for all numbers, 409one for all strings, etc. 410By default, a value has no metatable, 411but the string library sets a metatable for the string type (see <a href="#6.4">§6.4</a>). 412 413 414<p> 415A metatable controls how an object behaves in 416arithmetic operations, bitwise operations, 417order comparisons, concatenation, length operation, calls, and indexing. 418A metatable also can define a function to be called 419when a userdata or a table is garbage collected (<a href="#2.5">§2.5</a>). 420 421 422<p> 423A detailed list of events controlled by metatables is given next. 424Each operation is identified by its corresponding event name. 425The key for each event is a string with its name prefixed by 426two underscores, '<code>__</code>'; 427for instance, the key for operation "add" is the 428string "<code>__add</code>". 429Note that queries for metamethods are always raw; 430the access to a metamethod does not invoke other metamethods. 431 432 433<p> 434For the unary operators (negation, length, and bitwise not), 435the metamethod is computed and called with a dummy second operand, 436equal to the first one. 437This extra operand is only to simplify Lua's internals 438(by making these operators behave like a binary operation) 439and may be removed in future versions. 440(For most uses this extra operand is irrelevant.) 441 442 443 444<ul> 445 446<li><b>"add": </b> 447the <code>+</code> operation. 448 449If any operand for an addition is not a number 450(nor a string coercible to a number), 451Lua will try to call a metamethod. 452First, Lua will check the first operand (even if it is valid). 453If that operand does not define a metamethod for the "<code>__add</code>" event, 454then Lua will check the second operand. 455If Lua can find a metamethod, 456it calls the metamethod with the two operands as arguments, 457and the result of the call 458(adjusted to one value) 459is the result of the operation. 460Otherwise, 461it raises an error. 462</li> 463 464<li><b>"sub": </b> 465the <code>-</code> operation. 466 467Behavior similar to the "add" operation. 468</li> 469 470<li><b>"mul": </b> 471the <code>*</code> operation. 472 473Behavior similar to the "add" operation. 474</li> 475 476<li><b>"div": </b> 477the <code>/</code> operation. 478 479Behavior similar to the "add" operation. 480</li> 481 482<li><b>"mod": </b> 483the <code>%</code> operation. 484 485Behavior similar to the "add" operation. 486</li> 487 488<li><b>"pow": </b> 489the <code>^</code> (exponentiation) operation. 490 491Behavior similar to the "add" operation. 492</li> 493 494<li><b>"unm": </b> 495the <code>-</code> (unary minus) operation. 496 497Behavior similar to the "add" operation. 498</li> 499 500<li><b>"idiv": </b> 501the <code>//</code> (floor division) operation. 502 503Behavior similar to the "add" operation. 504</li> 505 506<li><b>"band": </b> 507the <code>&</code> (bitwise and) operation. 508 509Behavior similar to the "add" operation, 510except that Lua will try a metamethod 511if any operand is neither an integer 512nor a value coercible to an integer (see <a href="#3.4.3">§3.4.3</a>). 513</li> 514 515<li><b>"bor": </b> 516the <code>|</code> (bitwise or) operation. 517 518Behavior similar to the "band" operation. 519</li> 520 521<li><b>"bxor": </b> 522the <code>~</code> (bitwise exclusive or) operation. 523 524Behavior similar to the "band" operation. 525</li> 526 527<li><b>"bnot": </b> 528the <code>~</code> (bitwise unary not) operation. 529 530Behavior similar to the "band" operation. 531</li> 532 533<li><b>"shl": </b> 534the <code><<</code> (bitwise left shift) operation. 535 536Behavior similar to the "band" operation. 537</li> 538 539<li><b>"shr": </b> 540the <code>>></code> (bitwise right shift) operation. 541 542Behavior similar to the "band" operation. 543</li> 544 545<li><b>"concat": </b> 546the <code>..</code> (concatenation) operation. 547 548Behavior similar to the "add" operation, 549except that Lua will try a metamethod 550if any operand is neither a string nor a number 551(which is always coercible to a string). 552</li> 553 554<li><b>"len": </b> 555the <code>#</code> (length) operation. 556 557If the object is not a string, 558Lua will try its metamethod. 559If there is a metamethod, 560Lua calls it with the object as argument, 561and the result of the call 562(always adjusted to one value) 563is the result of the operation. 564If there is no metamethod but the object is a table, 565then Lua uses the table length operation (see <a href="#3.4.7">§3.4.7</a>). 566Otherwise, Lua raises an error. 567</li> 568 569<li><b>"eq": </b> 570the <code>==</code> (equal) operation. 571 572Behavior similar to the "add" operation, 573except that Lua will try a metamethod only when the values 574being compared are either both tables or both full userdata 575and they are not primitively equal. 576The result of the call is always converted to a boolean. 577</li> 578 579<li><b>"lt": </b> 580the <code><</code> (less than) operation. 581 582Behavior similar to the "add" operation, 583except that Lua will try a metamethod only when the values 584being compared are neither both numbers nor both strings. 585The result of the call is always converted to a boolean. 586</li> 587 588<li><b>"le": </b> 589the <code><=</code> (less equal) operation. 590 591Unlike other operations, 592The less-equal operation can use two different events. 593First, Lua looks for the "<code>__le</code>" metamethod in both operands, 594like in the "lt" operation. 595If it cannot find such a metamethod, 596then it will try the "<code>__lt</code>" event, 597assuming that <code>a <= b</code> is equivalent to <code>not (b < a)</code>. 598As with the other comparison operators, 599the result is always a boolean. 600(This use of the "<code>__lt</code>" event can be removed in future versions; 601it is also slower than a real "<code>__le</code>" metamethod.) 602</li> 603 604<li><b>"index": </b> 605The indexing access <code>table[key]</code>. 606 607This event happens when <code>table</code> is not a table or 608when <code>key</code> is not present in <code>table</code>. 609The metamethod is looked up in <code>table</code>. 610 611 612<p> 613Despite the name, 614the metamethod for this event can be either a function or a table. 615If it is a function, 616it is called with <code>table</code> and <code>key</code> as arguments. 617If it is a table, 618the final result is the result of indexing this table with <code>key</code>. 619(This indexing is regular, not raw, 620and therefore can trigger another metamethod.) 621</li> 622 623<li><b>"newindex": </b> 624The indexing assignment <code>table[key] = value</code>. 625 626Like the index event, 627this event happens when <code>table</code> is not a table or 628when <code>key</code> is not present in <code>table</code>. 629The metamethod is looked up in <code>table</code>. 630 631 632<p> 633Like with indexing, 634the metamethod for this event can be either a function or a table. 635If it is a function, 636it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments. 637If it is a table, 638Lua does an indexing assignment to this table with the same key and value. 639(This assignment is regular, not raw, 640and therefore can trigger another metamethod.) 641 642 643<p> 644Whenever there is a "newindex" metamethod, 645Lua does not perform the primitive assignment. 646(If necessary, 647the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a> 648to do the assignment.) 649</li> 650 651<li><b>"call": </b> 652The call operation <code>func(args)</code>. 653 654This event happens when Lua tries to call a non-function value 655(that is, <code>func</code> is not a function). 656The metamethod is looked up in <code>func</code>. 657If present, 658the metamethod is called with <code>func</code> as its first argument, 659followed by the arguments of the original call (<code>args</code>). 660</li> 661 662</ul> 663 664<p> 665It is a good practice to add all needed metamethods to a table 666before setting it as a metatable of some object. 667In particular, the "<code>__gc</code>" metamethod works only when this order 668is followed (see <a href="#2.5.1">§2.5.1</a>). 669 670 671 672 673 674<h2>2.5 – <a name="2.5">Garbage Collection</a></h2> 675 676<p> 677Lua performs automatic memory management. 678This means that 679you do not have to worry about allocating memory for new objects 680or freeing it when the objects are no longer needed. 681Lua manages memory automatically by running 682a <em>garbage collector</em> to collect all <em>dead objects</em> 683(that is, objects that are no longer accessible from Lua). 684All memory used by Lua is subject to automatic management: 685strings, tables, userdata, functions, threads, internal structures, etc. 686 687 688<p> 689Lua implements an incremental mark-and-sweep collector. 690It uses two numbers to control its garbage-collection cycles: 691the <em>garbage-collector pause</em> and 692the <em>garbage-collector step multiplier</em>. 693Both use percentage points as units 694(e.g., a value of 100 means an internal value of 1). 695 696 697<p> 698The garbage-collector pause 699controls how long the collector waits before starting a new cycle. 700Larger values make the collector less aggressive. 701Values smaller than 100 mean the collector will not wait to 702start a new cycle. 703A value of 200 means that the collector waits for the total memory in use 704to double before starting a new cycle. 705 706 707<p> 708The garbage-collector step multiplier 709controls the relative speed of the collector relative to 710memory allocation. 711Larger values make the collector more aggressive but also increase 712the size of each incremental step. 713You should not use values smaller than 100, 714because they make the collector too slow and 715can result in the collector never finishing a cycle. 716The default is 200, 717which means that the collector runs at "twice" 718the speed of memory allocation. 719 720 721<p> 722If you set the step multiplier to a very large number 723(larger than 10% of the maximum number of 724bytes that the program may use), 725the collector behaves like a stop-the-world collector. 726If you then set the pause to 200, 727the collector behaves as in old Lua versions, 728doing a complete collection every time Lua doubles its 729memory usage. 730 731 732<p> 733You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C 734or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua. 735You can also use these functions to control 736the collector directly (e.g., stop and restart it). 737 738 739 740<h3>2.5.1 – <a name="2.5.1">Garbage-Collection Metamethods</a></h3> 741 742<p> 743You can set garbage-collector metamethods for tables 744and, using the C API, 745for full userdata (see <a href="#2.4">§2.4</a>). 746These metamethods are also called <em>finalizers</em>. 747Finalizers allow you to coordinate Lua's garbage collection 748with external resource management 749(such as closing files, network or database connections, 750or freeing your own memory). 751 752 753<p> 754For an object (table or userdata) to be finalized when collected, 755you must <em>mark</em> it for finalization. 756 757You mark an object for finalization when you set its metatable 758and the metatable has a field indexed by the string "<code>__gc</code>". 759Note that if you set a metatable without a <code>__gc</code> field 760and later create that field in the metatable, 761the object will not be marked for finalization. 762 763 764<p> 765When a marked object becomes garbage, 766it is not collected immediately by the garbage collector. 767Instead, Lua puts it in a list. 768After the collection, 769Lua goes through that list. 770For each object in the list, 771it checks the object's <code>__gc</code> metamethod: 772If it is a function, 773Lua calls it with the object as its single argument; 774if the metamethod is not a function, 775Lua simply ignores it. 776 777 778<p> 779At the end of each garbage-collection cycle, 780the finalizers for objects are called in 781the reverse order that the objects were marked for finalization, 782among those collected in that cycle; 783that is, the first finalizer to be called is the one associated 784with the object marked last in the program. 785The execution of each finalizer may occur at any point during 786the execution of the regular code. 787 788 789<p> 790Because the object being collected must still be used by the finalizer, 791that object (and other objects accessible only through it) 792must be <em>resurrected</em> by Lua. 793Usually, this resurrection is transient, 794and the object memory is freed in the next garbage-collection cycle. 795However, if the finalizer stores the object in some global place 796(e.g., a global variable), 797then the resurrection is permanent. 798Moreover, if the finalizer marks a finalizing object for finalization again, 799its finalizer will be called again in the next cycle where the 800object is unreachable. 801In any case, 802the object memory is freed only in a GC cycle where 803the object is unreachable and not marked for finalization. 804 805 806<p> 807When you close a state (see <a href="#lua_close"><code>lua_close</code></a>), 808Lua calls the finalizers of all objects marked for finalization, 809following the reverse order that they were marked. 810If any finalizer marks objects for collection during that phase, 811these marks have no effect. 812 813 814 815 816 817<h3>2.5.2 – <a name="2.5.2">Weak Tables</a></h3> 818 819<p> 820A <em>weak table</em> is a table whose elements are 821<em>weak references</em>. 822A weak reference is ignored by the garbage collector. 823In other words, 824if the only references to an object are weak references, 825then the garbage collector will collect that object. 826 827 828<p> 829A weak table can have weak keys, weak values, or both. 830A table with weak values allows the collection of its values, 831but prevents the collection of its keys. 832A table with both weak keys and weak values allows the collection of 833both keys and values. 834In any case, if either the key or the value is collected, 835the whole pair is removed from the table. 836The weakness of a table is controlled by the 837<code>__mode</code> field of its metatable. 838If the <code>__mode</code> field is a string containing the character '<code>k</code>', 839the keys in the table are weak. 840If <code>__mode</code> contains '<code>v</code>', 841the values in the table are weak. 842 843 844<p> 845A table with weak keys and strong values 846is also called an <em>ephemeron table</em>. 847In an ephemeron table, 848a value is considered reachable only if its key is reachable. 849In particular, 850if the only reference to a key comes through its value, 851the pair is removed. 852 853 854<p> 855Any change in the weakness of a table may take effect only 856at the next collect cycle. 857In particular, if you change the weakness to a stronger mode, 858Lua may still collect some items from that table 859before the change takes effect. 860 861 862<p> 863Only objects that have an explicit construction 864are removed from weak tables. 865Values, such as numbers and light C functions, 866are not subject to garbage collection, 867and therefore are not removed from weak tables 868(unless their associated values are collected). 869Although strings are subject to garbage collection, 870they do not have an explicit construction, 871and therefore are not removed from weak tables. 872 873 874<p> 875Resurrected objects 876(that is, objects being finalized 877and objects accessible only through objects being finalized) 878have a special behavior in weak tables. 879They are removed from weak values before running their finalizers, 880but are removed from weak keys only in the next collection 881after running their finalizers, when such objects are actually freed. 882This behavior allows the finalizer to access properties 883associated with the object through weak tables. 884 885 886<p> 887If a weak table is among the resurrected objects in a collection cycle, 888it may not be properly cleared until the next cycle. 889 890 891 892 893 894 895 896<h2>2.6 – <a name="2.6">Coroutines</a></h2> 897 898<p> 899Lua supports coroutines, 900also called <em>collaborative multithreading</em>. 901A coroutine in Lua represents an independent thread of execution. 902Unlike threads in multithread systems, however, 903a coroutine only suspends its execution by explicitly calling 904a yield function. 905 906 907<p> 908You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>. 909Its sole argument is a function 910that is the main function of the coroutine. 911The <code>create</code> function only creates a new coroutine and 912returns a handle to it (an object of type <em>thread</em>); 913it does not start the coroutine. 914 915 916<p> 917You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. 918When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, 919passing as its first argument 920a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>, 921the coroutine starts its execution by 922calling its main function. 923Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed 924as arguments to that function. 925After the coroutine starts running, 926it runs until it terminates or <em>yields</em>. 927 928 929<p> 930A coroutine can terminate its execution in two ways: 931normally, when its main function returns 932(explicitly or implicitly, after the last instruction); 933and abnormally, if there is an unprotected error. 934In case of normal termination, 935<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>, 936plus any values returned by the coroutine main function. 937In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b> 938plus an error message. 939 940 941<p> 942A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>. 943When a coroutine yields, 944the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately, 945even if the yield happens inside nested function calls 946(that is, not in the main function, 947but in a function directly or indirectly called by the main function). 948In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>, 949plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>. 950The next time you resume the same coroutine, 951it continues its execution from the point where it yielded, 952with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra 953arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. 954 955 956<p> 957Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>, 958the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine, 959but instead of returning the coroutine itself, 960it returns a function that, when called, resumes the coroutine. 961Any arguments passed to this function 962go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. 963<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, 964except the first one (the boolean error code). 965Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, 966<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors; 967any error is propagated to the caller. 968 969 970<p> 971As an example of how coroutines work, 972consider the following code: 973 974<pre> 975 function foo (a) 976 print("foo", a) 977 return coroutine.yield(2*a) 978 end 979 980 co = coroutine.create(function (a,b) 981 print("co-body", a, b) 982 local r = foo(a+1) 983 print("co-body", r) 984 local r, s = coroutine.yield(a+b, a-b) 985 print("co-body", r, s) 986 return b, "end" 987 end) 988 989 print("main", coroutine.resume(co, 1, 10)) 990 print("main", coroutine.resume(co, "r")) 991 print("main", coroutine.resume(co, "x", "y")) 992 print("main", coroutine.resume(co, "x", "y")) 993</pre><p> 994When you run it, it produces the following output: 995 996<pre> 997 co-body 1 10 998 foo 2 999 main true 4 1000 co-body r 1001 main true 11 -9 1002 co-body x y 1003 main true 10 end 1004 main false cannot resume dead coroutine 1005</pre> 1006 1007<p> 1008You can also create and manipulate coroutines through the C API: 1009see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>, 1010and <a href="#lua_yield"><code>lua_yield</code></a>. 1011 1012 1013 1014 1015 1016<h1>3 – <a name="3">The Language</a></h1> 1017 1018<p> 1019This section describes the lexis, the syntax, and the semantics of Lua. 1020In other words, 1021this section describes 1022which tokens are valid, 1023how they can be combined, 1024and what their combinations mean. 1025 1026 1027<p> 1028Language constructs will be explained using the usual extended BNF notation, 1029in which 1030{<em>a</em>} means 0 or more <em>a</em>'s, and 1031[<em>a</em>] means an optional <em>a</em>. 1032Non-terminals are shown like non-terminal, 1033keywords are shown like <b>kword</b>, 1034and other terminal symbols are shown like ‘<b>=</b>’. 1035The complete syntax of Lua can be found in <a href="#9">§9</a> 1036at the end of this manual. 1037 1038 1039 1040<h2>3.1 – <a name="3.1">Lexical Conventions</a></h2> 1041 1042<p> 1043Lua is a free-form language. 1044It ignores spaces (including new lines) and comments 1045between lexical elements (tokens), 1046except as delimiters between names and keywords. 1047 1048 1049<p> 1050<em>Names</em> 1051(also called <em>identifiers</em>) 1052in Lua can be any string of letters, 1053digits, and underscores, 1054not beginning with a digit. 1055Identifiers are used to name variables, table fields, and labels. 1056 1057 1058<p> 1059The following <em>keywords</em> are reserved 1060and cannot be used as names: 1061 1062 1063<pre> 1064 and break do else elseif end 1065 false for function goto if in 1066 local nil not or repeat return 1067 then true until while 1068</pre> 1069 1070<p> 1071Lua is a case-sensitive language: 1072<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code> 1073are two different, valid names. 1074As a convention, 1075programs should avoid creating 1076names that start with an underscore followed by 1077one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>). 1078 1079 1080<p> 1081The following strings denote other tokens: 1082 1083<pre> 1084 + - * / % ^ # 1085 & ~ | << >> // 1086 == ~= <= >= < > = 1087 ( ) { } [ ] :: 1088 ; : , . .. ... 1089</pre> 1090 1091<p> 1092<em>Literal strings</em> 1093can be delimited by matching single or double quotes, 1094and can contain the following C-like escape sequences: 1095'<code>\a</code>' (bell), 1096'<code>\b</code>' (backspace), 1097'<code>\f</code>' (form feed), 1098'<code>\n</code>' (newline), 1099'<code>\r</code>' (carriage return), 1100'<code>\t</code>' (horizontal tab), 1101'<code>\v</code>' (vertical tab), 1102'<code>\\</code>' (backslash), 1103'<code>\"</code>' (quotation mark [double quote]), 1104and '<code>\'</code>' (apostrophe [single quote]). 1105A backslash followed by a real newline 1106results in a newline in the string. 1107The escape sequence '<code>\z</code>' skips the following span 1108of white-space characters, 1109including line breaks; 1110it is particularly useful to break and indent a long literal string 1111into multiple lines without adding the newlines and spaces 1112into the string contents. 1113 1114 1115<p> 1116Strings in Lua can contain any 8-bit value, including embedded zeros, 1117which can be specified as '<code>\0</code>'. 1118More generally, 1119we can specify any byte in a literal string by its numeric value. 1120This can be done 1121with the escape sequence <code>\x<em>XX</em></code>, 1122where <em>XX</em> is a sequence of exactly two hexadecimal digits, 1123or with the escape sequence <code>\<em>ddd</em></code>, 1124where <em>ddd</em> is a sequence of up to three decimal digits. 1125(Note that if a decimal escape sequence is to be followed by a digit, 1126it must be expressed using exactly three digits.) 1127 1128 1129<p> 1130The UTF-8 encoding of a Unicode character 1131can be inserted in a literal string with 1132the escape sequence <code>\u{<em>XXX</em>}</code> 1133(note the mandatory enclosing brackets), 1134where <em>XXX</em> is a sequence of one or more hexadecimal digits 1135representing the character code point. 1136 1137 1138<p> 1139Literal strings can also be defined using a long format 1140enclosed by <em>long brackets</em>. 1141We define an <em>opening long bracket of level <em>n</em></em> as an opening 1142square bracket followed by <em>n</em> equal signs followed by another 1143opening square bracket. 1144So, an opening long bracket of level 0 is written as <code>[[</code>, 1145an opening long bracket of level 1 is written as <code>[=[</code>, 1146and so on. 1147A <em>closing long bracket</em> is defined similarly; 1148for instance, 1149a closing long bracket of level 4 is written as <code>]====]</code>. 1150A <em>long literal</em> starts with an opening long bracket of any level and 1151ends at the first closing long bracket of the same level. 1152It can contain any text except a closing bracket of the same level. 1153Literals in this bracketed form can run for several lines, 1154do not interpret any escape sequences, 1155and ignore long brackets of any other level. 1156Any kind of end-of-line sequence 1157(carriage return, newline, carriage return followed by newline, 1158or newline followed by carriage return) 1159is converted to a simple newline. 1160 1161 1162<p> 1163Any byte in a literal string not 1164explicitly affected by the previous rules represents itself. 1165However, Lua opens files for parsing in text mode, 1166and the system file functions may have problems with 1167some control characters. 1168So, it is safer to represent 1169non-text data as a quoted literal with 1170explicit escape sequences for non-text characters. 1171 1172 1173<p> 1174For convenience, 1175when the opening long bracket is immediately followed by a newline, 1176the newline is not included in the string. 1177As an example, in a system using ASCII 1178(in which '<code>a</code>' is coded as 97, 1179newline is coded as 10, and '<code>1</code>' is coded as 49), 1180the five literal strings below denote the same string: 1181 1182<pre> 1183 a = 'alo\n123"' 1184 a = "alo\n123\"" 1185 a = '\97lo\10\04923"' 1186 a = [[alo 1187 123"]] 1188 a = [==[ 1189 alo 1190 123"]==] 1191</pre> 1192 1193<p> 1194A <em>numeric constant</em> (or <em>numeral</em>) 1195can be written with an optional fractional part 1196and an optional decimal exponent, 1197marked by a letter '<code>e</code>' or '<code>E</code>'. 1198Lua also accepts hexadecimal constants, 1199which start with <code>0x</code> or <code>0X</code>. 1200Hexadecimal constants also accept an optional fractional part 1201plus an optional binary exponent, 1202marked by a letter '<code>p</code>' or '<code>P</code>'. 1203A numeric constant with a fractional dot or an exponent 1204denotes a float; 1205otherwise it denotes an integer. 1206Examples of valid integer constants are 1207 1208<pre> 1209 3 345 0xff 0xBEBADA 1210</pre><p> 1211Examples of valid float constants are 1212 1213<pre> 1214 3.0 3.1416 314.16e-2 0.31416E1 34e1 1215 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 1216</pre> 1217 1218<p> 1219A <em>comment</em> starts with a double hyphen (<code>--</code>) 1220anywhere outside a string. 1221If the text immediately after <code>--</code> is not an opening long bracket, 1222the comment is a <em>short comment</em>, 1223which runs until the end of the line. 1224Otherwise, it is a <em>long comment</em>, 1225which runs until the corresponding closing long bracket. 1226Long comments are frequently used to disable code temporarily. 1227 1228 1229 1230 1231 1232<h2>3.2 – <a name="3.2">Variables</a></h2> 1233 1234<p> 1235Variables are places that store values. 1236There are three kinds of variables in Lua: 1237global variables, local variables, and table fields. 1238 1239 1240<p> 1241A single name can denote a global variable or a local variable 1242(or a function's formal parameter, 1243which is a particular kind of local variable): 1244 1245<pre> 1246 var ::= Name 1247</pre><p> 1248Name denotes identifiers, as defined in <a href="#3.1">§3.1</a>. 1249 1250 1251<p> 1252Any variable name is assumed to be global unless explicitly declared 1253as a local (see <a href="#3.3.7">§3.3.7</a>). 1254Local variables are <em>lexically scoped</em>: 1255local variables can be freely accessed by functions 1256defined inside their scope (see <a href="#3.5">§3.5</a>). 1257 1258 1259<p> 1260Before the first assignment to a variable, its value is <b>nil</b>. 1261 1262 1263<p> 1264Square brackets are used to index a table: 1265 1266<pre> 1267 var ::= prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ 1268</pre><p> 1269The meaning of accesses to table fields can be changed via metatables. 1270An access to an indexed variable <code>t[i]</code> is equivalent to 1271a call <code>gettable_event(t,i)</code>. 1272(See <a href="#2.4">§2.4</a> for a complete description of the 1273<code>gettable_event</code> function. 1274This function is not defined or callable in Lua. 1275We use it here only for explanatory purposes.) 1276 1277 1278<p> 1279The syntax <code>var.Name</code> is just syntactic sugar for 1280<code>var["Name"]</code>: 1281 1282<pre> 1283 var ::= prefixexp ‘<b>.</b>’ Name 1284</pre> 1285 1286<p> 1287An access to a global variable <code>x</code> 1288is equivalent to <code>_ENV.x</code>. 1289Due to the way that chunks are compiled, 1290<code>_ENV</code> is never a global name (see <a href="#2.2">§2.2</a>). 1291 1292 1293 1294 1295 1296<h2>3.3 – <a name="3.3">Statements</a></h2> 1297 1298<p> 1299Lua supports an almost conventional set of statements, 1300similar to those in Pascal or C. 1301This set includes 1302assignments, control structures, function calls, 1303and variable declarations. 1304 1305 1306 1307<h3>3.3.1 – <a name="3.3.1">Blocks</a></h3> 1308 1309<p> 1310A block is a list of statements, 1311which are executed sequentially: 1312 1313<pre> 1314 block ::= {stat} 1315</pre><p> 1316Lua has <em>empty statements</em> 1317that allow you to separate statements with semicolons, 1318start a block with a semicolon 1319or write two semicolons in sequence: 1320 1321<pre> 1322 stat ::= ‘<b>;</b>’ 1323</pre> 1324 1325<p> 1326Function calls and assignments 1327can start with an open parenthesis. 1328This possibility leads to an ambiguity in Lua's grammar. 1329Consider the following fragment: 1330 1331<pre> 1332 a = b + c 1333 (print or io.write)('done') 1334</pre><p> 1335The grammar could see it in two ways: 1336 1337<pre> 1338 a = b + c(print or io.write)('done') 1339 1340 a = b + c; (print or io.write)('done') 1341</pre><p> 1342The current parser always sees such constructions 1343in the first way, 1344interpreting the open parenthesis 1345as the start of the arguments to a call. 1346To avoid this ambiguity, 1347it is a good practice to always precede with a semicolon 1348statements that start with a parenthesis: 1349 1350<pre> 1351 ;(print or io.write)('done') 1352</pre> 1353 1354<p> 1355A block can be explicitly delimited to produce a single statement: 1356 1357<pre> 1358 stat ::= <b>do</b> block <b>end</b> 1359</pre><p> 1360Explicit blocks are useful 1361to control the scope of variable declarations. 1362Explicit blocks are also sometimes used to 1363add a <b>return</b> statement in the middle 1364of another block (see <a href="#3.3.4">§3.3.4</a>). 1365 1366 1367 1368 1369 1370<h3>3.3.2 – <a name="3.3.2">Chunks</a></h3> 1371 1372<p> 1373The unit of compilation of Lua is called a <em>chunk</em>. 1374Syntactically, 1375a chunk is simply a block: 1376 1377<pre> 1378 chunk ::= block 1379</pre> 1380 1381<p> 1382Lua handles a chunk as the body of an anonymous function 1383with a variable number of arguments 1384(see <a href="#3.4.11">§3.4.11</a>). 1385As such, chunks can define local variables, 1386receive arguments, and return values. 1387Moreover, such anonymous function is compiled as in the 1388scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">§2.2</a>). 1389The resulting function always has <code>_ENV</code> as its only upvalue, 1390even if it does not use that variable. 1391 1392 1393<p> 1394A chunk can be stored in a file or in a string inside the host program. 1395To execute a chunk, 1396Lua first <em>loads</em> it, 1397precompiling the chunk's code into instructions for a virtual machine, 1398and then Lua executes the compiled code 1399with an interpreter for the virtual machine. 1400 1401 1402<p> 1403Chunks can also be precompiled into binary form; 1404see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details. 1405Programs in source and compiled forms are interchangeable; 1406Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>). 1407 1408 1409 1410 1411 1412<h3>3.3.3 – <a name="3.3.3">Assignment</a></h3> 1413 1414<p> 1415Lua allows multiple assignments. 1416Therefore, the syntax for assignment 1417defines a list of variables on the left side 1418and a list of expressions on the right side. 1419The elements in both lists are separated by commas: 1420 1421<pre> 1422 stat ::= varlist ‘<b>=</b>’ explist 1423 varlist ::= var {‘<b>,</b>’ var} 1424 explist ::= exp {‘<b>,</b>’ exp} 1425</pre><p> 1426Expressions are discussed in <a href="#3.4">§3.4</a>. 1427 1428 1429<p> 1430Before the assignment, 1431the list of values is <em>adjusted</em> to the length of 1432the list of variables. 1433If there are more values than needed, 1434the excess values are thrown away. 1435If there are fewer values than needed, 1436the list is extended with as many <b>nil</b>'s as needed. 1437If the list of expressions ends with a function call, 1438then all values returned by that call enter the list of values, 1439before the adjustment 1440(except when the call is enclosed in parentheses; see <a href="#3.4">§3.4</a>). 1441 1442 1443<p> 1444The assignment statement first evaluates all its expressions 1445and only then the assignments are performed. 1446Thus the code 1447 1448<pre> 1449 i = 3 1450 i, a[i] = i+1, 20 1451</pre><p> 1452sets <code>a[3]</code> to 20, without affecting <code>a[4]</code> 1453because the <code>i</code> in <code>a[i]</code> is evaluated (to 3) 1454before it is assigned 4. 1455Similarly, the line 1456 1457<pre> 1458 x, y = y, x 1459</pre><p> 1460exchanges the values of <code>x</code> and <code>y</code>, 1461and 1462 1463<pre> 1464 x, y, z = y, z, x 1465</pre><p> 1466cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>. 1467 1468 1469<p> 1470The meaning of assignments to global variables 1471and table fields can be changed via metatables. 1472An assignment to an indexed variable <code>t[i] = val</code> is equivalent to 1473<code>settable_event(t,i,val)</code>. 1474(See <a href="#2.4">§2.4</a> for a complete description of the 1475<code>settable_event</code> function. 1476This function is not defined or callable in Lua. 1477We use it here only for explanatory purposes.) 1478 1479 1480<p> 1481An assignment to a global name <code>x = val</code> 1482is equivalent to the assignment 1483<code>_ENV.x = val</code> (see <a href="#2.2">§2.2</a>). 1484 1485 1486 1487 1488 1489<h3>3.3.4 – <a name="3.3.4">Control Structures</a></h3><p> 1490The control structures 1491<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and 1492familiar syntax: 1493 1494 1495 1496 1497<pre> 1498 stat ::= <b>while</b> exp <b>do</b> block <b>end</b> 1499 stat ::= <b>repeat</b> block <b>until</b> exp 1500 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> 1501</pre><p> 1502Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">§3.3.5</a>). 1503 1504 1505<p> 1506The condition expression of a 1507control structure can return any value. 1508Both <b>false</b> and <b>nil</b> are considered false. 1509All values different from <b>nil</b> and <b>false</b> are considered true 1510(in particular, the number 0 and the empty string are also true). 1511 1512 1513<p> 1514In the <b>repeat</b>–<b>until</b> loop, 1515the inner block does not end at the <b>until</b> keyword, 1516but only after the condition. 1517So, the condition can refer to local variables 1518declared inside the loop block. 1519 1520 1521<p> 1522The <b>goto</b> statement transfers the program control to a label. 1523For syntactical reasons, 1524labels in Lua are considered statements too: 1525 1526 1527 1528<pre> 1529 stat ::= <b>goto</b> Name 1530 stat ::= label 1531 label ::= ‘<b>::</b>’ Name ‘<b>::</b>’ 1532</pre> 1533 1534<p> 1535A label is visible in the entire block where it is defined, 1536except 1537inside nested blocks where a label with the same name is defined and 1538inside nested functions. 1539A goto may jump to any visible label as long as it does not 1540enter into the scope of a local variable. 1541 1542 1543<p> 1544Labels and empty statements are called <em>void statements</em>, 1545as they perform no actions. 1546 1547 1548<p> 1549The <b>break</b> statement terminates the execution of a 1550<b>while</b>, <b>repeat</b>, or <b>for</b> loop, 1551skipping to the next statement after the loop: 1552 1553 1554<pre> 1555 stat ::= <b>break</b> 1556</pre><p> 1557A <b>break</b> ends the innermost enclosing loop. 1558 1559 1560<p> 1561The <b>return</b> statement is used to return values 1562from a function or a chunk 1563(which is an anonymous function). 1564 1565Functions can return more than one value, 1566so the syntax for the <b>return</b> statement is 1567 1568<pre> 1569 stat ::= <b>return</b> [explist] [‘<b>;</b>’] 1570</pre> 1571 1572<p> 1573The <b>return</b> statement can only be written 1574as the last statement of a block. 1575If it is really necessary to <b>return</b> in the middle of a block, 1576then an explicit inner block can be used, 1577as in the idiom <code>do return end</code>, 1578because now <b>return</b> is the last statement in its (inner) block. 1579 1580 1581 1582 1583 1584<h3>3.3.5 – <a name="3.3.5">For Statement</a></h3> 1585 1586<p> 1587 1588The <b>for</b> statement has two forms: 1589one numerical and one generic. 1590 1591 1592<p> 1593The numerical <b>for</b> loop repeats a block of code while a 1594control variable runs through an arithmetic progression. 1595It has the following syntax: 1596 1597<pre> 1598 stat ::= <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b> 1599</pre><p> 1600The <em>block</em> is repeated for <em>name</em> starting at the value of 1601the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the 1602third <em>exp</em>. 1603More precisely, a <b>for</b> statement like 1604 1605<pre> 1606 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end 1607</pre><p> 1608is equivalent to the code: 1609 1610<pre> 1611 do 1612 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>) 1613 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end 1614 <em>var</em> = <em>var</em> - <em>step</em> 1615 while true do 1616 <em>var</em> = <em>var</em> + <em>step</em> 1617 if (<em>step</em> >= 0 and <em>var</em> > <em>limit</em>) or (<em>step</em> < 0 and <em>var</em> < <em>limit</em>) then 1618 break 1619 end 1620 local v = <em>var</em> 1621 <em>block</em> 1622 end 1623 end 1624</pre> 1625 1626<p> 1627Note the following: 1628 1629<ul> 1630 1631<li> 1632All three control expressions are evaluated only once, 1633before the loop starts. 1634They must all result in numbers. 1635</li> 1636 1637<li> 1638<code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables. 1639The names shown here are for explanatory purposes only. 1640</li> 1641 1642<li> 1643If the third expression (the step) is absent, 1644then a step of 1 is used. 1645</li> 1646 1647<li> 1648You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop. 1649</li> 1650 1651<li> 1652The loop variable <code>v</code> is local to the loop body. 1653If you need its value after the loop, 1654assign it to another variable before exiting the loop. 1655</li> 1656 1657</ul> 1658 1659<p> 1660The generic <b>for</b> statement works over functions, 1661called <em>iterators</em>. 1662On each iteration, the iterator function is called to produce a new value, 1663stopping when this new value is <b>nil</b>. 1664The generic <b>for</b> loop has the following syntax: 1665 1666<pre> 1667 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> 1668 namelist ::= Name {‘<b>,</b>’ Name} 1669</pre><p> 1670A <b>for</b> statement like 1671 1672<pre> 1673 for <em>var_1</em>, ···, <em>var_n</em> in <em>explist</em> do <em>block</em> end 1674</pre><p> 1675is equivalent to the code: 1676 1677<pre> 1678 do 1679 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em> 1680 while true do 1681 local <em>var_1</em>, ···, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>) 1682 if <em>var_1</em> == nil then break end 1683 <em>var</em> = <em>var_1</em> 1684 <em>block</em> 1685 end 1686 end 1687</pre><p> 1688Note the following: 1689 1690<ul> 1691 1692<li> 1693<code><em>explist</em></code> is evaluated only once. 1694Its results are an <em>iterator</em> function, 1695a <em>state</em>, 1696and an initial value for the first <em>iterator variable</em>. 1697</li> 1698 1699<li> 1700<code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables. 1701The names are here for explanatory purposes only. 1702</li> 1703 1704<li> 1705You can use <b>break</b> to exit a <b>for</b> loop. 1706</li> 1707 1708<li> 1709The loop variables <code><em>var_i</em></code> are local to the loop; 1710you cannot use their values after the <b>for</b> ends. 1711If you need these values, 1712then assign them to other variables before breaking or exiting the loop. 1713</li> 1714 1715</ul> 1716 1717 1718 1719 1720<h3>3.3.6 – <a name="3.3.6">Function Calls as Statements</a></h3><p> 1721To allow possible side-effects, 1722function calls can be executed as statements: 1723 1724<pre> 1725 stat ::= functioncall 1726</pre><p> 1727In this case, all returned values are thrown away. 1728Function calls are explained in <a href="#3.4.10">§3.4.10</a>. 1729 1730 1731 1732 1733 1734<h3>3.3.7 – <a name="3.3.7">Local Declarations</a></h3><p> 1735Local variables can be declared anywhere inside a block. 1736The declaration can include an initial assignment: 1737 1738<pre> 1739 stat ::= <b>local</b> namelist [‘<b>=</b>’ explist] 1740</pre><p> 1741If present, an initial assignment has the same semantics 1742of a multiple assignment (see <a href="#3.3.3">§3.3.3</a>). 1743Otherwise, all variables are initialized with <b>nil</b>. 1744 1745 1746<p> 1747A chunk is also a block (see <a href="#3.3.2">§3.3.2</a>), 1748and so local variables can be declared in a chunk outside any explicit block. 1749 1750 1751<p> 1752The visibility rules for local variables are explained in <a href="#3.5">§3.5</a>. 1753 1754 1755 1756 1757 1758 1759 1760<h2>3.4 – <a name="3.4">Expressions</a></h2> 1761 1762<p> 1763The basic expressions in Lua are the following: 1764 1765<pre> 1766 exp ::= prefixexp 1767 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> 1768 exp ::= Numeral 1769 exp ::= LiteralString 1770 exp ::= functiondef 1771 exp ::= tableconstructor 1772 exp ::= ‘<b>...</b>’ 1773 exp ::= exp binop exp 1774 exp ::= unop exp 1775 prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’ 1776</pre> 1777 1778<p> 1779Numerals and literal strings are explained in <a href="#3.1">§3.1</a>; 1780variables are explained in <a href="#3.2">§3.2</a>; 1781function definitions are explained in <a href="#3.4.11">§3.4.11</a>; 1782function calls are explained in <a href="#3.4.10">§3.4.10</a>; 1783table constructors are explained in <a href="#3.4.9">§3.4.9</a>. 1784Vararg expressions, 1785denoted by three dots ('<code>...</code>'), can only be used when 1786directly inside a vararg function; 1787they are explained in <a href="#3.4.11">§3.4.11</a>. 1788 1789 1790<p> 1791Binary operators comprise arithmetic operators (see <a href="#3.4.1">§3.4.1</a>), 1792bitwise operators (see <a href="#3.4.2">§3.4.2</a>), 1793relational operators (see <a href="#3.4.4">§3.4.4</a>), logical operators (see <a href="#3.4.5">§3.4.5</a>), 1794and the concatenation operator (see <a href="#3.4.6">§3.4.6</a>). 1795Unary operators comprise the unary minus (see <a href="#3.4.1">§3.4.1</a>), 1796the unary bitwise not (see <a href="#3.4.2">§3.4.2</a>), 1797the unary logical <b>not</b> (see <a href="#3.4.5">§3.4.5</a>), 1798and the unary <em>length operator</em> (see <a href="#3.4.7">§3.4.7</a>). 1799 1800 1801<p> 1802Both function calls and vararg expressions can result in multiple values. 1803If a function call is used as a statement (see <a href="#3.3.6">§3.3.6</a>), 1804then its return list is adjusted to zero elements, 1805thus discarding all returned values. 1806If an expression is used as the last (or the only) element 1807of a list of expressions, 1808then no adjustment is made 1809(unless the expression is enclosed in parentheses). 1810In all other contexts, 1811Lua adjusts the result list to one element, 1812either discarding all values except the first one 1813or adding a single <b>nil</b> if there are no values. 1814 1815 1816<p> 1817Here are some examples: 1818 1819<pre> 1820 f() -- adjusted to 0 results 1821 g(f(), x) -- f() is adjusted to 1 result 1822 g(x, f()) -- g gets x plus all results from f() 1823 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) 1824 a,b = ... -- a gets the first vararg parameter, b gets 1825 -- the second (both a and b can get nil if there 1826 -- is no corresponding vararg parameter) 1827 1828 a,b,c = x, f() -- f() is adjusted to 2 results 1829 a,b,c = f() -- f() is adjusted to 3 results 1830 return f() -- returns all results from f() 1831 return ... -- returns all received vararg parameters 1832 return x,y,f() -- returns x, y, and all results from f() 1833 {f()} -- creates a list with all results from f() 1834 {...} -- creates a list with all vararg parameters 1835 {f(), nil} -- f() is adjusted to 1 result 1836</pre> 1837 1838<p> 1839Any expression enclosed in parentheses always results in only one value. 1840Thus, 1841<code>(f(x,y,z))</code> is always a single value, 1842even if <code>f</code> returns several values. 1843(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code> 1844or <b>nil</b> if <code>f</code> does not return any values.) 1845 1846 1847 1848<h3>3.4.1 – <a name="3.4.1">Arithmetic Operators</a></h3><p> 1849Lua supports the following arithmetic operators: 1850 1851<ul> 1852<li><b><code>+</code>: </b>addition</li> 1853<li><b><code>-</code>: </b>subtraction</li> 1854<li><b><code>*</code>: </b>multiplication</li> 1855<li><b><code>/</code>: </b>float division</li> 1856<li><b><code>//</code>: </b>floor division</li> 1857<li><b><code>%</code>: </b>modulo</li> 1858<li><b><code>^</code>: </b>exponentiation</li> 1859<li><b><code>-</code>: </b>unary minus</li> 1860</ul> 1861 1862<p> 1863With the exception of exponentiation and float division, 1864the arithmetic operators work as follows: 1865If both operands are integers, 1866the operation is performed over integers and the result is an integer. 1867Otherwise, if both operands are numbers 1868or strings that can be converted to 1869numbers (see <a href="#3.4.3">§3.4.3</a>), 1870then they are converted to floats, 1871the operation is performed following the usual rules 1872for floating-point arithmetic 1873(usually the IEEE 754 standard), 1874and the result is a float. 1875 1876 1877<p> 1878Exponentiation and float division (<code>/</code>) 1879always convert their operands to floats 1880and the result is always a float. 1881Exponentiation uses the ISO C function <code>pow</code>, 1882so that it works for non-integer exponents too. 1883 1884 1885<p> 1886Floor division (<code>//</code>) is a division 1887that rounds the quotient towards minus infinity, 1888that is, the floor of the division of its operands. 1889 1890 1891<p> 1892Modulo is defined as the remainder of a division 1893that rounds the quotient towards minus infinity (floor division). 1894 1895 1896<p> 1897In case of overflows in integer arithmetic, 1898all operations <em>wrap around</em>, 1899according to the usual rules of two-complement arithmetic. 1900(In other words, 1901they return the unique representable integer 1902that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.) 1903 1904 1905 1906<h3>3.4.2 – <a name="3.4.2">Bitwise Operators</a></h3><p> 1907Lua supports the following bitwise operators: 1908 1909<ul> 1910<li><b><code>&</code>: </b>bitwise and</li> 1911<li><b><code>|</code>: </b>bitwise or</li> 1912<li><b><code>~</code>: </b>bitwise exclusive or</li> 1913<li><b><code>>></code>: </b>right shift</li> 1914<li><b><code><<</code>: </b>left shift</li> 1915<li><b><code>~</code>: </b>unary bitwise not</li> 1916</ul> 1917 1918<p> 1919All bitwise operations convert its operands to integers 1920(see <a href="#3.4.3">§3.4.3</a>), 1921operate on all bits of those integers, 1922and result in an integer. 1923 1924 1925<p> 1926Both right and left shifts fill the vacant bits with zeros. 1927Negative displacements shift to the other direction; 1928displacements with absolute values equal to or higher than 1929the number of bits in an integer 1930result in zero (as all bits are shifted out). 1931 1932 1933 1934 1935 1936<h3>3.4.3 – <a name="3.4.3">Coercions and Conversions</a></h3><p> 1937Lua provides some automatic conversions between some 1938types and representations at run time. 1939Bitwise operators always convert float operands to integers. 1940Exponentiation and float division 1941always convert integer operands to floats. 1942All other arithmetic operations applied to mixed numbers 1943(integers and floats) convert the integer operand to a float; 1944this is called the <em>usual rule</em>. 1945The C API also converts both integers to floats and 1946floats to integers, as needed. 1947Moreover, string concatenation accepts numbers as arguments, 1948besides strings. 1949 1950 1951<p> 1952Lua also converts strings to numbers, 1953whenever a number is expected. 1954 1955 1956<p> 1957In a conversion from integer to float, 1958if the integer value has an exact representation as a float, 1959that is the result. 1960Otherwise, 1961the conversion gets the nearest higher or 1962the nearest lower representable value. 1963This kind of conversion never fails. 1964 1965 1966<p> 1967The conversion from float to integer 1968checks whether the float has an exact representation as an integer 1969(that is, the float has an integral value and 1970it is in the range of integer representation). 1971If it does, that representation is the result. 1972Otherwise, the conversion fails. 1973 1974 1975<p> 1976The conversion from strings to numbers goes as follows: 1977First, the string is converted to an integer or a float, 1978following its syntax and the rules of the Lua lexer. 1979(The string may have also leading and trailing spaces and a sign.) 1980Then, the resulting number (float or integer) 1981is converted to the type (float or integer) required by the context 1982(e.g., the operation that forced the conversion). 1983 1984 1985<p> 1986The conversion from numbers to strings uses a 1987non-specified human-readable format. 1988For complete control over how numbers are converted to strings, 1989use the <code>format</code> function from the string library 1990(see <a href="#pdf-string.format"><code>string.format</code></a>). 1991 1992 1993 1994 1995 1996<h3>3.4.4 – <a name="3.4.4">Relational Operators</a></h3><p> 1997Lua supports the following relational operators: 1998 1999<ul> 2000<li><b><code>==</code>: </b>equality</li> 2001<li><b><code>~=</code>: </b>inequality</li> 2002<li><b><code><</code>: </b>less than</li> 2003<li><b><code>></code>: </b>greater than</li> 2004<li><b><code><=</code>: </b>less or equal</li> 2005<li><b><code>>=</code>: </b>greater or equal</li> 2006</ul><p> 2007These operators always result in <b>false</b> or <b>true</b>. 2008 2009 2010<p> 2011Equality (<code>==</code>) first compares the type of its operands. 2012If the types are different, then the result is <b>false</b>. 2013Otherwise, the values of the operands are compared. 2014Strings are compared in the obvious way. 2015Numbers are equal if they denote the same mathematical value. 2016 2017 2018<p> 2019Tables, userdata, and threads 2020are compared by reference: 2021two objects are considered equal only if they are the same object. 2022Every time you create a new object 2023(a table, userdata, or thread), 2024this new object is different from any previously existing object. 2025Closures with the same reference are always equal. 2026Closures with any detectable difference 2027(different behavior, different definition) are always different. 2028 2029 2030<p> 2031You can change the way that Lua compares tables and userdata 2032by using the "eq" metamethod (see <a href="#2.4">§2.4</a>). 2033 2034 2035<p> 2036Equality comparisons do not convert strings to numbers 2037or vice versa. 2038Thus, <code>"0"==0</code> evaluates to <b>false</b>, 2039and <code>t[0]</code> and <code>t["0"]</code> denote different 2040entries in a table. 2041 2042 2043<p> 2044The operator <code>~=</code> is exactly the negation of equality (<code>==</code>). 2045 2046 2047<p> 2048The order operators work as follows. 2049If both arguments are numbers, 2050then they are compared according to their mathematical values 2051(regardless of their subtypes). 2052Otherwise, if both arguments are strings, 2053then their values are compared according to the current locale. 2054Otherwise, Lua tries to call the "lt" or the "le" 2055metamethod (see <a href="#2.4">§2.4</a>). 2056A comparison <code>a > b</code> is translated to <code>b < a</code> 2057and <code>a >= b</code> is translated to <code>b <= a</code>. 2058 2059 2060<p> 2061Following the IEEE 754 standard, 2062NaN is considered neither smaller than, 2063nor equal to, nor greater than any value (including itself). 2064 2065 2066 2067 2068 2069<h3>3.4.5 – <a name="3.4.5">Logical Operators</a></h3><p> 2070The logical operators in Lua are 2071<b>and</b>, <b>or</b>, and <b>not</b>. 2072Like the control structures (see <a href="#3.3.4">§3.3.4</a>), 2073all logical operators consider both <b>false</b> and <b>nil</b> as false 2074and anything else as true. 2075 2076 2077<p> 2078The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>. 2079The conjunction operator <b>and</b> returns its first argument 2080if this value is <b>false</b> or <b>nil</b>; 2081otherwise, <b>and</b> returns its second argument. 2082The disjunction operator <b>or</b> returns its first argument 2083if this value is different from <b>nil</b> and <b>false</b>; 2084otherwise, <b>or</b> returns its second argument. 2085Both <b>and</b> and <b>or</b> use short-circuit evaluation; 2086that is, 2087the second operand is evaluated only if necessary. 2088Here are some examples: 2089 2090<pre> 2091 10 or 20 --> 10 2092 10 or error() --> 10 2093 nil or "a" --> "a" 2094 nil and 10 --> nil 2095 false and error() --> false 2096 false and nil --> false 2097 false or nil --> nil 2098 10 and 20 --> 20 2099</pre><p> 2100(In this manual, 2101<code>--></code> indicates the result of the preceding expression.) 2102 2103 2104 2105 2106 2107<h3>3.4.6 – <a name="3.4.6">Concatenation</a></h3><p> 2108The string concatenation operator in Lua is 2109denoted by two dots ('<code>..</code>'). 2110If both operands are strings or numbers, then they are converted to 2111strings according to the rules described in <a href="#3.4.3">§3.4.3</a>. 2112Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">§2.4</a>). 2113 2114 2115 2116 2117 2118<h3>3.4.7 – <a name="3.4.7">The Length Operator</a></h3> 2119 2120<p> 2121The length operator is denoted by the unary prefix operator <code>#</code>. 2122The length of a string is its number of bytes 2123(that is, the usual meaning of string length when each 2124character is one byte). 2125 2126 2127<p> 2128A program can modify the behavior of the length operator for 2129any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">§2.4</a>). 2130 2131 2132<p> 2133Unless a <code>__len</code> metamethod is given, 2134the length of a table <code>t</code> is only defined if the 2135table is a <em>sequence</em>, 2136that is, 2137the set of its positive numeric keys is equal to <em>{1..n}</em> 2138for some non-negative integer <em>n</em>. 2139In that case, <em>n</em> is its length. 2140Note that a table like 2141 2142<pre> 2143 {10, 20, nil, 40} 2144</pre><p> 2145is not a sequence, because it has the key <code>4</code> 2146but does not have the key <code>3</code>. 2147(So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal 2148to the set of positive numeric keys of that table.) 2149Note, however, that non-numeric keys do not interfere 2150with whether a table is a sequence. 2151 2152 2153 2154 2155 2156<h3>3.4.8 – <a name="3.4.8">Precedence</a></h3><p> 2157Operator precedence in Lua follows the table below, 2158from lower to higher priority: 2159 2160<pre> 2161 or 2162 and 2163 < > <= >= ~= == 2164 | 2165 ~ 2166 & 2167 << >> 2168 .. 2169 + - 2170 * / // % 2171 unary operators (not # - ~) 2172 ^ 2173</pre><p> 2174As usual, 2175you can use parentheses to change the precedences of an expression. 2176The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>') 2177operators are right associative. 2178All other binary operators are left associative. 2179 2180 2181 2182 2183 2184<h3>3.4.9 – <a name="3.4.9">Table Constructors</a></h3><p> 2185Table constructors are expressions that create tables. 2186Every time a constructor is evaluated, a new table is created. 2187A constructor can be used to create an empty table 2188or to create a table and initialize some of its fields. 2189The general syntax for constructors is 2190 2191<pre> 2192 tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’ 2193 fieldlist ::= field {fieldsep field} [fieldsep] 2194 field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp 2195 fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’ 2196</pre> 2197 2198<p> 2199Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry 2200with key <code>exp1</code> and value <code>exp2</code>. 2201A field of the form <code>name = exp</code> is equivalent to 2202<code>["name"] = exp</code>. 2203Finally, fields of the form <code>exp</code> are equivalent to 2204<code>[i] = exp</code>, where <code>i</code> are consecutive integers 2205starting with 1. 2206Fields in the other formats do not affect this counting. 2207For example, 2208 2209<pre> 2210 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } 2211</pre><p> 2212is equivalent to 2213 2214<pre> 2215 do 2216 local t = {} 2217 t[f(1)] = g 2218 t[1] = "x" -- 1st exp 2219 t[2] = "y" -- 2nd exp 2220 t.x = 1 -- t["x"] = 1 2221 t[3] = f(x) -- 3rd exp 2222 t[30] = 23 2223 t[4] = 45 -- 4th exp 2224 a = t 2225 end 2226</pre> 2227 2228<p> 2229The order of the assignments in a constructor is undefined. 2230(This order would be relevant only when there are repeated keys.) 2231 2232 2233<p> 2234If the last field in the list has the form <code>exp</code> 2235and the expression is a function call or a vararg expression, 2236then all values returned by this expression enter the list consecutively 2237(see <a href="#3.4.10">§3.4.10</a>). 2238 2239 2240<p> 2241The field list can have an optional trailing separator, 2242as a convenience for machine-generated code. 2243 2244 2245 2246 2247 2248<h3>3.4.10 – <a name="3.4.10">Function Calls</a></h3><p> 2249A function call in Lua has the following syntax: 2250 2251<pre> 2252 functioncall ::= prefixexp args 2253</pre><p> 2254In a function call, 2255first prefixexp and args are evaluated. 2256If the value of prefixexp has type <em>function</em>, 2257then this function is called 2258with the given arguments. 2259Otherwise, the prefixexp "call" metamethod is called, 2260having as first parameter the value of prefixexp, 2261followed by the original call arguments 2262(see <a href="#2.4">§2.4</a>). 2263 2264 2265<p> 2266The form 2267 2268<pre> 2269 functioncall ::= prefixexp ‘<b>:</b>’ Name args 2270</pre><p> 2271can be used to call "methods". 2272A call <code>v:name(<em>args</em>)</code> 2273is syntactic sugar for <code>v.name(v,<em>args</em>)</code>, 2274except that <code>v</code> is evaluated only once. 2275 2276 2277<p> 2278Arguments have the following syntax: 2279 2280<pre> 2281 args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ 2282 args ::= tableconstructor 2283 args ::= LiteralString 2284</pre><p> 2285All argument expressions are evaluated before the call. 2286A call of the form <code>f{<em>fields</em>}</code> is 2287syntactic sugar for <code>f({<em>fields</em>})</code>; 2288that is, the argument list is a single new table. 2289A call of the form <code>f'<em>string</em>'</code> 2290(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>) 2291is syntactic sugar for <code>f('<em>string</em>')</code>; 2292that is, the argument list is a single literal string. 2293 2294 2295<p> 2296A call of the form <code>return <em>functioncall</em></code> is called 2297a <em>tail call</em>. 2298Lua implements <em>proper tail calls</em> 2299(or <em>proper tail recursion</em>): 2300in a tail call, 2301the called function reuses the stack entry of the calling function. 2302Therefore, there is no limit on the number of nested tail calls that 2303a program can execute. 2304However, a tail call erases any debug information about the 2305calling function. 2306Note that a tail call only happens with a particular syntax, 2307where the <b>return</b> has one single function call as argument; 2308this syntax makes the calling function return exactly 2309the returns of the called function. 2310So, none of the following examples are tail calls: 2311 2312<pre> 2313 return (f(x)) -- results adjusted to 1 2314 return 2 * f(x) 2315 return x, f(x) -- additional results 2316 f(x); return -- results discarded 2317 return x or f(x) -- results adjusted to 1 2318</pre> 2319 2320 2321 2322 2323<h3>3.4.11 – <a name="3.4.11">Function Definitions</a></h3> 2324 2325<p> 2326The syntax for function definition is 2327 2328<pre> 2329 functiondef ::= <b>function</b> funcbody 2330 funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b> 2331</pre> 2332 2333<p> 2334The following syntactic sugar simplifies function definitions: 2335 2336<pre> 2337 stat ::= <b>function</b> funcname funcbody 2338 stat ::= <b>local</b> <b>function</b> Name funcbody 2339 funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name] 2340</pre><p> 2341The statement 2342 2343<pre> 2344 function f () <em>body</em> end 2345</pre><p> 2346translates to 2347 2348<pre> 2349 f = function () <em>body</em> end 2350</pre><p> 2351The statement 2352 2353<pre> 2354 function t.a.b.c.f () <em>body</em> end 2355</pre><p> 2356translates to 2357 2358<pre> 2359 t.a.b.c.f = function () <em>body</em> end 2360</pre><p> 2361The statement 2362 2363<pre> 2364 local function f () <em>body</em> end 2365</pre><p> 2366translates to 2367 2368<pre> 2369 local f; f = function () <em>body</em> end 2370</pre><p> 2371not to 2372 2373<pre> 2374 local f = function () <em>body</em> end 2375</pre><p> 2376(This only makes a difference when the body of the function 2377contains references to <code>f</code>.) 2378 2379 2380<p> 2381A function definition is an executable expression, 2382whose value has type <em>function</em>. 2383When Lua precompiles a chunk, 2384all its function bodies are precompiled too. 2385Then, whenever Lua executes the function definition, 2386the function is <em>instantiated</em> (or <em>closed</em>). 2387This function instance (or <em>closure</em>) 2388is the final value of the expression. 2389 2390 2391<p> 2392Parameters act as local variables that are 2393initialized with the argument values: 2394 2395<pre> 2396 parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’ 2397</pre><p> 2398When a function is called, 2399the list of arguments is adjusted to 2400the length of the list of parameters, 2401unless the function is a <em>vararg function</em>, 2402which is indicated by three dots ('<code>...</code>') 2403at the end of its parameter list. 2404A vararg function does not adjust its argument list; 2405instead, it collects all extra arguments and supplies them 2406to the function through a <em>vararg expression</em>, 2407which is also written as three dots. 2408The value of this expression is a list of all actual extra arguments, 2409similar to a function with multiple results. 2410If a vararg expression is used inside another expression 2411or in the middle of a list of expressions, 2412then its return list is adjusted to one element. 2413If the expression is used as the last element of a list of expressions, 2414then no adjustment is made 2415(unless that last expression is enclosed in parentheses). 2416 2417 2418<p> 2419As an example, consider the following definitions: 2420 2421<pre> 2422 function f(a, b) end 2423 function g(a, b, ...) end 2424 function r() return 1,2,3 end 2425</pre><p> 2426Then, we have the following mapping from arguments to parameters and 2427to the vararg expression: 2428 2429<pre> 2430 CALL PARAMETERS 2431 2432 f(3) a=3, b=nil 2433 f(3, 4) a=3, b=4 2434 f(3, 4, 5) a=3, b=4 2435 f(r(), 10) a=1, b=10 2436 f(r()) a=1, b=2 2437 2438 g(3) a=3, b=nil, ... --> (nothing) 2439 g(3, 4) a=3, b=4, ... --> (nothing) 2440 g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 2441 g(5, r()) a=5, b=1, ... --> 2 3 2442</pre> 2443 2444<p> 2445Results are returned using the <b>return</b> statement (see <a href="#3.3.4">§3.3.4</a>). 2446If control reaches the end of a function 2447without encountering a <b>return</b> statement, 2448then the function returns with no results. 2449 2450 2451<p> 2452 2453There is a system-dependent limit on the number of values 2454that a function may return. 2455This limit is guaranteed to be larger than 1000. 2456 2457 2458<p> 2459The <em>colon</em> syntax 2460is used for defining <em>methods</em>, 2461that is, functions that have an implicit extra parameter <code>self</code>. 2462Thus, the statement 2463 2464<pre> 2465 function t.a.b.c:f (<em>params</em>) <em>body</em> end 2466</pre><p> 2467is syntactic sugar for 2468 2469<pre> 2470 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end 2471</pre> 2472 2473 2474 2475 2476 2477 2478<h2>3.5 – <a name="3.5">Visibility Rules</a></h2> 2479 2480<p> 2481 2482Lua is a lexically scoped language. 2483The scope of a local variable begins at the first statement after 2484its declaration and lasts until the last non-void statement 2485of the innermost block that includes the declaration. 2486Consider the following example: 2487 2488<pre> 2489 x = 10 -- global variable 2490 do -- new block 2491 local x = x -- new 'x', with value 10 2492 print(x) --> 10 2493 x = x+1 2494 do -- another block 2495 local x = x+1 -- another 'x' 2496 print(x) --> 12 2497 end 2498 print(x) --> 11 2499 end 2500 print(x) --> 10 (the global one) 2501</pre> 2502 2503<p> 2504Notice that, in a declaration like <code>local x = x</code>, 2505the new <code>x</code> being declared is not in scope yet, 2506and so the second <code>x</code> refers to the outside variable. 2507 2508 2509<p> 2510Because of the lexical scoping rules, 2511local variables can be freely accessed by functions 2512defined inside their scope. 2513A local variable used by an inner function is called 2514an <em>upvalue</em>, or <em>external local variable</em>, 2515inside the inner function. 2516 2517 2518<p> 2519Notice that each execution of a <b>local</b> statement 2520defines new local variables. 2521Consider the following example: 2522 2523<pre> 2524 a = {} 2525 local x = 20 2526 for i=1,10 do 2527 local y = 0 2528 a[i] = function () y=y+1; return x+y end 2529 end 2530</pre><p> 2531The loop creates ten closures 2532(that is, ten instances of the anonymous function). 2533Each of these closures uses a different <code>y</code> variable, 2534while all of them share the same <code>x</code>. 2535 2536 2537 2538 2539 2540<h1>4 – <a name="4">The Application Program Interface</a></h1> 2541 2542<p> 2543 2544This section describes the C API for Lua, that is, 2545the set of C functions available to the host program to communicate 2546with Lua. 2547All API functions and related types and constants 2548are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>. 2549 2550 2551<p> 2552Even when we use the term "function", 2553any facility in the API may be provided as a macro instead. 2554Except where stated otherwise, 2555all such macros use each of their arguments exactly once 2556(except for the first argument, which is always a Lua state), 2557and so do not generate any hidden side-effects. 2558 2559 2560<p> 2561As in most C libraries, 2562the Lua API functions do not check their arguments for validity or consistency. 2563However, you can change this behavior by compiling Lua 2564with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined. 2565 2566 2567 2568<h2>4.1 – <a name="4.1">The Stack</a></h2> 2569 2570<p> 2571Lua uses a <em>virtual stack</em> to pass values to and from C. 2572Each element in this stack represents a Lua value 2573(<b>nil</b>, number, string, etc.). 2574 2575 2576<p> 2577Whenever Lua calls C, the called function gets a new stack, 2578which is independent of previous stacks and of stacks of 2579C functions that are still active. 2580This stack initially contains any arguments to the C function 2581and it is where the C function pushes its results 2582to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 2583 2584 2585<p> 2586For convenience, 2587most query operations in the API do not follow a strict stack discipline. 2588Instead, they can refer to any element in the stack 2589by using an <em>index</em>: 2590A positive index represents an absolute stack position 2591(starting at 1); 2592a negative index represents an offset relative to the top of the stack. 2593More specifically, if the stack has <em>n</em> elements, 2594then index 1 represents the first element 2595(that is, the element that was pushed onto the stack first) 2596and 2597index <em>n</em> represents the last element; 2598index -1 also represents the last element 2599(that is, the element at the top) 2600and index <em>-n</em> represents the first element. 2601 2602 2603 2604 2605 2606<h2>4.2 – <a name="4.2">Stack Size</a></h2> 2607 2608<p> 2609When you interact with the Lua API, 2610you are responsible for ensuring consistency. 2611In particular, 2612<em>you are responsible for controlling stack overflow</em>. 2613You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a> 2614to ensure that the stack has enough space for pushing new elements. 2615 2616 2617<p> 2618Whenever Lua calls C, 2619it ensures that the stack has space for 2620at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots. 2621<code>LUA_MINSTACK</code> is defined as 20, 2622so that usually you do not have to worry about stack space 2623unless your code has loops pushing elements onto the stack. 2624 2625 2626<p> 2627When you call a Lua function 2628without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>), 2629Lua ensures that the stack has enough space for all results, 2630but it does not ensure any extra space. 2631So, before pushing anything in the stack after such a call 2632you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>. 2633 2634 2635 2636 2637 2638<h2>4.3 – <a name="4.3">Valid and Acceptable Indices</a></h2> 2639 2640<p> 2641Any function in the API that receives stack indices 2642works only with <em>valid indices</em> or <em>acceptable indices</em>. 2643 2644 2645<p> 2646A <em>valid index</em> is an index that refers to a 2647position that stores a modifiable Lua value. 2648It comprises stack indices between 1 and the stack top 2649(<code>1 ≤ abs(index) ≤ top</code>) 2650 2651plus <em>pseudo-indices</em>, 2652which represent some positions that are accessible to C code 2653but that are not in the stack. 2654Pseudo-indices are used to access the registry (see <a href="#4.5">§4.5</a>) 2655and the upvalues of a C function (see <a href="#4.4">§4.4</a>). 2656 2657 2658<p> 2659Functions that do not need a specific mutable position, 2660but only a value (e.g., query functions), 2661can be called with acceptable indices. 2662An <em>acceptable index</em> can be any valid index, 2663but it also can be any positive index after the stack top 2664within the space allocated for the stack, 2665that is, indices up to the stack size. 2666(Note that 0 is never an acceptable index.) 2667Except when noted otherwise, 2668functions in the API work with acceptable indices. 2669 2670 2671<p> 2672Acceptable indices serve to avoid extra tests 2673against the stack top when querying the stack. 2674For instance, a C function can query its third argument 2675without the need to first check whether there is a third argument, 2676that is, without the need to check whether 3 is a valid index. 2677 2678 2679<p> 2680For functions that can be called with acceptable indices, 2681any non-valid index is treated as if it 2682contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>, 2683which behaves like a nil value. 2684 2685 2686 2687 2688 2689<h2>4.4 – <a name="4.4">C Closures</a></h2> 2690 2691<p> 2692When a C function is created, 2693it is possible to associate some values with it, 2694thus creating a <em>C closure</em> 2695(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>); 2696these values are called <em>upvalues</em> and are 2697accessible to the function whenever it is called. 2698 2699 2700<p> 2701Whenever a C function is called, 2702its upvalues are located at specific pseudo-indices. 2703These pseudo-indices are produced by the macro 2704<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>. 2705The first upvalue associated with a function is at index 2706<code>lua_upvalueindex(1)</code>, and so on. 2707Any access to <code>lua_upvalueindex(<em>n</em>)</code>, 2708where <em>n</em> is greater than the number of upvalues of the 2709current function (but not greater than 256), 2710produces an acceptable but invalid index. 2711 2712 2713 2714 2715 2716<h2>4.5 – <a name="4.5">Registry</a></h2> 2717 2718<p> 2719Lua provides a <em>registry</em>, 2720a predefined table that can be used by any C code to 2721store whatever Lua values it needs to store. 2722The registry table is always located at pseudo-index 2723<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>. 2724Any C library can store data into this table, 2725but it must take care to choose keys 2726that are different from those used 2727by other libraries, to avoid collisions. 2728Typically, you should use as key a string containing your library name, 2729or a light userdata with the address of a C object in your code, 2730or any Lua object created by your code. 2731As with variable names, 2732string keys starting with an underscore followed by 2733uppercase letters are reserved for Lua. 2734 2735 2736<p> 2737The integer keys in the registry are used 2738by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>) 2739and by some predefined values. 2740Therefore, integer keys must not be used for other purposes. 2741 2742 2743<p> 2744When you create a new Lua state, 2745its registry comes with some predefined values. 2746These predefined values are indexed with integer keys 2747defined as constants in <code>lua.h</code>. 2748The following constants are defined: 2749 2750<ul> 2751<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has 2752the main thread of the state. 2753(The main thread is the one created together with the state.) 2754</li> 2755 2756<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has 2757the global environment. 2758</li> 2759</ul> 2760 2761 2762 2763 2764<h2>4.6 – <a name="4.6">Error Handling in C</a></h2> 2765 2766<p> 2767Internally, Lua uses the C <code>longjmp</code> facility to handle errors. 2768(Lua will use exceptions if you compile it as C++; 2769search for <code>LUAI_THROW</code> in the source code for details.) 2770When Lua faces any error 2771(such as a memory allocation error, type errors, syntax errors, 2772and runtime errors) 2773it <em>raises</em> an error; 2774that is, it does a long jump. 2775A <em>protected environment</em> uses <code>setjmp</code> 2776to set a recovery point; 2777any error jumps to the most recent active recovery point. 2778 2779 2780<p> 2781If an error happens outside any protected environment, 2782Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) 2783and then calls <code>abort</code>, 2784thus exiting the host application. 2785Your panic function can avoid this exit by 2786never returning 2787(e.g., doing a long jump to your own recovery point outside Lua). 2788 2789 2790<p> 2791The panic function runs as if it were a message handler (see <a href="#2.3">§2.3</a>); 2792in particular, the error message is at the top of the stack. 2793However, there is no guarantee about stack space. 2794To push anything on the stack, 2795the panic function must first check the available space (see <a href="#4.2">§4.2</a>). 2796 2797 2798<p> 2799Most functions in the API can raise an error, 2800for instance due to a memory allocation error. 2801The documentation for each function indicates whether 2802it can raise errors. 2803 2804 2805<p> 2806Inside a C function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>. 2807 2808 2809 2810 2811 2812<h2>4.7 – <a name="4.7">Handling Yields in C</a></h2> 2813 2814<p> 2815Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine. 2816Therefore, if a C function <code>foo</code> calls an API function 2817and this API function yields 2818(directly or indirectly by calling another function that yields), 2819Lua cannot return to <code>foo</code> any more, 2820because the <code>longjmp</code> removes its frame from the C stack. 2821 2822 2823<p> 2824To avoid this kind of problem, 2825Lua raises an error whenever it tries to yield across an API call, 2826except for three functions: 2827<a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>. 2828All those functions receive a <em>continuation function</em> 2829(as a parameter named <code>k</code>) to continue execution after a yield. 2830 2831 2832<p> 2833We need to set some terminology to explain continuations. 2834We have a C function called from Lua which we will call 2835the <em>original function</em>. 2836This original function then calls one of those three functions in the C API, 2837which we will call the <em>callee function</em>, 2838that then yields the current thread. 2839(This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 2840or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a> 2841and the function called by them yields.) 2842 2843 2844<p> 2845Suppose the running thread yields while executing the callee function. 2846After the thread resumes, 2847it eventually will finish running the callee function. 2848However, 2849the callee function cannot return to the original function, 2850because its frame in the C stack was destroyed by the yield. 2851Instead, Lua calls a <em>continuation function</em>, 2852which was given as an argument to the callee function. 2853As the name implies, 2854the continuation function should continue the task 2855of the original function. 2856 2857 2858<p> 2859As an illustration, consider the following function: 2860 2861<pre> 2862 int original_function (lua_State *L) { 2863 ... /* code 1 */ 2864 status = lua_pcall(L, n, m, h); /* calls Lua */ 2865 ... /* code 2 */ 2866 } 2867</pre><p> 2868Now we want to allow 2869the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield. 2870First, we can rewrite our function like here: 2871 2872<pre> 2873 int k (lua_State *L, int status, lua_KContext ctx) { 2874 ... /* code 2 */ 2875 } 2876 2877 int original_function (lua_State *L) { 2878 ... /* code 1 */ 2879 return k(L, lua_pcall(L, n, m, h), ctx); 2880 } 2881</pre><p> 2882In the above code, 2883the new function <code>k</code> is a 2884<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>), 2885which should do all the work that the original function 2886was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>. 2887Now, we must inform Lua that it must call <code>k</code> if the Lua code 2888being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way 2889(errors or yielding), 2890so we rewrite the code as here, 2891replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>: 2892 2893<pre> 2894 int original_function (lua_State *L) { 2895 ... /* code 1 */ 2896 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); 2897 } 2898</pre><p> 2899Note the external, explicit call to the continuation: 2900Lua will call the continuation only if needed, that is, 2901in case of errors or resuming after a yield. 2902If the called function returns normally without ever yielding, 2903<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally. 2904(Of course, instead of calling the continuation in that case, 2905you can do the equivalent work directly inside the original function.) 2906 2907 2908<p> 2909Besides the Lua state, 2910the continuation function has two other parameters: 2911the final status of the call plus the context value (<code>ctx</code>) that 2912was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>. 2913(Lua does not use this context value; 2914it only passes this value from the original function to the 2915continuation function.) 2916For <a href="#lua_pcallk"><code>lua_pcallk</code></a>, 2917the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>, 2918except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield 2919(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>). 2920For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>, 2921the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation. 2922(For these two functions, 2923Lua will not call the continuation in case of errors, 2924because they do not handle errors.) 2925Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>, 2926you should call the continuation function 2927with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status. 2928(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling 2929directly the continuation function, 2930because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.) 2931 2932 2933<p> 2934Lua treats the continuation function as if it were the original function. 2935The continuation function receives the same Lua stack 2936from the original function, 2937in the same state it would be if the callee function had returned. 2938(For instance, 2939after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are 2940removed from the stack and replaced by the results from the call.) 2941It also has the same upvalues. 2942Whatever it returns is handled by Lua as if it were the return 2943of the original function. 2944 2945 2946 2947 2948 2949<h2>4.8 – <a name="4.8">Functions and Types</a></h2> 2950 2951<p> 2952Here we list all functions and types from the C API in 2953alphabetical order. 2954Each function has an indicator like this: 2955<span class="apii">[-o, +p, <em>x</em>]</span> 2956 2957 2958<p> 2959The first field, <code>o</code>, 2960is how many elements the function pops from the stack. 2961The second field, <code>p</code>, 2962is how many elements the function pushes onto the stack. 2963(Any function always pushes its results after popping its arguments.) 2964A field in the form <code>x|y</code> means the function can push (or pop) 2965<code>x</code> or <code>y</code> elements, 2966depending on the situation; 2967an interrogation mark '<code>?</code>' means that 2968we cannot know how many elements the function pops/pushes 2969by looking only at its arguments 2970(e.g., they may depend on what is on the stack). 2971The third field, <code>x</code>, 2972tells whether the function may raise errors: 2973'<code>-</code>' means the function never raises any error; 2974'<code>e</code>' means the function may raise errors; 2975'<code>v</code>' means the function may raise an error on purpose. 2976 2977 2978 2979<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p> 2980<span class="apii">[-0, +0, –]</span> 2981<pre>int lua_absindex (lua_State *L, int idx);</pre> 2982 2983<p> 2984Converts the acceptable index <code>idx</code> 2985into an equivalent absolute index 2986(that is, one that does not depend on the stack top). 2987 2988 2989 2990 2991 2992<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3> 2993<pre>typedef void * (*lua_Alloc) (void *ud, 2994 void *ptr, 2995 size_t osize, 2996 size_t nsize);</pre> 2997 2998<p> 2999The type of the memory-allocation function used by Lua states. 3000The allocator function must provide a 3001functionality similar to <code>realloc</code>, 3002but not exactly the same. 3003Its arguments are 3004<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>; 3005<code>ptr</code>, a pointer to the block being allocated/reallocated/freed; 3006<code>osize</code>, the original size of the block or some code about what 3007is being allocated; 3008and <code>nsize</code>, the new size of the block. 3009 3010 3011<p> 3012When <code>ptr</code> is not <code>NULL</code>, 3013<code>osize</code> is the size of the block pointed by <code>ptr</code>, 3014that is, the size given when it was allocated or reallocated. 3015 3016 3017<p> 3018When <code>ptr</code> is <code>NULL</code>, 3019<code>osize</code> encodes the kind of object that Lua is allocating. 3020<code>osize</code> is any of 3021<a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>, 3022<a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when) 3023Lua is creating a new object of that type. 3024When <code>osize</code> is some other value, 3025Lua is allocating memory for something else. 3026 3027 3028<p> 3029Lua assumes the following behavior from the allocator function: 3030 3031 3032<p> 3033When <code>nsize</code> is zero, 3034the allocator must behave like <code>free</code> 3035and return <code>NULL</code>. 3036 3037 3038<p> 3039When <code>nsize</code> is not zero, 3040the allocator must behave like <code>realloc</code>. 3041The allocator returns <code>NULL</code> 3042if and only if it cannot fulfill the request. 3043Lua assumes that the allocator never fails when 3044<code>osize >= nsize</code>. 3045 3046 3047<p> 3048Here is a simple implementation for the allocator function. 3049It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>. 3050 3051<pre> 3052 static void *l_alloc (void *ud, void *ptr, size_t osize, 3053 size_t nsize) { 3054 (void)ud; (void)osize; /* not used */ 3055 if (nsize == 0) { 3056 free(ptr); 3057 return NULL; 3058 } 3059 else 3060 return realloc(ptr, nsize); 3061 } 3062</pre><p> 3063Note that Standard C ensures 3064that <code>free(NULL)</code> has no effect and that 3065<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>. 3066This code assumes that <code>realloc</code> does not fail when shrinking a block. 3067(Although Standard C does not ensure this behavior, 3068it seems to be a safe assumption.) 3069 3070 3071 3072 3073 3074<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p> 3075<span class="apii">[-(2|1), +1, <em>e</em>]</span> 3076<pre>void lua_arith (lua_State *L, int op);</pre> 3077 3078<p> 3079Performs an arithmetic or bitwise operation over the two values 3080(or one, in the case of negations) 3081at the top of the stack, 3082with the value at the top being the second operand, 3083pops these values, and pushes the result of the operation. 3084The function follows the semantics of the corresponding Lua operator 3085(that is, it may call metamethods). 3086 3087 3088<p> 3089The value of <code>op</code> must be one of the following constants: 3090 3091<ul> 3092 3093<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li> 3094<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li> 3095<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li> 3096<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li> 3097<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li> 3098<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li> 3099<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li> 3100<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li> 3101<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise negation (<code>~</code>)</li> 3102<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise and (<code>&</code>)</li> 3103<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise or (<code>|</code>)</li> 3104<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive or (<code>~</code>)</li> 3105<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code><<</code>)</li> 3106<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>>></code>)</li> 3107 3108</ul> 3109 3110 3111 3112 3113<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p> 3114<span class="apii">[-0, +0, –]</span> 3115<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre> 3116 3117<p> 3118Sets a new panic function and returns the old one (see <a href="#4.6">§4.6</a>). 3119 3120 3121 3122 3123 3124<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p> 3125<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span> 3126<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre> 3127 3128<p> 3129Calls a function. 3130 3131 3132<p> 3133To call a function you must use the following protocol: 3134first, the function to be called is pushed onto the stack; 3135then, the arguments to the function are pushed 3136in direct order; 3137that is, the first argument is pushed first. 3138Finally you call <a href="#lua_call"><code>lua_call</code></a>; 3139<code>nargs</code> is the number of arguments that you pushed onto the stack. 3140All arguments and the function value are popped from the stack 3141when the function is called. 3142The function results are pushed onto the stack when the function returns. 3143The number of results is adjusted to <code>nresults</code>, 3144unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>. 3145In this case, all results from the function are pushed. 3146Lua takes care that the returned values fit into the stack space. 3147The function results are pushed onto the stack in direct order 3148(the first result is pushed first), 3149so that after the call the last result is on the top of the stack. 3150 3151 3152<p> 3153Any error inside the called function is propagated upwards 3154(with a <code>longjmp</code>). 3155 3156 3157<p> 3158The following example shows how the host program can do the 3159equivalent to this Lua code: 3160 3161<pre> 3162 a = f("how", t.x, 14) 3163</pre><p> 3164Here it is in C: 3165 3166<pre> 3167 lua_getglobal(L, "f"); /* function to be called */ 3168 lua_pushliteral(L, "how"); /* 1st argument */ 3169 lua_getglobal(L, "t"); /* table to be indexed */ 3170 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ 3171 lua_remove(L, -2); /* remove 't' from the stack */ 3172 lua_pushinteger(L, 14); /* 3rd argument */ 3173 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */ 3174 lua_setglobal(L, "a"); /* set global 'a' */ 3175</pre><p> 3176Note that the code above is <em>balanced</em>: 3177at its end, the stack is back to its original configuration. 3178This is considered good programming practice. 3179 3180 3181 3182 3183 3184<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p> 3185<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span> 3186<pre>void lua_callk (lua_State *L, 3187 int nargs, 3188 int nresults, 3189 lua_KContext ctx, 3190 lua_KFunction k);</pre> 3191 3192<p> 3193This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>, 3194but allows the called function to yield (see <a href="#4.7">§4.7</a>). 3195 3196 3197 3198 3199 3200<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3> 3201<pre>typedef int (*lua_CFunction) (lua_State *L);</pre> 3202 3203<p> 3204Type for C functions. 3205 3206 3207<p> 3208In order to communicate properly with Lua, 3209a C function must use the following protocol, 3210which defines the way parameters and results are passed: 3211a C function receives its arguments from Lua in its stack 3212in direct order (the first argument is pushed first). 3213So, when the function starts, 3214<code>lua_gettop(L)</code> returns the number of arguments received by the function. 3215The first argument (if any) is at index 1 3216and its last argument is at index <code>lua_gettop(L)</code>. 3217To return values to Lua, a C function just pushes them onto the stack, 3218in direct order (the first result is pushed first), 3219and returns the number of results. 3220Any other value in the stack below the results will be properly 3221discarded by Lua. 3222Like a Lua function, a C function called by Lua can also return 3223many results. 3224 3225 3226<p> 3227As an example, the following function receives a variable number 3228of numeric arguments and returns their average and their sum: 3229 3230<pre> 3231 static int foo (lua_State *L) { 3232 int n = lua_gettop(L); /* number of arguments */ 3233 lua_Number sum = 0.0; 3234 int i; 3235 for (i = 1; i <= n; i++) { 3236 if (!lua_isnumber(L, i)) { 3237 lua_pushliteral(L, "incorrect argument"); 3238 lua_error(L); 3239 } 3240 sum += lua_tonumber(L, i); 3241 } 3242 lua_pushnumber(L, sum/n); /* first result */ 3243 lua_pushnumber(L, sum); /* second result */ 3244 return 2; /* number of results */ 3245 } 3246</pre> 3247 3248 3249 3250 3251<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p> 3252<span class="apii">[-0, +0, –]</span> 3253<pre>int lua_checkstack (lua_State *L, int n);</pre> 3254 3255<p> 3256Ensures that the stack has space for at least <code>n</code> extra slots. 3257It returns false if it cannot fulfill the request, 3258either because it would cause the stack 3259to be larger than a fixed maximum size 3260(typically at least several thousand elements) or 3261because it cannot allocate memory for the extra space. 3262This function never shrinks the stack; 3263if the stack is already larger than the new size, 3264it is left unchanged. 3265 3266 3267 3268 3269 3270<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p> 3271<span class="apii">[-0, +0, –]</span> 3272<pre>void lua_close (lua_State *L);</pre> 3273 3274<p> 3275Destroys all objects in the given Lua state 3276(calling the corresponding garbage-collection metamethods, if any) 3277and frees all dynamic memory used by this state. 3278On several platforms, you may not need to call this function, 3279because all resources are naturally released when the host program ends. 3280On the other hand, long-running programs that create multiple states, 3281such as daemons or web servers, 3282will probably need to close states as soon as they are not needed. 3283 3284 3285 3286 3287 3288<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p> 3289<span class="apii">[-0, +0, <em>e</em>]</span> 3290<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre> 3291 3292<p> 3293Compares two Lua values. 3294Returns 1 if the value at index <code>index1</code> satisfies <code>op</code> 3295when compared with the value at index <code>index2</code>, 3296following the semantics of the corresponding Lua operator 3297(that is, it may call metamethods). 3298Otherwise returns 0. 3299Also returns 0 if any of the indices is not valid. 3300 3301 3302<p> 3303The value of <code>op</code> must be one of the following constants: 3304 3305<ul> 3306 3307<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li> 3308<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code><</code>)</li> 3309<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code><=</code>)</li> 3310 3311</ul> 3312 3313 3314 3315 3316<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p> 3317<span class="apii">[-n, +1, <em>e</em>]</span> 3318<pre>void lua_concat (lua_State *L, int n);</pre> 3319 3320<p> 3321Concatenates the <code>n</code> values at the top of the stack, 3322pops them, and leaves the result at the top. 3323If <code>n</code> is 1, the result is the single value on the stack 3324(that is, the function does nothing); 3325if <code>n</code> is 0, the result is the empty string. 3326Concatenation is performed following the usual semantics of Lua 3327(see <a href="#3.4.6">§3.4.6</a>). 3328 3329 3330 3331 3332 3333<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p> 3334<span class="apii">[-0, +0, –]</span> 3335<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre> 3336 3337<p> 3338Copies the element at index <code>fromidx</code> 3339into the valid index <code>toidx</code>, 3340replacing the value at that position. 3341Values at other positions are not affected. 3342 3343 3344 3345 3346 3347<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p> 3348<span class="apii">[-0, +1, <em>e</em>]</span> 3349<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre> 3350 3351<p> 3352Creates a new empty table and pushes it onto the stack. 3353Parameter <code>narr</code> is a hint for how many elements the table 3354will have as a sequence; 3355parameter <code>nrec</code> is a hint for how many other elements 3356the table will have. 3357Lua may use these hints to preallocate memory for the new table. 3358This pre-allocation is useful for performance when you know in advance 3359how many elements the table will have. 3360Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>. 3361 3362 3363 3364 3365 3366<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p> 3367<span class="apii">[-0, +0, <em>e</em>]</span> 3368<pre>int lua_dump (lua_State *L, 3369 lua_Writer writer, 3370 void *data, 3371 int strip);</pre> 3372 3373<p> 3374Dumps a function as a binary chunk. 3375Receives a Lua function on the top of the stack 3376and produces a binary chunk that, 3377if loaded again, 3378results in a function equivalent to the one dumped. 3379As it produces parts of the chunk, 3380<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>) 3381with the given <code>data</code> 3382to write them. 3383 3384 3385<p> 3386If <code>strip</code> is true, 3387the binary representation may not include all debug information 3388about the function, 3389to save space. 3390 3391 3392<p> 3393The value returned is the error code returned by the last 3394call to the writer; 33950 means no errors. 3396 3397 3398<p> 3399This function does not pop the Lua function from the stack. 3400 3401 3402 3403 3404 3405<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p> 3406<span class="apii">[-1, +0, <em>v</em>]</span> 3407<pre>int lua_error (lua_State *L);</pre> 3408 3409<p> 3410Generates a Lua error, 3411using the value at the top of the stack as the error object. 3412This function does a long jump, 3413and therefore never returns 3414(see <a href="#luaL_error"><code>luaL_error</code></a>). 3415 3416 3417 3418 3419 3420<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p> 3421<span class="apii">[-0, +0, <em>e</em>]</span> 3422<pre>int lua_gc (lua_State *L, int what, int data);</pre> 3423 3424<p> 3425Controls the garbage collector. 3426 3427 3428<p> 3429This function performs several tasks, 3430according to the value of the parameter <code>what</code>: 3431 3432<ul> 3433 3434<li><b><code>LUA_GCSTOP</code>: </b> 3435stops the garbage collector. 3436</li> 3437 3438<li><b><code>LUA_GCRESTART</code>: </b> 3439restarts the garbage collector. 3440</li> 3441 3442<li><b><code>LUA_GCCOLLECT</code>: </b> 3443performs a full garbage-collection cycle. 3444</li> 3445 3446<li><b><code>LUA_GCCOUNT</code>: </b> 3447returns the current amount of memory (in Kbytes) in use by Lua. 3448</li> 3449 3450<li><b><code>LUA_GCCOUNTB</code>: </b> 3451returns the remainder of dividing the current amount of bytes of 3452memory in use by Lua by 1024. 3453</li> 3454 3455<li><b><code>LUA_GCSTEP</code>: </b> 3456performs an incremental step of garbage collection. 3457</li> 3458 3459<li><b><code>LUA_GCSETPAUSE</code>: </b> 3460sets <code>data</code> as the new value 3461for the <em>pause</em> of the collector (see <a href="#2.5">§2.5</a>) 3462and returns the previous value of the pause. 3463</li> 3464 3465<li><b><code>LUA_GCSETSTEPMUL</code>: </b> 3466sets <code>data</code> as the new value for the <em>step multiplier</em> of 3467the collector (see <a href="#2.5">§2.5</a>) 3468and returns the previous value of the step multiplier. 3469</li> 3470 3471<li><b><code>LUA_GCISRUNNING</code>: </b> 3472returns a boolean that tells whether the collector is running 3473(i.e., not stopped). 3474</li> 3475 3476</ul> 3477 3478<p> 3479For more details about these options, 3480see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>. 3481 3482 3483 3484 3485 3486<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p> 3487<span class="apii">[-0, +0, –]</span> 3488<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre> 3489 3490<p> 3491Returns the memory-allocation function of a given state. 3492If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the 3493opaque pointer given when the memory-allocator function was set. 3494 3495 3496 3497 3498 3499<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p> 3500<span class="apii">[-0, +1, <em>e</em>]</span> 3501<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre> 3502 3503<p> 3504Pushes onto the stack the value <code>t[k]</code>, 3505where <code>t</code> is the value at the given index. 3506As in Lua, this function may trigger a metamethod 3507for the "index" event (see <a href="#2.4">§2.4</a>). 3508 3509 3510<p> 3511Returns the type of the pushed value. 3512 3513 3514 3515 3516 3517<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p> 3518<span class="apii">[-0, +0, –]</span> 3519<pre>void *lua_getextraspace (lua_State *L);</pre> 3520 3521<p> 3522Returns a pointer to a raw memory area associated with the 3523given Lua state. 3524The application can use this area for any purpose; 3525Lua does not use it for anything. 3526 3527 3528<p> 3529Each new thread has this area initialized with a copy 3530of the area of the main thread. 3531 3532 3533<p> 3534By default, this area has the size of a pointer to void, 3535but you can recompile Lua with a different size for this area. 3536(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.) 3537 3538 3539 3540 3541 3542<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p> 3543<span class="apii">[-0, +1, <em>e</em>]</span> 3544<pre>int lua_getglobal (lua_State *L, const char *name);</pre> 3545 3546<p> 3547Pushes onto the stack the value of the global <code>name</code>. 3548Returns the type of that value. 3549 3550 3551 3552 3553 3554<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p> 3555<span class="apii">[-0, +1, <em>e</em>]</span> 3556<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre> 3557 3558<p> 3559Pushes onto the stack the value <code>t[i]</code>, 3560where <code>t</code> is the value at the given index. 3561As in Lua, this function may trigger a metamethod 3562for the "index" event (see <a href="#2.4">§2.4</a>). 3563 3564 3565<p> 3566Returns the type of the pushed value. 3567 3568 3569 3570 3571 3572<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p> 3573<span class="apii">[-0, +(0|1), –]</span> 3574<pre>int lua_getmetatable (lua_State *L, int index);</pre> 3575 3576<p> 3577If the value at the given index has a metatable, 3578the function pushes that metatable onto the stack and returns 1. 3579Otherwise, 3580the function returns 0 and pushes nothing on the stack. 3581 3582 3583 3584 3585 3586<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p> 3587<span class="apii">[-1, +1, <em>e</em>]</span> 3588<pre>int lua_gettable (lua_State *L, int index);</pre> 3589 3590<p> 3591Pushes onto the stack the value <code>t[k]</code>, 3592where <code>t</code> is the value at the given index 3593and <code>k</code> is the value at the top of the stack. 3594 3595 3596<p> 3597This function pops the key from the stack, 3598pushing the resulting value in its place. 3599As in Lua, this function may trigger a metamethod 3600for the "index" event (see <a href="#2.4">§2.4</a>). 3601 3602 3603<p> 3604Returns the type of the pushed value. 3605 3606 3607 3608 3609 3610<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p> 3611<span class="apii">[-0, +0, –]</span> 3612<pre>int lua_gettop (lua_State *L);</pre> 3613 3614<p> 3615Returns the index of the top element in the stack. 3616Because indices start at 1, 3617this result is equal to the number of elements in the stack; 3618in particular, 0 means an empty stack. 3619 3620 3621 3622 3623 3624<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p> 3625<span class="apii">[-0, +1, –]</span> 3626<pre>int lua_getuservalue (lua_State *L, int index);</pre> 3627 3628<p> 3629Pushes onto the stack the Lua value associated with the userdata 3630at the given index. 3631 3632 3633<p> 3634Returns the type of the pushed value. 3635 3636 3637 3638 3639 3640<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p> 3641<span class="apii">[-1, +1, –]</span> 3642<pre>void lua_insert (lua_State *L, int index);</pre> 3643 3644<p> 3645Moves the top element into the given valid index, 3646shifting up the elements above this index to open space. 3647This function cannot be called with a pseudo-index, 3648because a pseudo-index is not an actual stack position. 3649 3650 3651 3652 3653 3654<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3> 3655<pre>typedef ... lua_Integer;</pre> 3656 3657<p> 3658The type of integers in Lua. 3659 3660 3661<p> 3662By default this type is <code>long long</code>, 3663(usually a 64-bit two-complement integer), 3664but that can be changed to <code>long</code> or <code>int</code> 3665(usually a 32-bit two-complement integer). 3666(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.) 3667 3668 3669<p> 3670Lua also defines the constants 3671<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>, 3672with the minimum and the maximum values that fit in this type. 3673 3674 3675 3676 3677 3678<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p> 3679<span class="apii">[-0, +0, –]</span> 3680<pre>int lua_isboolean (lua_State *L, int index);</pre> 3681 3682<p> 3683Returns 1 if the value at the given index is a boolean, 3684and 0 otherwise. 3685 3686 3687 3688 3689 3690<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p> 3691<span class="apii">[-0, +0, –]</span> 3692<pre>int lua_iscfunction (lua_State *L, int index);</pre> 3693 3694<p> 3695Returns 1 if the value at the given index is a C function, 3696and 0 otherwise. 3697 3698 3699 3700 3701 3702<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p> 3703<span class="apii">[-0, +0, –]</span> 3704<pre>int lua_isfunction (lua_State *L, int index);</pre> 3705 3706<p> 3707Returns 1 if the value at the given index is a function 3708(either C or Lua), and 0 otherwise. 3709 3710 3711 3712 3713 3714<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p> 3715<span class="apii">[-0, +0, –]</span> 3716<pre>int lua_isinteger (lua_State *L, int index);</pre> 3717 3718<p> 3719Returns 1 if the value at the given index is an integer 3720(that is, the value is a number and is represented as an integer), 3721and 0 otherwise. 3722 3723 3724 3725 3726 3727<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p> 3728<span class="apii">[-0, +0, –]</span> 3729<pre>int lua_islightuserdata (lua_State *L, int index);</pre> 3730 3731<p> 3732Returns 1 if the value at the given index is a light userdata, 3733and 0 otherwise. 3734 3735 3736 3737 3738 3739<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p> 3740<span class="apii">[-0, +0, –]</span> 3741<pre>int lua_isnil (lua_State *L, int index);</pre> 3742 3743<p> 3744Returns 1 if the value at the given index is <b>nil</b>, 3745and 0 otherwise. 3746 3747 3748 3749 3750 3751<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p> 3752<span class="apii">[-0, +0, –]</span> 3753<pre>int lua_isnone (lua_State *L, int index);</pre> 3754 3755<p> 3756Returns 1 if the given index is not valid, 3757and 0 otherwise. 3758 3759 3760 3761 3762 3763<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p> 3764<span class="apii">[-0, +0, –]</span> 3765<pre>int lua_isnoneornil (lua_State *L, int index);</pre> 3766 3767<p> 3768Returns 1 if the given index is not valid 3769or if the value at this index is <b>nil</b>, 3770and 0 otherwise. 3771 3772 3773 3774 3775 3776<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p> 3777<span class="apii">[-0, +0, –]</span> 3778<pre>int lua_isnumber (lua_State *L, int index);</pre> 3779 3780<p> 3781Returns 1 if the value at the given index is a number 3782or a string convertible to a number, 3783and 0 otherwise. 3784 3785 3786 3787 3788 3789<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p> 3790<span class="apii">[-0, +0, –]</span> 3791<pre>int lua_isstring (lua_State *L, int index);</pre> 3792 3793<p> 3794Returns 1 if the value at the given index is a string 3795or a number (which is always convertible to a string), 3796and 0 otherwise. 3797 3798 3799 3800 3801 3802<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p> 3803<span class="apii">[-0, +0, –]</span> 3804<pre>int lua_istable (lua_State *L, int index);</pre> 3805 3806<p> 3807Returns 1 if the value at the given index is a table, 3808and 0 otherwise. 3809 3810 3811 3812 3813 3814<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p> 3815<span class="apii">[-0, +0, –]</span> 3816<pre>int lua_isthread (lua_State *L, int index);</pre> 3817 3818<p> 3819Returns 1 if the value at the given index is a thread, 3820and 0 otherwise. 3821 3822 3823 3824 3825 3826<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p> 3827<span class="apii">[-0, +0, –]</span> 3828<pre>int lua_isuserdata (lua_State *L, int index);</pre> 3829 3830<p> 3831Returns 1 if the value at the given index is a userdata 3832(either full or light), and 0 otherwise. 3833 3834 3835 3836 3837 3838<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p> 3839<span class="apii">[-0, +0, –]</span> 3840<pre>int lua_isyieldable (lua_State *L);</pre> 3841 3842<p> 3843Returns 1 if the given coroutine can yield, 3844and 0 otherwise. 3845 3846 3847 3848 3849 3850<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3> 3851<pre>typedef ... lua_KContext;</pre> 3852 3853<p> 3854The type for continuation-function contexts. 3855It must be a numeric type. 3856This type is defined as <code>intptr_t</code> 3857when <code>intptr_t</code> is available, 3858so that it can store pointers too. 3859Otherwise, it is defined as <code>ptrdiff_t</code>. 3860 3861 3862 3863 3864 3865<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3> 3866<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre> 3867 3868<p> 3869Type for continuation functions (see <a href="#4.7">§4.7</a>). 3870 3871 3872 3873 3874 3875<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p> 3876<span class="apii">[-0, +1, <em>e</em>]</span> 3877<pre>void lua_len (lua_State *L, int index);</pre> 3878 3879<p> 3880Returns the length of the value at the given index. 3881It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>) and 3882may trigger a metamethod for the "length" event (see <a href="#2.4">§2.4</a>). 3883The result is pushed on the stack. 3884 3885 3886 3887 3888 3889<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p> 3890<span class="apii">[-0, +1, –]</span> 3891<pre>int lua_load (lua_State *L, 3892 lua_Reader reader, 3893 void *data, 3894 const char *chunkname, 3895 const char *mode);</pre> 3896 3897<p> 3898Loads a Lua chunk without running it. 3899If there are no errors, 3900<code>lua_load</code> pushes the compiled chunk as a Lua 3901function on top of the stack. 3902Otherwise, it pushes an error message. 3903 3904 3905<p> 3906The return values of <code>lua_load</code> are: 3907 3908<ul> 3909 3910<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li> 3911 3912<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> 3913syntax error during precompilation;</li> 3914 3915<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> 3916memory allocation error;</li> 3917 3918<li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> 3919error while running a <code>__gc</code> metamethod. 3920(This error has no relation with the chunk being loaded. 3921It is generated by the garbage collector.) 3922</li> 3923 3924</ul> 3925 3926<p> 3927The <code>lua_load</code> function uses a user-supplied <code>reader</code> function 3928to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>). 3929The <code>data</code> argument is an opaque value passed to the reader function. 3930 3931 3932<p> 3933The <code>chunkname</code> argument gives a name to the chunk, 3934which is used for error messages and in debug information (see <a href="#4.9">§4.9</a>). 3935 3936 3937<p> 3938<code>lua_load</code> automatically detects whether the chunk is text or binary 3939and loads it accordingly (see program <code>luac</code>). 3940The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>, 3941with the addition that 3942a <code>NULL</code> value is equivalent to the string "<code>bt</code>". 3943 3944 3945<p> 3946<code>lua_load</code> uses the stack internally, 3947so the reader function must always leave the stack 3948unmodified when returning. 3949 3950 3951<p> 3952If the resulting function has upvalues, 3953its first upvalue is set to the value of the global environment 3954stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">§4.5</a>). 3955When loading main chunks, 3956this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>). 3957Other upvalues are initialized with <b>nil</b>. 3958 3959 3960 3961 3962 3963<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p> 3964<span class="apii">[-0, +0, –]</span> 3965<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre> 3966 3967<p> 3968Creates a new thread running in a new, independent state. 3969Returns <code>NULL</code> if it cannot create the thread or the state 3970(due to lack of memory). 3971The argument <code>f</code> is the allocator function; 3972Lua does all memory allocation for this state through this function. 3973The second argument, <code>ud</code>, is an opaque pointer that Lua 3974passes to the allocator in every call. 3975 3976 3977 3978 3979 3980<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p> 3981<span class="apii">[-0, +1, <em>e</em>]</span> 3982<pre>void lua_newtable (lua_State *L);</pre> 3983 3984<p> 3985Creates a new empty table and pushes it onto the stack. 3986It is equivalent to <code>lua_createtable(L, 0, 0)</code>. 3987 3988 3989 3990 3991 3992<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p> 3993<span class="apii">[-0, +1, <em>e</em>]</span> 3994<pre>lua_State *lua_newthread (lua_State *L);</pre> 3995 3996<p> 3997Creates a new thread, pushes it on the stack, 3998and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread. 3999The new thread returned by this function shares with the original thread 4000its global environment, 4001but has an independent execution stack. 4002 4003 4004<p> 4005There is no explicit function to close or to destroy a thread. 4006Threads are subject to garbage collection, 4007like any Lua object. 4008 4009 4010 4011 4012 4013<hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p> 4014<span class="apii">[-0, +1, <em>e</em>]</span> 4015<pre>void *lua_newuserdata (lua_State *L, size_t size);</pre> 4016 4017<p> 4018This function allocates a new block of memory with the given size, 4019pushes onto the stack a new full userdata with the block address, 4020and returns this address. 4021The host program can freely use this memory. 4022 4023 4024 4025 4026 4027<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p> 4028<span class="apii">[-1, +(2|0), <em>e</em>]</span> 4029<pre>int lua_next (lua_State *L, int index);</pre> 4030 4031<p> 4032Pops a key from the stack, 4033and pushes a key–value pair from the table at the given index 4034(the "next" pair after the given key). 4035If there are no more elements in the table, 4036then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing). 4037 4038 4039<p> 4040A typical traversal looks like this: 4041 4042<pre> 4043 /* table is in the stack at index 't' */ 4044 lua_pushnil(L); /* first key */ 4045 while (lua_next(L, t) != 0) { 4046 /* uses 'key' (at index -2) and 'value' (at index -1) */ 4047 printf("%s - %s\n", 4048 lua_typename(L, lua_type(L, -2)), 4049 lua_typename(L, lua_type(L, -1))); 4050 /* removes 'value'; keeps 'key' for next iteration */ 4051 lua_pop(L, 1); 4052 } 4053</pre> 4054 4055<p> 4056While traversing a table, 4057do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key, 4058unless you know that the key is actually a string. 4059Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change 4060the value at the given index; 4061this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>. 4062 4063 4064<p> 4065See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying 4066the table during its traversal. 4067 4068 4069 4070 4071 4072<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3> 4073<pre>typedef ... lua_Number;</pre> 4074 4075<p> 4076The type of floats in Lua. 4077 4078 4079<p> 4080By default this type is double, 4081but that can be changed to a single float or a long double. 4082(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.) 4083 4084 4085 4086 4087 4088<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3> 4089<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre> 4090 4091<p> 4092Converts a Lua float to a Lua integer. 4093This macro assumes that <code>n</code> has an integral value. 4094If that value is within the range of Lua integers, 4095it is converted to an integer and assigned to <code>*p</code>. 4096The macro results in a boolean indicating whether the 4097conversion was successful. 4098(Note that this range test can be tricky to do 4099correctly without this macro, 4100due to roundings.) 4101 4102 4103<p> 4104This macro may evaluate its arguments more than once. 4105 4106 4107 4108 4109 4110<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p> 4111<span class="apii">[-(nargs + 1), +(nresults|1), –]</span> 4112<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre> 4113 4114<p> 4115Calls a function in protected mode. 4116 4117 4118<p> 4119Both <code>nargs</code> and <code>nresults</code> have the same meaning as 4120in <a href="#lua_call"><code>lua_call</code></a>. 4121If there are no errors during the call, 4122<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>. 4123However, if there is any error, 4124<a href="#lua_pcall"><code>lua_pcall</code></a> catches it, 4125pushes a single value on the stack (the error message), 4126and returns an error code. 4127Like <a href="#lua_call"><code>lua_call</code></a>, 4128<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function 4129and its arguments from the stack. 4130 4131 4132<p> 4133If <code>msgh</code> is 0, 4134then the error message returned on the stack 4135is exactly the original error message. 4136Otherwise, <code>msgh</code> is the stack index of a 4137<em>message handler</em>. 4138(This index cannot be a pseudo-index.) 4139In case of runtime errors, 4140this function will be called with the error message 4141and its return value will be the message 4142returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>. 4143 4144 4145<p> 4146Typically, the message handler is used to add more debug 4147information to the error message, such as a stack traceback. 4148Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>, 4149since by then the stack has unwound. 4150 4151 4152<p> 4153The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants 4154(defined in <code>lua.h</code>): 4155 4156<ul> 4157 4158<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> 4159success.</li> 4160 4161<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> 4162a runtime error. 4163</li> 4164 4165<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> 4166memory allocation error. 4167For such errors, Lua does not call the message handler. 4168</li> 4169 4170<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> 4171error while running the message handler. 4172</li> 4173 4174<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> 4175error while running a <code>__gc</code> metamethod. 4176(This error typically has no relation with the function being called.) 4177</li> 4178 4179</ul> 4180 4181 4182 4183 4184<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p> 4185<span class="apii">[-(nargs + 1), +(nresults|1), –]</span> 4186<pre>int lua_pcallk (lua_State *L, 4187 int nargs, 4188 int nresults, 4189 int msgh, 4190 lua_KContext ctx, 4191 lua_KFunction k);</pre> 4192 4193<p> 4194This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>, 4195but allows the called function to yield (see <a href="#4.7">§4.7</a>). 4196 4197 4198 4199 4200 4201<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p> 4202<span class="apii">[-n, +0, –]</span> 4203<pre>void lua_pop (lua_State *L, int n);</pre> 4204 4205<p> 4206Pops <code>n</code> elements from the stack. 4207 4208 4209 4210 4211 4212<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p> 4213<span class="apii">[-0, +1, –]</span> 4214<pre>void lua_pushboolean (lua_State *L, int b);</pre> 4215 4216<p> 4217Pushes a boolean value with value <code>b</code> onto the stack. 4218 4219 4220 4221 4222 4223<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p> 4224<span class="apii">[-n, +1, <em>e</em>]</span> 4225<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre> 4226 4227<p> 4228Pushes a new C closure onto the stack. 4229 4230 4231<p> 4232When a C function is created, 4233it is possible to associate some values with it, 4234thus creating a C closure (see <a href="#4.4">§4.4</a>); 4235these values are then accessible to the function whenever it is called. 4236To associate values with a C function, 4237first these values must be pushed onto the stack 4238(when there are multiple values, the first value is pushed first). 4239Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> 4240is called to create and push the C function onto the stack, 4241with the argument <code>n</code> telling how many values will be 4242associated with the function. 4243<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack. 4244 4245 4246<p> 4247The maximum value for <code>n</code> is 255. 4248 4249 4250<p> 4251When <code>n</code> is zero, 4252this function creates a <em>light C function</em>, 4253which is just a pointer to the C function. 4254In that case, it never raises a memory error. 4255 4256 4257 4258 4259 4260<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p> 4261<span class="apii">[-0, +1, –]</span> 4262<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre> 4263 4264<p> 4265Pushes a C function onto the stack. 4266This function receives a pointer to a C function 4267and pushes onto the stack a Lua value of type <code>function</code> that, 4268when called, invokes the corresponding C function. 4269 4270 4271<p> 4272Any function to be callable by Lua must 4273follow the correct protocol to receive its parameters 4274and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 4275 4276 4277 4278 4279 4280<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p> 4281<span class="apii">[-0, +1, <em>e</em>]</span> 4282<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre> 4283 4284<p> 4285Pushes onto the stack a formatted string 4286and returns a pointer to this string. 4287It is similar to the ISO C function <code>sprintf</code>, 4288but has some important differences: 4289 4290<ul> 4291 4292<li> 4293You do not have to allocate space for the result: 4294the result is a Lua string and Lua takes care of memory allocation 4295(and deallocation, through garbage collection). 4296</li> 4297 4298<li> 4299The conversion specifiers are quite restricted. 4300There are no flags, widths, or precisions. 4301The conversion specifiers can only be 4302'<code>%%</code>' (inserts the character '<code>%</code>'), 4303'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions), 4304'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>), 4305'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>), 4306'<code>%p</code>' (inserts a pointer as a hexadecimal numeral), 4307'<code>%d</code>' (inserts an <code>int</code>), 4308'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and 4309'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence). 4310</li> 4311 4312</ul> 4313 4314 4315 4316 4317<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p> 4318<span class="apii">[-0, +1, –]</span> 4319<pre>void lua_pushglobaltable (lua_State *L);</pre> 4320 4321<p> 4322Pushes the global environment onto the stack. 4323 4324 4325 4326 4327 4328<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p> 4329<span class="apii">[-0, +1, –]</span> 4330<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre> 4331 4332<p> 4333Pushes an integer with value <code>n</code> onto the stack. 4334 4335 4336 4337 4338 4339<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p> 4340<span class="apii">[-0, +1, –]</span> 4341<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre> 4342 4343<p> 4344Pushes a light userdata onto the stack. 4345 4346 4347<p> 4348Userdata represent C values in Lua. 4349A <em>light userdata</em> represents a pointer, a <code>void*</code>. 4350It is a value (like a number): 4351you do not create it, it has no individual metatable, 4352and it is not collected (as it was never created). 4353A light userdata is equal to "any" 4354light userdata with the same C address. 4355 4356 4357 4358 4359 4360<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p> 4361<span class="apii">[-0, +1, <em>e</em>]</span> 4362<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre> 4363 4364<p> 4365This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>, 4366but should be used only when <code>s</code> is a literal string. 4367 4368 4369 4370 4371 4372<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p> 4373<span class="apii">[-0, +1, <em>e</em>]</span> 4374<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre> 4375 4376<p> 4377Pushes the string pointed to by <code>s</code> with size <code>len</code> 4378onto the stack. 4379Lua makes (or reuses) an internal copy of the given string, 4380so the memory at <code>s</code> can be freed or reused immediately after 4381the function returns. 4382The string can contain any binary data, 4383including embedded zeros. 4384 4385 4386<p> 4387Returns a pointer to the internal copy of the string. 4388 4389 4390 4391 4392 4393<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p> 4394<span class="apii">[-0, +1, –]</span> 4395<pre>void lua_pushnil (lua_State *L);</pre> 4396 4397<p> 4398Pushes a nil value onto the stack. 4399 4400 4401 4402 4403 4404<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p> 4405<span class="apii">[-0, +1, –]</span> 4406<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre> 4407 4408<p> 4409Pushes a float with value <code>n</code> onto the stack. 4410 4411 4412 4413 4414 4415<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p> 4416<span class="apii">[-0, +1, <em>e</em>]</span> 4417<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre> 4418 4419<p> 4420Pushes the zero-terminated string pointed to by <code>s</code> 4421onto the stack. 4422Lua makes (or reuses) an internal copy of the given string, 4423so the memory at <code>s</code> can be freed or reused immediately after 4424the function returns. 4425 4426 4427<p> 4428Returns a pointer to the internal copy of the string. 4429 4430 4431<p> 4432If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>. 4433 4434 4435 4436 4437 4438<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p> 4439<span class="apii">[-0, +1, –]</span> 4440<pre>int lua_pushthread (lua_State *L);</pre> 4441 4442<p> 4443Pushes the thread represented by <code>L</code> onto the stack. 4444Returns 1 if this thread is the main thread of its state. 4445 4446 4447 4448 4449 4450<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p> 4451<span class="apii">[-0, +1, –]</span> 4452<pre>void lua_pushvalue (lua_State *L, int index);</pre> 4453 4454<p> 4455Pushes a copy of the element at the given index 4456onto the stack. 4457 4458 4459 4460 4461 4462<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p> 4463<span class="apii">[-0, +1, <em>e</em>]</span> 4464<pre>const char *lua_pushvfstring (lua_State *L, 4465 const char *fmt, 4466 va_list argp);</pre> 4467 4468<p> 4469Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code> 4470instead of a variable number of arguments. 4471 4472 4473 4474 4475 4476<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p> 4477<span class="apii">[-0, +0, –]</span> 4478<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre> 4479 4480<p> 4481Returns 1 if the two values in indices <code>index1</code> and 4482<code>index2</code> are primitively equal 4483(that is, without calling metamethods). 4484Otherwise returns 0. 4485Also returns 0 if any of the indices are not valid. 4486 4487 4488 4489 4490 4491<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p> 4492<span class="apii">[-1, +1, –]</span> 4493<pre>int lua_rawget (lua_State *L, int index);</pre> 4494 4495<p> 4496Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access 4497(i.e., without metamethods). 4498 4499 4500 4501 4502 4503<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p> 4504<span class="apii">[-0, +1, –]</span> 4505<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre> 4506 4507<p> 4508Pushes onto the stack the value <code>t[n]</code>, 4509where <code>t</code> is the table at the given index. 4510The access is raw; 4511that is, it does not invoke metamethods. 4512 4513 4514<p> 4515Returns the type of the pushed value. 4516 4517 4518 4519 4520 4521<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p> 4522<span class="apii">[-0, +1, –]</span> 4523<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre> 4524 4525<p> 4526Pushes onto the stack the value <code>t[k]</code>, 4527where <code>t</code> is the table at the given index and 4528<code>k</code> is the pointer <code>p</code> represented as a light userdata. 4529The access is raw; 4530that is, it does not invoke metamethods. 4531 4532 4533<p> 4534Returns the type of the pushed value. 4535 4536 4537 4538 4539 4540<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p> 4541<span class="apii">[-0, +0, –]</span> 4542<pre>size_t lua_rawlen (lua_State *L, int index);</pre> 4543 4544<p> 4545Returns the raw "length" of the value at the given index: 4546for strings, this is the string length; 4547for tables, this is the result of the length operator ('<code>#</code>') 4548with no metamethods; 4549for userdata, this is the size of the block of memory allocated 4550for the userdata; 4551for other values, it is 0. 4552 4553 4554 4555 4556 4557<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p> 4558<span class="apii">[-2, +0, <em>e</em>]</span> 4559<pre>void lua_rawset (lua_State *L, int index);</pre> 4560 4561<p> 4562Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment 4563(i.e., without metamethods). 4564 4565 4566 4567 4568 4569<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p> 4570<span class="apii">[-1, +0, <em>e</em>]</span> 4571<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre> 4572 4573<p> 4574Does the equivalent of <code>t[i] = v</code>, 4575where <code>t</code> is the table at the given index 4576and <code>v</code> is the value at the top of the stack. 4577 4578 4579<p> 4580This function pops the value from the stack. 4581The assignment is raw; 4582that is, it does not invoke metamethods. 4583 4584 4585 4586 4587 4588<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p> 4589<span class="apii">[-1, +0, <em>e</em>]</span> 4590<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre> 4591 4592<p> 4593Does the equivalent of <code>t[p] = v</code>, 4594where <code>t</code> is the table at the given index, 4595<code>p</code> is encoded as a light userdata, 4596and <code>v</code> is the value at the top of the stack. 4597 4598 4599<p> 4600This function pops the value from the stack. 4601The assignment is raw; 4602that is, it does not invoke metamethods. 4603 4604 4605 4606 4607 4608<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3> 4609<pre>typedef const char * (*lua_Reader) (lua_State *L, 4610 void *data, 4611 size_t *size);</pre> 4612 4613<p> 4614The reader function used by <a href="#lua_load"><code>lua_load</code></a>. 4615Every time it needs another piece of the chunk, 4616<a href="#lua_load"><code>lua_load</code></a> calls the reader, 4617passing along its <code>data</code> parameter. 4618The reader must return a pointer to a block of memory 4619with a new piece of the chunk 4620and set <code>size</code> to the block size. 4621The block must exist until the reader function is called again. 4622To signal the end of the chunk, 4623the reader must return <code>NULL</code> or set <code>size</code> to zero. 4624The reader function may return pieces of any size greater than zero. 4625 4626 4627 4628 4629 4630<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p> 4631<span class="apii">[-0, +0, <em>e</em>]</span> 4632<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre> 4633 4634<p> 4635Sets the C function <code>f</code> as the new value of global <code>name</code>. 4636It is defined as a macro: 4637 4638<pre> 4639 #define lua_register(L,n,f) \ 4640 (lua_pushcfunction(L, f), lua_setglobal(L, n)) 4641</pre> 4642 4643 4644 4645 4646<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p> 4647<span class="apii">[-1, +0, –]</span> 4648<pre>void lua_remove (lua_State *L, int index);</pre> 4649 4650<p> 4651Removes the element at the given valid index, 4652shifting down the elements above this index to fill the gap. 4653This function cannot be called with a pseudo-index, 4654because a pseudo-index is not an actual stack position. 4655 4656 4657 4658 4659 4660<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p> 4661<span class="apii">[-1, +0, –]</span> 4662<pre>void lua_replace (lua_State *L, int index);</pre> 4663 4664<p> 4665Moves the top element into the given valid index 4666without shifting any element 4667(therefore replacing the value at that given index), 4668and then pops the top element. 4669 4670 4671 4672 4673 4674<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p> 4675<span class="apii">[-?, +?, –]</span> 4676<pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre> 4677 4678<p> 4679Starts and resumes a coroutine in the given thread <code>L</code>. 4680 4681 4682<p> 4683To start a coroutine, 4684you push onto the thread stack the main function plus any arguments; 4685then you call <a href="#lua_resume"><code>lua_resume</code></a>, 4686with <code>nargs</code> being the number of arguments. 4687This call returns when the coroutine suspends or finishes its execution. 4688When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>, 4689or all values returned by the body function. 4690<a href="#lua_resume"><code>lua_resume</code></a> returns 4691<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields, 4692<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution 4693without errors, 4694or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>). 4695 4696 4697<p> 4698In case of errors, 4699the stack is not unwound, 4700so you can use the debug API over it. 4701The error message is on the top of the stack. 4702 4703 4704<p> 4705To resume a coroutine, 4706you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>, 4707put on its stack only the values to 4708be passed as results from <code>yield</code>, 4709and then call <a href="#lua_resume"><code>lua_resume</code></a>. 4710 4711 4712<p> 4713The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>. 4714If there is no such coroutine, 4715this parameter can be <code>NULL</code>. 4716 4717 4718 4719 4720 4721<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p> 4722<span class="apii">[-0, +0, –]</span> 4723<pre>void lua_rotate (lua_State *L, int idx, int n);</pre> 4724 4725<p> 4726Rotates the stack elements between the valid index <code>idx</code> 4727and the top of the stack. 4728The elements are rotated <code>n</code> positions in the direction of the top, 4729for a positive <code>n</code>, 4730or <code>-n</code> positions in the direction of the bottom, 4731for a negative <code>n</code>. 4732The absolute value of <code>n</code> must not be greater than the size 4733of the slice being rotated. 4734This function cannot be called with a pseudo-index, 4735because a pseudo-index is not an actual stack position. 4736 4737 4738 4739 4740 4741<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p> 4742<span class="apii">[-0, +0, –]</span> 4743<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre> 4744 4745<p> 4746Changes the allocator function of a given state to <code>f</code> 4747with user data <code>ud</code>. 4748 4749 4750 4751 4752 4753<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p> 4754<span class="apii">[-1, +0, <em>e</em>]</span> 4755<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre> 4756 4757<p> 4758Does the equivalent to <code>t[k] = v</code>, 4759where <code>t</code> is the value at the given index 4760and <code>v</code> is the value at the top of the stack. 4761 4762 4763<p> 4764This function pops the value from the stack. 4765As in Lua, this function may trigger a metamethod 4766for the "newindex" event (see <a href="#2.4">§2.4</a>). 4767 4768 4769 4770 4771 4772<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p> 4773<span class="apii">[-1, +0, <em>e</em>]</span> 4774<pre>void lua_setglobal (lua_State *L, const char *name);</pre> 4775 4776<p> 4777Pops a value from the stack and 4778sets it as the new value of global <code>name</code>. 4779 4780 4781 4782 4783 4784<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p> 4785<span class="apii">[-1, +0, <em>e</em>]</span> 4786<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre> 4787 4788<p> 4789Does the equivalent to <code>t[n] = v</code>, 4790where <code>t</code> is the value at the given index 4791and <code>v</code> is the value at the top of the stack. 4792 4793 4794<p> 4795This function pops the value from the stack. 4796As in Lua, this function may trigger a metamethod 4797for the "newindex" event (see <a href="#2.4">§2.4</a>). 4798 4799 4800 4801 4802 4803<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p> 4804<span class="apii">[-1, +0, –]</span> 4805<pre>void lua_setmetatable (lua_State *L, int index);</pre> 4806 4807<p> 4808Pops a table from the stack and 4809sets it as the new metatable for the value at the given index. 4810 4811 4812 4813 4814 4815<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p> 4816<span class="apii">[-2, +0, <em>e</em>]</span> 4817<pre>void lua_settable (lua_State *L, int index);</pre> 4818 4819<p> 4820Does the equivalent to <code>t[k] = v</code>, 4821where <code>t</code> is the value at the given index, 4822<code>v</code> is the value at the top of the stack, 4823and <code>k</code> is the value just below the top. 4824 4825 4826<p> 4827This function pops both the key and the value from the stack. 4828As in Lua, this function may trigger a metamethod 4829for the "newindex" event (see <a href="#2.4">§2.4</a>). 4830 4831 4832 4833 4834 4835<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p> 4836<span class="apii">[-?, +?, –]</span> 4837<pre>void lua_settop (lua_State *L, int index);</pre> 4838 4839<p> 4840Accepts any index, or 0, 4841and sets the stack top to this index. 4842If the new top is larger than the old one, 4843then the new elements are filled with <b>nil</b>. 4844If <code>index</code> is 0, then all stack elements are removed. 4845 4846 4847 4848 4849 4850<hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p> 4851<span class="apii">[-1, +0, –]</span> 4852<pre>void lua_setuservalue (lua_State *L, int index);</pre> 4853 4854<p> 4855Pops a value from the stack and sets it as 4856the new value associated to the userdata at the given index. 4857 4858 4859 4860 4861 4862<hr><h3><a name="lua_State"><code>lua_State</code></a></h3> 4863<pre>typedef struct lua_State lua_State;</pre> 4864 4865<p> 4866An opaque structure that points to a thread and indirectly 4867(through the thread) to the whole state of a Lua interpreter. 4868The Lua library is fully reentrant: 4869it has no global variables. 4870All information about a state is accessible through this structure. 4871 4872 4873<p> 4874A pointer to this structure must be passed as the first argument to 4875every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>, 4876which creates a Lua state from scratch. 4877 4878 4879 4880 4881 4882<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p> 4883<span class="apii">[-0, +0, –]</span> 4884<pre>int lua_status (lua_State *L);</pre> 4885 4886<p> 4887Returns the status of the thread <code>L</code>. 4888 4889 4890<p> 4891The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread, 4892an error code if the thread finished the execution 4893of a <a href="#lua_resume"><code>lua_resume</code></a> with an error, 4894or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended. 4895 4896 4897<p> 4898You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>. 4899You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> 4900(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> 4901(to resume a coroutine). 4902 4903 4904 4905 4906 4907<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p> 4908<span class="apii">[-0, +1, –]</span> 4909<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre> 4910 4911<p> 4912Converts the zero-terminated string <code>s</code> to a number, 4913pushes that number into the stack, 4914and returns the total size of the string, 4915that is, its length plus one. 4916The conversion can result in an integer or a float, 4917according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>). 4918The string may have leading and trailing spaces and a sign. 4919If the string is not a valid numeral, 4920returns 0 and pushes nothing. 4921(Note that the result can be used as a boolean, 4922true if the conversion succeeds.) 4923 4924 4925 4926 4927 4928<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p> 4929<span class="apii">[-0, +0, –]</span> 4930<pre>int lua_toboolean (lua_State *L, int index);</pre> 4931 4932<p> 4933Converts the Lua value at the given index to a C boolean 4934value (0 or 1). 4935Like all tests in Lua, 4936<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value 4937different from <b>false</b> and <b>nil</b>; 4938otherwise it returns false. 4939(If you want to accept only actual boolean values, 4940use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.) 4941 4942 4943 4944 4945 4946<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p> 4947<span class="apii">[-0, +0, –]</span> 4948<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre> 4949 4950<p> 4951Converts a value at the given index to a C function. 4952That value must be a C function; 4953otherwise, returns <code>NULL</code>. 4954 4955 4956 4957 4958 4959<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p> 4960<span class="apii">[-0, +0, –]</span> 4961<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre> 4962 4963<p> 4964Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>. 4965 4966 4967 4968 4969 4970<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p> 4971<span class="apii">[-0, +0, –]</span> 4972<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre> 4973 4974<p> 4975Converts the Lua value at the given index 4976to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>. 4977The Lua value must be an integer, 4978or a number or string convertible to an integer (see <a href="#3.4.3">§3.4.3</a>); 4979otherwise, <code>lua_tointegerx</code> returns 0. 4980 4981 4982<p> 4983If <code>isnum</code> is not <code>NULL</code>, 4984its referent is assigned a boolean value that 4985indicates whether the operation succeeded. 4986 4987 4988 4989 4990 4991<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p> 4992<span class="apii">[-0, +0, <em>e</em>]</span> 4993<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre> 4994 4995<p> 4996Converts the Lua value at the given index to a C string. 4997If <code>len</code> is not <code>NULL</code>, 4998it also sets <code>*len</code> with the string length. 4999The Lua value must be a string or a number; 5000otherwise, the function returns <code>NULL</code>. 5001If the value is a number, 5002then <code>lua_tolstring</code> also 5003<em>changes the actual value in the stack to a string</em>. 5004(This change confuses <a href="#lua_next"><code>lua_next</code></a> 5005when <code>lua_tolstring</code> is applied to keys during a table traversal.) 5006 5007 5008<p> 5009<code>lua_tolstring</code> returns a fully aligned pointer 5010to a string inside the Lua state. 5011This string always has a zero ('<code>\0</code>') 5012after its last character (as in C), 5013but can contain other zeros in its body. 5014 5015 5016<p> 5017Because Lua has garbage collection, 5018there is no guarantee that the pointer returned by <code>lua_tolstring</code> 5019will be valid after the corresponding Lua value is removed from the stack. 5020 5021 5022 5023 5024 5025<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p> 5026<span class="apii">[-0, +0, –]</span> 5027<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre> 5028 5029<p> 5030Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>. 5031 5032 5033 5034 5035 5036<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p> 5037<span class="apii">[-0, +0, –]</span> 5038<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre> 5039 5040<p> 5041Converts the Lua value at the given index 5042to the C type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>). 5043The Lua value must be a number or a string convertible to a number 5044(see <a href="#3.4.3">§3.4.3</a>); 5045otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns 0. 5046 5047 5048<p> 5049If <code>isnum</code> is not <code>NULL</code>, 5050its referent is assigned a boolean value that 5051indicates whether the operation succeeded. 5052 5053 5054 5055 5056 5057<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p> 5058<span class="apii">[-0, +0, –]</span> 5059<pre>const void *lua_topointer (lua_State *L, int index);</pre> 5060 5061<p> 5062Converts the value at the given index to a generic 5063C pointer (<code>void*</code>). 5064The value can be a userdata, a table, a thread, or a function; 5065otherwise, <code>lua_topointer</code> returns <code>NULL</code>. 5066Different objects will give different pointers. 5067There is no way to convert the pointer back to its original value. 5068 5069 5070<p> 5071Typically this function is used only for hashing and debug information. 5072 5073 5074 5075 5076 5077<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p> 5078<span class="apii">[-0, +0, <em>e</em>]</span> 5079<pre>const char *lua_tostring (lua_State *L, int index);</pre> 5080 5081<p> 5082Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>. 5083 5084 5085 5086 5087 5088<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p> 5089<span class="apii">[-0, +0, –]</span> 5090<pre>lua_State *lua_tothread (lua_State *L, int index);</pre> 5091 5092<p> 5093Converts the value at the given index to a Lua thread 5094(represented as <code>lua_State*</code>). 5095This value must be a thread; 5096otherwise, the function returns <code>NULL</code>. 5097 5098 5099 5100 5101 5102<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p> 5103<span class="apii">[-0, +0, –]</span> 5104<pre>void *lua_touserdata (lua_State *L, int index);</pre> 5105 5106<p> 5107If the value at the given index is a full userdata, 5108returns its block address. 5109If the value is a light userdata, 5110returns its pointer. 5111Otherwise, returns <code>NULL</code>. 5112 5113 5114 5115 5116 5117<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p> 5118<span class="apii">[-0, +0, –]</span> 5119<pre>int lua_type (lua_State *L, int index);</pre> 5120 5121<p> 5122Returns the type of the value in the given valid index, 5123or <code>LUA_TNONE</code> for a non-valid (but acceptable) index. 5124The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants 5125defined in <code>lua.h</code>: 5126<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a> (0), 5127<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>, 5128<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>, 5129<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, 5130<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, 5131<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>, 5132<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, 5133<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>, 5134and 5135<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>. 5136 5137 5138 5139 5140 5141<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p> 5142<span class="apii">[-0, +0, –]</span> 5143<pre>const char *lua_typename (lua_State *L, int tp);</pre> 5144 5145<p> 5146Returns the name of the type encoded by the value <code>tp</code>, 5147which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>. 5148 5149 5150 5151 5152 5153<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3> 5154<pre>typedef ... lua_Unsigned;</pre> 5155 5156<p> 5157The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>. 5158 5159 5160 5161 5162 5163<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p> 5164<span class="apii">[-0, +0, –]</span> 5165<pre>int lua_upvalueindex (int i);</pre> 5166 5167<p> 5168Returns the pseudo-index that represents the <code>i</code>-th upvalue of 5169the running function (see <a href="#4.4">§4.4</a>). 5170 5171 5172 5173 5174 5175<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p> 5176<span class="apii">[-0, +0, <em>v</em>]</span> 5177<pre>const lua_Number *lua_version (lua_State *L);</pre> 5178 5179<p> 5180Returns the address of the version number stored in the Lua core. 5181When called with a valid <a href="#lua_State"><code>lua_State</code></a>, 5182returns the address of the version used to create that state. 5183When called with <code>NULL</code>, 5184returns the address of the version running the call. 5185 5186 5187 5188 5189 5190<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3> 5191<pre>typedef int (*lua_Writer) (lua_State *L, 5192 const void* p, 5193 size_t sz, 5194 void* ud);</pre> 5195 5196<p> 5197The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>. 5198Every time it produces another piece of chunk, 5199<a href="#lua_dump"><code>lua_dump</code></a> calls the writer, 5200passing along the buffer to be written (<code>p</code>), 5201its size (<code>sz</code>), 5202and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>. 5203 5204 5205<p> 5206The writer returns an error code: 52070 means no errors; 5208any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from 5209calling the writer again. 5210 5211 5212 5213 5214 5215<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p> 5216<span class="apii">[-?, +?, –]</span> 5217<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre> 5218 5219<p> 5220Exchange values between different threads of the same state. 5221 5222 5223<p> 5224This function pops <code>n</code> values from the stack <code>from</code>, 5225and pushes them onto the stack <code>to</code>. 5226 5227 5228 5229 5230 5231<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p> 5232<span class="apii">[-?, +?, <em>e</em>]</span> 5233<pre>int lua_yield (lua_State *L, int nresults);</pre> 5234 5235<p> 5236This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5237but it has no continuation (see <a href="#4.7">§4.7</a>). 5238Therefore, when the thread resumes, 5239it continues the function that called 5240the function calling <code>lua_yield</code>. 5241 5242 5243 5244 5245 5246<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p> 5247<span class="apii">[-?, +?, <em>e</em>]</span> 5248<pre>int lua_yieldk (lua_State *L, 5249 int nresults, 5250 lua_KContext ctx, 5251 lua_KFunction k);</pre> 5252 5253<p> 5254Yields a coroutine (thread). 5255 5256 5257<p> 5258When a C function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5259the running coroutine suspends its execution, 5260and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns. 5261The parameter <code>nresults</code> is the number of values from the stack 5262that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>. 5263 5264 5265<p> 5266When the coroutine is resumed again, 5267Lua calls the given continuation function <code>k</code> to continue 5268the execution of the C function that yielded (see <a href="#4.7">§4.7</a>). 5269This continuation function receives the same stack 5270from the previous function, 5271with the <code>n</code> results removed and 5272replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>. 5273Moreover, 5274the continuation function receives the value <code>ctx</code> 5275that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>. 5276 5277 5278<p> 5279Usually, this function does not return; 5280when the coroutine eventually resumes, 5281it continues executing the continuation function. 5282However, there is one special case, 5283which is when this function is called 5284from inside a line hook (see <a href="#4.9">§4.9</a>). 5285In that case, <code>lua_yieldk</code> should be called with no continuation 5286(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>), 5287and the hook should return immediately after the call. 5288Lua will yield and, 5289when the coroutine resumes again, 5290it will continue the normal execution 5291of the (Lua) function that triggered the hook. 5292 5293 5294<p> 5295This function can raise an error if it is called from a thread 5296with a pending C call with no continuation function, 5297or it is called from a thread that is not running inside a resume 5298(e.g., the main thread). 5299 5300 5301 5302 5303 5304 5305 5306<h2>4.9 – <a name="4.9">The Debug Interface</a></h2> 5307 5308<p> 5309Lua has no built-in debugging facilities. 5310Instead, it offers a special interface 5311by means of functions and <em>hooks</em>. 5312This interface allows the construction of different 5313kinds of debuggers, profilers, and other tools 5314that need "inside information" from the interpreter. 5315 5316 5317 5318<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3> 5319<pre>typedef struct lua_Debug { 5320 int event; 5321 const char *name; /* (n) */ 5322 const char *namewhat; /* (n) */ 5323 const char *what; /* (S) */ 5324 const char *source; /* (S) */ 5325 int currentline; /* (l) */ 5326 int linedefined; /* (S) */ 5327 int lastlinedefined; /* (S) */ 5328 unsigned char nups; /* (u) number of upvalues */ 5329 unsigned char nparams; /* (u) number of parameters */ 5330 char isvararg; /* (u) */ 5331 char istailcall; /* (t) */ 5332 char short_src[LUA_IDSIZE]; /* (S) */ 5333 /* private part */ 5334 <em>other fields</em> 5335} lua_Debug;</pre> 5336 5337<p> 5338A structure used to carry different pieces of 5339information about a function or an activation record. 5340<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part 5341of this structure, for later use. 5342To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information, 5343call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. 5344 5345 5346<p> 5347The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning: 5348 5349<ul> 5350 5351<li><b><code>source</code>: </b> 5352the name of the chunk that created the function. 5353If <code>source</code> starts with a '<code>@</code>', 5354it means that the function was defined in a file where 5355the file name follows the '<code>@</code>'. 5356If <code>source</code> starts with a '<code>=</code>', 5357the remainder of its contents describe the source in a user-dependent manner. 5358Otherwise, 5359the function was defined in a string where 5360<code>source</code> is that string. 5361</li> 5362 5363<li><b><code>short_src</code>: </b> 5364a "printable" version of <code>source</code>, to be used in error messages. 5365</li> 5366 5367<li><b><code>linedefined</code>: </b> 5368the line number where the definition of the function starts. 5369</li> 5370 5371<li><b><code>lastlinedefined</code>: </b> 5372the line number where the definition of the function ends. 5373</li> 5374 5375<li><b><code>what</code>: </b> 5376the string <code>"Lua"</code> if the function is a Lua function, 5377<code>"C"</code> if it is a C function, 5378<code>"main"</code> if it is the main part of a chunk. 5379</li> 5380 5381<li><b><code>currentline</code>: </b> 5382the current line where the given function is executing. 5383When no line information is available, 5384<code>currentline</code> is set to -1. 5385</li> 5386 5387<li><b><code>name</code>: </b> 5388a reasonable name for the given function. 5389Because functions in Lua are first-class values, 5390they do not have a fixed name: 5391some functions can be the value of multiple global variables, 5392while others can be stored only in a table field. 5393The <code>lua_getinfo</code> function checks how the function was 5394called to find a suitable name. 5395If it cannot find a name, 5396then <code>name</code> is set to <code>NULL</code>. 5397</li> 5398 5399<li><b><code>namewhat</code>: </b> 5400explains the <code>name</code> field. 5401The value of <code>namewhat</code> can be 5402<code>"global"</code>, <code>"local"</code>, <code>"method"</code>, 5403<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string), 5404according to how the function was called. 5405(Lua uses the empty string when no other option seems to apply.) 5406</li> 5407 5408<li><b><code>istailcall</code>: </b> 5409true if this function invocation was called by a tail call. 5410In this case, the caller of this level is not in the stack. 5411</li> 5412 5413<li><b><code>nups</code>: </b> 5414the number of upvalues of the function. 5415</li> 5416 5417<li><b><code>nparams</code>: </b> 5418the number of fixed parameters of the function 5419(always 0 for C functions). 5420</li> 5421 5422<li><b><code>isvararg</code>: </b> 5423true if the function is a vararg function 5424(always true for C functions). 5425</li> 5426 5427</ul> 5428 5429 5430 5431 5432<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p> 5433<span class="apii">[-0, +0, –]</span> 5434<pre>lua_Hook lua_gethook (lua_State *L);</pre> 5435 5436<p> 5437Returns the current hook function. 5438 5439 5440 5441 5442 5443<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p> 5444<span class="apii">[-0, +0, –]</span> 5445<pre>int lua_gethookcount (lua_State *L);</pre> 5446 5447<p> 5448Returns the current hook count. 5449 5450 5451 5452 5453 5454<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p> 5455<span class="apii">[-0, +0, –]</span> 5456<pre>int lua_gethookmask (lua_State *L);</pre> 5457 5458<p> 5459Returns the current hook mask. 5460 5461 5462 5463 5464 5465<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p> 5466<span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span> 5467<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre> 5468 5469<p> 5470Gets information about a specific function or function invocation. 5471 5472 5473<p> 5474To get information about a function invocation, 5475the parameter <code>ar</code> must be a valid activation record that was 5476filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or 5477given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). 5478 5479 5480<p> 5481To get information about a function you push it onto the stack 5482and start the <code>what</code> string with the character '<code>></code>'. 5483(In that case, 5484<code>lua_getinfo</code> pops the function from the top of the stack.) 5485For instance, to know in which line a function <code>f</code> was defined, 5486you can write the following code: 5487 5488<pre> 5489 lua_Debug ar; 5490 lua_getglobal(L, "f"); /* get global 'f' */ 5491 lua_getinfo(L, ">S", &ar); 5492 printf("%d\n", ar.linedefined); 5493</pre> 5494 5495<p> 5496Each character in the string <code>what</code> 5497selects some fields of the structure <code>ar</code> to be filled or 5498a value to be pushed on the stack: 5499 5500<ul> 5501 5502<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>; 5503</li> 5504 5505<li><b>'<code>S</code>': </b> 5506fills in the fields <code>source</code>, <code>short_src</code>, 5507<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>; 5508</li> 5509 5510<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>; 5511</li> 5512 5513<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>; 5514</li> 5515 5516<li><b>'<code>u</code>': </b> fills in the fields 5517<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>; 5518</li> 5519 5520<li><b>'<code>f</code>': </b> 5521pushes onto the stack the function that is 5522running at the given level; 5523</li> 5524 5525<li><b>'<code>L</code>': </b> 5526pushes onto the stack a table whose indices are the 5527numbers of the lines that are valid on the function. 5528(A <em>valid line</em> is a line with some associated code, 5529that is, a line where you can put a break point. 5530Non-valid lines include empty lines and comments.) 5531 5532 5533<p> 5534If this option is given together with option '<code>f</code>', 5535its table is pushed after the function. 5536</li> 5537 5538</ul> 5539 5540<p> 5541This function returns 0 on error 5542(for instance, an invalid option in <code>what</code>). 5543 5544 5545 5546 5547 5548<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p> 5549<span class="apii">[-0, +(0|1), –]</span> 5550<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre> 5551 5552<p> 5553Gets information about a local variable of 5554a given activation record or a given function. 5555 5556 5557<p> 5558In the first case, 5559the parameter <code>ar</code> must be a valid activation record that was 5560filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or 5561given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). 5562The index <code>n</code> selects which local variable to inspect; 5563see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices 5564and names. 5565 5566 5567<p> 5568<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack 5569and returns its name. 5570 5571 5572<p> 5573In the second case, <code>ar</code> must be <code>NULL</code> and the function 5574to be inspected must be at the top of the stack. 5575In this case, only parameters of Lua functions are visible 5576(as there is no information about what variables are active) 5577and no values are pushed onto the stack. 5578 5579 5580<p> 5581Returns <code>NULL</code> (and pushes nothing) 5582when the index is greater than 5583the number of active local variables. 5584 5585 5586 5587 5588 5589<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p> 5590<span class="apii">[-0, +0, –]</span> 5591<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre> 5592 5593<p> 5594Gets information about the interpreter runtime stack. 5595 5596 5597<p> 5598This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with 5599an identification of the <em>activation record</em> 5600of the function executing at a given level. 5601Level 0 is the current running function, 5602whereas level <em>n+1</em> is the function that has called level <em>n</em> 5603(except for tail calls, which do not count on the stack). 5604When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1; 5605when called with a level greater than the stack depth, 5606it returns 0. 5607 5608 5609 5610 5611 5612<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p> 5613<span class="apii">[-0, +(0|1), –]</span> 5614<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre> 5615 5616<p> 5617Gets information about the <code>n</code>-th upvalue 5618of the closure at index <code>funcindex</code>. 5619It pushes the upvalue's value onto the stack 5620and returns its name. 5621Returns <code>NULL</code> (and pushes nothing) 5622when the index <code>n</code> is greater than the number of upvalues. 5623 5624 5625<p> 5626For C functions, this function uses the empty string <code>""</code> 5627as a name for all upvalues. 5628(For Lua functions, 5629upvalues are the external local variables that the function uses, 5630and that are consequently included in its closure.) 5631 5632 5633<p> 5634Upvalues have no particular order, 5635as they are active through the whole function. 5636They are numbered in an arbitrary order. 5637 5638 5639 5640 5641 5642<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3> 5643<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre> 5644 5645<p> 5646Type for debugging hook functions. 5647 5648 5649<p> 5650Whenever a hook is called, its <code>ar</code> argument has its field 5651<code>event</code> set to the specific event that triggered the hook. 5652Lua identifies these events with the following constants: 5653<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>, 5654<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>, 5655and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>. 5656Moreover, for line events, the field <code>currentline</code> is also set. 5657To get the value of any other field in <code>ar</code>, 5658the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. 5659 5660 5661<p> 5662For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>, 5663the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call; 5664in this case, there will be no corresponding return event. 5665 5666 5667<p> 5668While Lua is running a hook, it disables other calls to hooks. 5669Therefore, if a hook calls back Lua to execute a function or a chunk, 5670this execution occurs without any calls to hooks. 5671 5672 5673<p> 5674Hook functions cannot have continuations, 5675that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5676<a href="#lua_pcallk"><code>lua_pcallk</code></a>, or <a href="#lua_callk"><code>lua_callk</code></a> with a non-null <code>k</code>. 5677 5678 5679<p> 5680Hook functions can yield under the following conditions: 5681Only count and line events can yield; 5682to yield, a hook function must finish its execution 5683calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero 5684(that is, with no values). 5685 5686 5687 5688 5689 5690<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p> 5691<span class="apii">[-0, +0, –]</span> 5692<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre> 5693 5694<p> 5695Sets the debugging hook function. 5696 5697 5698<p> 5699Argument <code>f</code> is the hook function. 5700<code>mask</code> specifies on which events the hook will be called: 5701it is formed by a bitwise or of the constants 5702<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>, 5703<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>, 5704<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>, 5705and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>. 5706The <code>count</code> argument is only meaningful when the mask 5707includes <code>LUA_MASKCOUNT</code>. 5708For each event, the hook is called as explained below: 5709 5710<ul> 5711 5712<li><b>The call hook: </b> is called when the interpreter calls a function. 5713The hook is called just after Lua enters the new function, 5714before the function gets its arguments. 5715</li> 5716 5717<li><b>The return hook: </b> is called when the interpreter returns from a function. 5718The hook is called just before Lua leaves the function. 5719There is no standard way to access the values 5720to be returned by the function. 5721</li> 5722 5723<li><b>The line hook: </b> is called when the interpreter is about to 5724start the execution of a new line of code, 5725or when it jumps back in the code (even to the same line). 5726(This event only happens while Lua is executing a Lua function.) 5727</li> 5728 5729<li><b>The count hook: </b> is called after the interpreter executes every 5730<code>count</code> instructions. 5731(This event only happens while Lua is executing a Lua function.) 5732</li> 5733 5734</ul> 5735 5736<p> 5737A hook is disabled by setting <code>mask</code> to zero. 5738 5739 5740 5741 5742 5743<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p> 5744<span class="apii">[-(0|1), +0, –]</span> 5745<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre> 5746 5747<p> 5748Sets the value of a local variable of a given activation record. 5749It assigns the value at the top of the stack 5750to the variable and returns its name. 5751It also pops the value from the stack. 5752 5753 5754<p> 5755Returns <code>NULL</code> (and pops nothing) 5756when the index is greater than 5757the number of active local variables. 5758 5759 5760<p> 5761Parameters <code>ar</code> and <code>n</code> are as in function <a href="#lua_getlocal"><code>lua_getlocal</code></a>. 5762 5763 5764 5765 5766 5767<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p> 5768<span class="apii">[-(0|1), +0, –]</span> 5769<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre> 5770 5771<p> 5772Sets the value of a closure's upvalue. 5773It assigns the value at the top of the stack 5774to the upvalue and returns its name. 5775It also pops the value from the stack. 5776 5777 5778<p> 5779Returns <code>NULL</code> (and pops nothing) 5780when the index <code>n</code> is greater than the number of upvalues. 5781 5782 5783<p> 5784Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>. 5785 5786 5787 5788 5789 5790<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p> 5791<span class="apii">[-0, +0, –]</span> 5792<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre> 5793 5794<p> 5795Returns a unique identifier for the upvalue numbered <code>n</code> 5796from the closure at index <code>funcindex</code>. 5797 5798 5799<p> 5800These unique identifiers allow a program to check whether different 5801closures share upvalues. 5802Lua closures that share an upvalue 5803(that is, that access a same external local variable) 5804will return identical ids for those upvalue indices. 5805 5806 5807<p> 5808Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>, 5809but <code>n</code> cannot be greater than the number of upvalues. 5810 5811 5812 5813 5814 5815<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p> 5816<span class="apii">[-0, +0, –]</span> 5817<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1, 5818 int funcindex2, int n2);</pre> 5819 5820<p> 5821Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code> 5822refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>. 5823 5824 5825 5826 5827 5828 5829 5830<h1>5 – <a name="5">The Auxiliary Library</a></h1> 5831 5832<p> 5833 5834The <em>auxiliary library</em> provides several convenient functions 5835to interface C with Lua. 5836While the basic API provides the primitive functions for all 5837interactions between C and Lua, 5838the auxiliary library provides higher-level functions for some 5839common tasks. 5840 5841 5842<p> 5843All functions and types from the auxiliary library 5844are defined in header file <code>lauxlib.h</code> and 5845have a prefix <code>luaL_</code>. 5846 5847 5848<p> 5849All functions in the auxiliary library are built on 5850top of the basic API, 5851and so they provide nothing that cannot be done with that API. 5852Nevertheless, the use of the auxiliary library ensures 5853more consistency to your code. 5854 5855 5856<p> 5857Several functions in the auxiliary library use internally some 5858extra stack slots. 5859When a function in the auxiliary library uses less than five slots, 5860it does not check the stack size; 5861it simply assumes that there are enough slots. 5862 5863 5864<p> 5865Several functions in the auxiliary library are used to 5866check C function arguments. 5867Because the error message is formatted for arguments 5868(e.g., "<code>bad argument #1</code>"), 5869you should not use these functions for other stack values. 5870 5871 5872<p> 5873Functions called <code>luaL_check*</code> 5874always raise an error if the check is not satisfied. 5875 5876 5877 5878<h2>5.1 – <a name="5.1">Functions and Types</a></h2> 5879 5880<p> 5881Here we list all functions and types from the auxiliary library 5882in alphabetical order. 5883 5884 5885 5886<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p> 5887<span class="apii">[-?, +?, <em>e</em>]</span> 5888<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre> 5889 5890<p> 5891Adds the byte <code>c</code> to the buffer <code>B</code> 5892(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5893 5894 5895 5896 5897 5898<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p> 5899<span class="apii">[-?, +?, <em>e</em>]</span> 5900<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre> 5901 5902<p> 5903Adds the string pointed to by <code>s</code> with length <code>l</code> to 5904the buffer <code>B</code> 5905(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5906The string can contain embedded zeros. 5907 5908 5909 5910 5911 5912<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p> 5913<span class="apii">[-?, +?, <em>e</em>]</span> 5914<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre> 5915 5916<p> 5917Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>) 5918a string of length <code>n</code> previously copied to the 5919buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>). 5920 5921 5922 5923 5924 5925<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p> 5926<span class="apii">[-?, +?, <em>e</em>]</span> 5927<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre> 5928 5929<p> 5930Adds the zero-terminated string pointed to by <code>s</code> 5931to the buffer <code>B</code> 5932(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5933 5934 5935 5936 5937 5938<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p> 5939<span class="apii">[-1, +?, <em>e</em>]</span> 5940<pre>void luaL_addvalue (luaL_Buffer *B);</pre> 5941 5942<p> 5943Adds the value at the top of the stack 5944to the buffer <code>B</code> 5945(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5946Pops the value. 5947 5948 5949<p> 5950This is the only function on string buffers that can (and must) 5951be called with an extra element on the stack, 5952which is the value to be added to the buffer. 5953 5954 5955 5956 5957 5958<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p> 5959<span class="apii">[-0, +0, <em>v</em>]</span> 5960<pre>void luaL_argcheck (lua_State *L, 5961 int cond, 5962 int arg, 5963 const char *extramsg);</pre> 5964 5965<p> 5966Checks whether <code>cond</code> is true. 5967If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>). 5968 5969 5970 5971 5972 5973<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p> 5974<span class="apii">[-0, +0, <em>v</em>]</span> 5975<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre> 5976 5977<p> 5978Raises an error reporting a problem with argument <code>arg</code> 5979of the C function that called it, 5980using a standard message 5981that includes <code>extramsg</code> as a comment: 5982 5983<pre> 5984 bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>) 5985</pre><p> 5986This function never returns. 5987 5988 5989 5990 5991 5992<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3> 5993<pre>typedef struct luaL_Buffer luaL_Buffer;</pre> 5994 5995<p> 5996Type for a <em>string buffer</em>. 5997 5998 5999<p> 6000A string buffer allows C code to build Lua strings piecemeal. 6001Its pattern of use is as follows: 6002 6003<ul> 6004 6005<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> 6006 6007<li>Then initialize it with a call <code>luaL_buffinit(L, &b)</code>.</li> 6008 6009<li> 6010Then add string pieces to the buffer calling any of 6011the <code>luaL_add*</code> functions. 6012</li> 6013 6014<li> 6015Finish by calling <code>luaL_pushresult(&b)</code>. 6016This call leaves the final string on the top of the stack. 6017</li> 6018 6019</ul> 6020 6021<p> 6022If you know beforehand the total size of the resulting string, 6023you can use the buffer like this: 6024 6025<ul> 6026 6027<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> 6028 6029<li>Then initialize it and preallocate a space of 6030size <code>sz</code> with a call <code>luaL_buffinitsize(L, &b, sz)</code>.</li> 6031 6032<li>Then copy the string into that space.</li> 6033 6034<li> 6035Finish by calling <code>luaL_pushresultsize(&b, sz)</code>, 6036where <code>sz</code> is the total size of the resulting string 6037copied into that space. 6038</li> 6039 6040</ul> 6041 6042<p> 6043During its normal operation, 6044a string buffer uses a variable number of stack slots. 6045So, while using a buffer, you cannot assume that you know where 6046the top of the stack is. 6047You can use the stack between successive calls to buffer operations 6048as long as that use is balanced; 6049that is, 6050when you call a buffer operation, 6051the stack is at the same level 6052it was immediately after the previous buffer operation. 6053(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.) 6054After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its 6055level when the buffer was initialized, 6056plus the final string on its top. 6057 6058 6059 6060 6061 6062<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p> 6063<span class="apii">[-0, +0, –]</span> 6064<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre> 6065 6066<p> 6067Initializes a buffer <code>B</code>. 6068This function does not allocate any space; 6069the buffer must be declared as a variable 6070(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 6071 6072 6073 6074 6075 6076<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p> 6077<span class="apii">[-?, +?, <em>e</em>]</span> 6078<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre> 6079 6080<p> 6081Equivalent to the sequence 6082<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>. 6083 6084 6085 6086 6087 6088<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p> 6089<span class="apii">[-0, +(0|1), <em>e</em>]</span> 6090<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre> 6091 6092<p> 6093Calls a metamethod. 6094 6095 6096<p> 6097If the object at index <code>obj</code> has a metatable and this 6098metatable has a field <code>e</code>, 6099this function calls this field passing the object as its only argument. 6100In this case this function returns true and pushes onto the 6101stack the value returned by the call. 6102If there is no metatable or no metamethod, 6103this function returns false (without pushing any value on the stack). 6104 6105 6106 6107 6108 6109<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p> 6110<span class="apii">[-0, +0, <em>v</em>]</span> 6111<pre>void luaL_checkany (lua_State *L, int arg);</pre> 6112 6113<p> 6114Checks whether the function has an argument 6115of any type (including <b>nil</b>) at position <code>arg</code>. 6116 6117 6118 6119 6120 6121<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p> 6122<span class="apii">[-0, +0, <em>v</em>]</span> 6123<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre> 6124 6125<p> 6126Checks whether the function argument <code>arg</code> is an integer 6127(or can be converted to an integer) 6128and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>. 6129 6130 6131 6132 6133 6134<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p> 6135<span class="apii">[-0, +0, <em>v</em>]</span> 6136<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre> 6137 6138<p> 6139Checks whether the function argument <code>arg</code> is a string 6140and returns this string; 6141if <code>l</code> is not <code>NULL</code> fills <code>*l</code> 6142with the string's length. 6143 6144 6145<p> 6146This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, 6147so all conversions and caveats of that function apply here. 6148 6149 6150 6151 6152 6153<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p> 6154<span class="apii">[-0, +0, <em>v</em>]</span> 6155<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre> 6156 6157<p> 6158Checks whether the function argument <code>arg</code> is a number 6159and returns this number. 6160 6161 6162 6163 6164 6165<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p> 6166<span class="apii">[-0, +0, <em>v</em>]</span> 6167<pre>int luaL_checkoption (lua_State *L, 6168 int arg, 6169 const char *def, 6170 const char *const lst[]);</pre> 6171 6172<p> 6173Checks whether the function argument <code>arg</code> is a string and 6174searches for this string in the array <code>lst</code> 6175(which must be NULL-terminated). 6176Returns the index in the array where the string was found. 6177Raises an error if the argument is not a string or 6178if the string cannot be found. 6179 6180 6181<p> 6182If <code>def</code> is not <code>NULL</code>, 6183the function uses <code>def</code> as a default value when 6184there is no argument <code>arg</code> or when this argument is <b>nil</b>. 6185 6186 6187<p> 6188This is a useful function for mapping strings to C enums. 6189(The usual convention in Lua libraries is 6190to use strings instead of numbers to select options.) 6191 6192 6193 6194 6195 6196<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p> 6197<span class="apii">[-0, +0, <em>v</em>]</span> 6198<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre> 6199 6200<p> 6201Grows the stack size to <code>top + sz</code> elements, 6202raising an error if the stack cannot grow to that size. 6203<code>msg</code> is an additional text to go into the error message 6204(or <code>NULL</code> for no additional text). 6205 6206 6207 6208 6209 6210<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p> 6211<span class="apii">[-0, +0, <em>v</em>]</span> 6212<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre> 6213 6214<p> 6215Checks whether the function argument <code>arg</code> is a string 6216and returns this string. 6217 6218 6219<p> 6220This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, 6221so all conversions and caveats of that function apply here. 6222 6223 6224 6225 6226 6227<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p> 6228<span class="apii">[-0, +0, <em>v</em>]</span> 6229<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre> 6230 6231<p> 6232Checks whether the function argument <code>arg</code> has type <code>t</code>. 6233See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>. 6234 6235 6236 6237 6238 6239<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p> 6240<span class="apii">[-0, +0, <em>v</em>]</span> 6241<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre> 6242 6243<p> 6244Checks whether the function argument <code>arg</code> is a userdata 6245of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and 6246returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>). 6247 6248 6249 6250 6251 6252<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p> 6253<span class="apii">[-0, +0, –]</span> 6254<pre>void luaL_checkversion (lua_State *L);</pre> 6255 6256<p> 6257Checks whether the core running the call, 6258the core that created the Lua state, 6259and the code making the call are all using the same version of Lua. 6260Also checks whether the core running the call 6261and the core that created the Lua state 6262are using the same address space. 6263 6264 6265 6266 6267 6268<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p> 6269<span class="apii">[-0, +?, <em>e</em>]</span> 6270<pre>int luaL_dofile (lua_State *L, const char *filename);</pre> 6271 6272<p> 6273Loads and runs the given file. 6274It is defined as the following macro: 6275 6276<pre> 6277 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) 6278</pre><p> 6279It returns false if there are no errors 6280or true in case of errors. 6281 6282 6283 6284 6285 6286<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p> 6287<span class="apii">[-0, +?, –]</span> 6288<pre>int luaL_dostring (lua_State *L, const char *str);</pre> 6289 6290<p> 6291Loads and runs the given string. 6292It is defined as the following macro: 6293 6294<pre> 6295 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) 6296</pre><p> 6297It returns false if there are no errors 6298or true in case of errors. 6299 6300 6301 6302 6303 6304<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p> 6305<span class="apii">[-0, +0, <em>v</em>]</span> 6306<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre> 6307 6308<p> 6309Raises an error. 6310The error message format is given by <code>fmt</code> 6311plus any extra arguments, 6312following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>. 6313It also adds at the beginning of the message the file name and 6314the line number where the error occurred, 6315if this information is available. 6316 6317 6318<p> 6319This function never returns, 6320but it is an idiom to use it in C functions 6321as <code>return luaL_error(<em>args</em>)</code>. 6322 6323 6324 6325 6326 6327<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p> 6328<span class="apii">[-0, +3, <em>e</em>]</span> 6329<pre>int luaL_execresult (lua_State *L, int stat);</pre> 6330 6331<p> 6332This function produces the return values for 6333process-related functions in the standard library 6334(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>). 6335 6336 6337 6338 6339 6340<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p> 6341<span class="apii">[-0, +(1|3), <em>e</em>]</span> 6342<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre> 6343 6344<p> 6345This function produces the return values for 6346file-related functions in the standard library 6347(<a href="#pdf-io.open"><code>io.open</code></a>, <a href="#pdf-os.rename"><code>os.rename</code></a>, <a href="#pdf-file:seek"><code>file:seek</code></a>, etc.). 6348 6349 6350 6351 6352 6353<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p> 6354<span class="apii">[-0, +(0|1), <em>e</em>]</span> 6355<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre> 6356 6357<p> 6358Pushes onto the stack the field <code>e</code> from the metatable 6359of the object at index <code>obj</code> and returns the type of pushed value. 6360If the object does not have a metatable, 6361or if the metatable does not have this field, 6362pushes nothing and returns <code>LUA_TNIL</code>. 6363 6364 6365 6366 6367 6368<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p> 6369<span class="apii">[-0, +1, –]</span> 6370<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre> 6371 6372<p> 6373Pushes onto the stack the metatable associated with name <code>tname</code> 6374in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) 6375(<b>nil</b> if there is no metatable associated with that name). 6376Returns the type of the pushed value. 6377 6378 6379 6380 6381 6382<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p> 6383<span class="apii">[-0, +1, <em>e</em>]</span> 6384<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre> 6385 6386<p> 6387Ensures that the value <code>t[fname]</code>, 6388where <code>t</code> is the value at index <code>idx</code>, 6389is a table, 6390and pushes that table onto the stack. 6391Returns true if it finds a previous table there 6392and false if it creates a new table. 6393 6394 6395 6396 6397 6398<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p> 6399<span class="apii">[-0, +1, <em>e</em>]</span> 6400<pre>const char *luaL_gsub (lua_State *L, 6401 const char *s, 6402 const char *p, 6403 const char *r);</pre> 6404 6405<p> 6406Creates a copy of string <code>s</code> by replacing 6407any occurrence of the string <code>p</code> 6408with the string <code>r</code>. 6409Pushes the resulting string on the stack and returns it. 6410 6411 6412 6413 6414 6415<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p> 6416<span class="apii">[-0, +0, <em>e</em>]</span> 6417<pre>lua_Integer luaL_len (lua_State *L, int index);</pre> 6418 6419<p> 6420Returns the "length" of the value at the given index 6421as a number; 6422it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>). 6423Raises an error if the result of the operation is not an integer. 6424(This case only can happen through metamethods.) 6425 6426 6427 6428 6429 6430<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p> 6431<span class="apii">[-0, +1, –]</span> 6432<pre>int luaL_loadbuffer (lua_State *L, 6433 const char *buff, 6434 size_t sz, 6435 const char *name);</pre> 6436 6437<p> 6438Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>. 6439 6440 6441 6442 6443 6444<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p> 6445<span class="apii">[-0, +1, –]</span> 6446<pre>int luaL_loadbufferx (lua_State *L, 6447 const char *buff, 6448 size_t sz, 6449 const char *name, 6450 const char *mode);</pre> 6451 6452<p> 6453Loads a buffer as a Lua chunk. 6454This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the 6455buffer pointed to by <code>buff</code> with size <code>sz</code>. 6456 6457 6458<p> 6459This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. 6460<code>name</code> is the chunk name, 6461used for debug information and error messages. 6462The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. 6463 6464 6465 6466 6467 6468<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p> 6469<span class="apii">[-0, +1, <em>e</em>]</span> 6470<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre> 6471 6472<p> 6473Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>. 6474 6475 6476 6477 6478 6479<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p> 6480<span class="apii">[-0, +1, <em>e</em>]</span> 6481<pre>int luaL_loadfilex (lua_State *L, const char *filename, 6482 const char *mode);</pre> 6483 6484<p> 6485Loads a file as a Lua chunk. 6486This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file 6487named <code>filename</code>. 6488If <code>filename</code> is <code>NULL</code>, 6489then it loads from the standard input. 6490The first line in the file is ignored if it starts with a <code>#</code>. 6491 6492 6493<p> 6494The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. 6495 6496 6497<p> 6498This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>, 6499but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> 6500if it cannot open/read the file or the file has a wrong mode. 6501 6502 6503<p> 6504As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; 6505it does not run it. 6506 6507 6508 6509 6510 6511<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p> 6512<span class="apii">[-0, +1, –]</span> 6513<pre>int luaL_loadstring (lua_State *L, const char *s);</pre> 6514 6515<p> 6516Loads a string as a Lua chunk. 6517This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in 6518the zero-terminated string <code>s</code>. 6519 6520 6521<p> 6522This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. 6523 6524 6525<p> 6526Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; 6527it does not run it. 6528 6529 6530 6531 6532 6533<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p> 6534<span class="apii">[-0, +1, <em>e</em>]</span> 6535<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre> 6536 6537<p> 6538Creates a new table and registers there 6539the functions in list <code>l</code>. 6540 6541 6542<p> 6543It is implemented as the following macro: 6544 6545<pre> 6546 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) 6547</pre><p> 6548The array <code>l</code> must be the actual array, 6549not a pointer to it. 6550 6551 6552 6553 6554 6555<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p> 6556<span class="apii">[-0, +1, <em>e</em>]</span> 6557<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre> 6558 6559<p> 6560Creates a new table with a size optimized 6561to store all entries in the array <code>l</code> 6562(but does not actually store them). 6563It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> 6564(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>). 6565 6566 6567<p> 6568It is implemented as a macro. 6569The array <code>l</code> must be the actual array, 6570not a pointer to it. 6571 6572 6573 6574 6575 6576<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p> 6577<span class="apii">[-0, +1, <em>e</em>]</span> 6578<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre> 6579 6580<p> 6581If the registry already has the key <code>tname</code>, 6582returns 0. 6583Otherwise, 6584creates a new table to be used as a metatable for userdata, 6585adds to this new table the pair <code>__name = tname</code>, 6586adds to the registry the pair <code>[tname] = new table</code>, 6587and returns 1. 6588(The entry <code>__name</code> is used by some error-reporting functions.) 6589 6590 6591<p> 6592In both cases pushes onto the stack the final value associated 6593with <code>tname</code> in the registry. 6594 6595 6596 6597 6598 6599<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p> 6600<span class="apii">[-0, +0, –]</span> 6601<pre>lua_State *luaL_newstate (void);</pre> 6602 6603<p> 6604Creates a new Lua state. 6605It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an 6606allocator based on the standard C <code>realloc</code> function 6607and then sets a panic function (see <a href="#4.6">§4.6</a>) that prints 6608an error message to the standard error output in case of fatal 6609errors. 6610 6611 6612<p> 6613Returns the new state, 6614or <code>NULL</code> if there is a memory allocation error. 6615 6616 6617 6618 6619 6620<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p> 6621<span class="apii">[-0, +0, <em>e</em>]</span> 6622<pre>void luaL_openlibs (lua_State *L);</pre> 6623 6624<p> 6625Opens all standard Lua libraries into the given state. 6626 6627 6628 6629 6630 6631<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p> 6632<span class="apii">[-0, +0, <em>v</em>]</span> 6633<pre>lua_Integer luaL_optinteger (lua_State *L, 6634 int arg, 6635 lua_Integer d);</pre> 6636 6637<p> 6638If the function argument <code>arg</code> is an integer 6639(or convertible to an integer), 6640returns this integer. 6641If this argument is absent or is <b>nil</b>, 6642returns <code>d</code>. 6643Otherwise, raises an error. 6644 6645 6646 6647 6648 6649<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p> 6650<span class="apii">[-0, +0, <em>v</em>]</span> 6651<pre>const char *luaL_optlstring (lua_State *L, 6652 int arg, 6653 const char *d, 6654 size_t *l);</pre> 6655 6656<p> 6657If the function argument <code>arg</code> is a string, 6658returns this string. 6659If this argument is absent or is <b>nil</b>, 6660returns <code>d</code>. 6661Otherwise, raises an error. 6662 6663 6664<p> 6665If <code>l</code> is not <code>NULL</code>, 6666fills the position <code>*l</code> with the result's length. 6667 6668 6669 6670 6671 6672<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p> 6673<span class="apii">[-0, +0, <em>v</em>]</span> 6674<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre> 6675 6676<p> 6677If the function argument <code>arg</code> is a number, 6678returns this number. 6679If this argument is absent or is <b>nil</b>, 6680returns <code>d</code>. 6681Otherwise, raises an error. 6682 6683 6684 6685 6686 6687<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p> 6688<span class="apii">[-0, +0, <em>v</em>]</span> 6689<pre>const char *luaL_optstring (lua_State *L, 6690 int arg, 6691 const char *d);</pre> 6692 6693<p> 6694If the function argument <code>arg</code> is a string, 6695returns this string. 6696If this argument is absent or is <b>nil</b>, 6697returns <code>d</code>. 6698Otherwise, raises an error. 6699 6700 6701 6702 6703 6704<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p> 6705<span class="apii">[-?, +?, <em>e</em>]</span> 6706<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre> 6707 6708<p> 6709Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a> 6710with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>. 6711 6712 6713 6714 6715 6716<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p> 6717<span class="apii">[-?, +?, <em>e</em>]</span> 6718<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre> 6719 6720<p> 6721Returns an address to a space of size <code>sz</code> 6722where you can copy a string to be added to buffer <code>B</code> 6723(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 6724After copying the string into this space you must call 6725<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add 6726it to the buffer. 6727 6728 6729 6730 6731 6732<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p> 6733<span class="apii">[-?, +1, <em>e</em>]</span> 6734<pre>void luaL_pushresult (luaL_Buffer *B);</pre> 6735 6736<p> 6737Finishes the use of buffer <code>B</code> leaving the final string on 6738the top of the stack. 6739 6740 6741 6742 6743 6744<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p> 6745<span class="apii">[-?, +1, <em>e</em>]</span> 6746<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre> 6747 6748<p> 6749Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>. 6750 6751 6752 6753 6754 6755<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p> 6756<span class="apii">[-1, +0, <em>e</em>]</span> 6757<pre>int luaL_ref (lua_State *L, int t);</pre> 6758 6759<p> 6760Creates and returns a <em>reference</em>, 6761in the table at index <code>t</code>, 6762for the object at the top of the stack (and pops the object). 6763 6764 6765<p> 6766A reference is a unique integer key. 6767As long as you do not manually add integer keys into table <code>t</code>, 6768<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns. 6769You can retrieve an object referred by reference <code>r</code> 6770by calling <code>lua_rawgeti(L, t, r)</code>. 6771Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object. 6772 6773 6774<p> 6775If the object at the top of the stack is <b>nil</b>, 6776<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>. 6777The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different 6778from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>. 6779 6780 6781 6782 6783 6784<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3> 6785<pre>typedef struct luaL_Reg { 6786 const char *name; 6787 lua_CFunction func; 6788} luaL_Reg;</pre> 6789 6790<p> 6791Type for arrays of functions to be registered by 6792<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>. 6793<code>name</code> is the function name and <code>func</code> is a pointer to 6794the function. 6795Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry 6796in which both <code>name</code> and <code>func</code> are <code>NULL</code>. 6797 6798 6799 6800 6801 6802<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p> 6803<span class="apii">[-0, +1, <em>e</em>]</span> 6804<pre>void luaL_requiref (lua_State *L, const char *modname, 6805 lua_CFunction openf, int glb);</pre> 6806 6807<p> 6808If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>, 6809calls function <code>openf</code> with string <code>modname</code> as an argument 6810and sets the call result in <code>package.loaded[modname]</code>, 6811as if that function has been called through <a href="#pdf-require"><code>require</code></a>. 6812 6813 6814<p> 6815If <code>glb</code> is true, 6816also stores the module into global <code>modname</code>. 6817 6818 6819<p> 6820Leaves a copy of the module on the stack. 6821 6822 6823 6824 6825 6826<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p> 6827<span class="apii">[-nup, +0, <em>e</em>]</span> 6828<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre> 6829 6830<p> 6831Registers all functions in the array <code>l</code> 6832(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack 6833(below optional upvalues, see next). 6834 6835 6836<p> 6837When <code>nup</code> is not zero, 6838all functions are created sharing <code>nup</code> upvalues, 6839which must be previously pushed on the stack 6840on top of the library table. 6841These values are popped from the stack after the registration. 6842 6843 6844 6845 6846 6847<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p> 6848<span class="apii">[-0, +0, –]</span> 6849<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre> 6850 6851<p> 6852Sets the metatable of the object at the top of the stack 6853as the metatable associated with name <code>tname</code> 6854in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). 6855 6856 6857 6858 6859 6860<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3> 6861<pre>typedef struct luaL_Stream { 6862 FILE *f; 6863 lua_CFunction closef; 6864} luaL_Stream;</pre> 6865 6866<p> 6867The standard representation for file handles, 6868which is used by the standard I/O library. 6869 6870 6871<p> 6872A file handle is implemented as a full userdata, 6873with a metatable called <code>LUA_FILEHANDLE</code> 6874(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name). 6875The metatable is created by the I/O library 6876(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). 6877 6878 6879<p> 6880This userdata must start with the structure <code>luaL_Stream</code>; 6881it can contain other data after this initial structure. 6882Field <code>f</code> points to the corresponding C stream 6883(or it can be <code>NULL</code> to indicate an incompletely created handle). 6884Field <code>closef</code> points to a Lua function 6885that will be called to close the stream 6886when the handle is closed or collected; 6887this function receives the file handle as its sole argument and 6888must return either <b>true</b> (in case of success) 6889or <b>nil</b> plus an error message (in case of error). 6890Once Lua calls this field, 6891the field value is changed to <code>NULL</code> 6892to signal that the handle is closed. 6893 6894 6895 6896 6897 6898<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p> 6899<span class="apii">[-0, +0, <em>e</em>]</span> 6900<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre> 6901 6902<p> 6903This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>, 6904except that, when the test fails, 6905it returns <code>NULL</code> instead of raising an error. 6906 6907 6908 6909 6910 6911<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p> 6912<span class="apii">[-0, +1, <em>e</em>]</span> 6913<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre> 6914 6915<p> 6916Converts any Lua value at the given index to a C string 6917in a reasonable format. 6918The resulting string is pushed onto the stack and also 6919returned by the function. 6920If <code>len</code> is not <code>NULL</code>, 6921the function also sets <code>*len</code> with the string length. 6922 6923 6924<p> 6925If the value has a metatable with a <code>"__tostring"</code> field, 6926then <code>luaL_tolstring</code> calls the corresponding metamethod 6927with the value as argument, 6928and uses the result of the call as its result. 6929 6930 6931 6932 6933 6934<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p> 6935<span class="apii">[-0, +1, <em>e</em>]</span> 6936<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, 6937 int level);</pre> 6938 6939<p> 6940Creates and pushes a traceback of the stack <code>L1</code>. 6941If <code>msg</code> is not <code>NULL</code> it is appended 6942at the beginning of the traceback. 6943The <code>level</code> parameter tells at which level 6944to start the traceback. 6945 6946 6947 6948 6949 6950<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p> 6951<span class="apii">[-0, +0, –]</span> 6952<pre>const char *luaL_typename (lua_State *L, int index);</pre> 6953 6954<p> 6955Returns the name of the type of the value at the given index. 6956 6957 6958 6959 6960 6961<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p> 6962<span class="apii">[-0, +0, –]</span> 6963<pre>void luaL_unref (lua_State *L, int t, int ref);</pre> 6964 6965<p> 6966Releases reference <code>ref</code> from the table at index <code>t</code> 6967(see <a href="#luaL_ref"><code>luaL_ref</code></a>). 6968The entry is removed from the table, 6969so that the referred object can be collected. 6970The reference <code>ref</code> is also freed to be used again. 6971 6972 6973<p> 6974If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>, 6975<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing. 6976 6977 6978 6979 6980 6981<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p> 6982<span class="apii">[-0, +1, <em>e</em>]</span> 6983<pre>void luaL_where (lua_State *L, int lvl);</pre> 6984 6985<p> 6986Pushes onto the stack a string identifying the current position 6987of the control at level <code>lvl</code> in the call stack. 6988Typically this string has the following format: 6989 6990<pre> 6991 <em>chunkname</em>:<em>currentline</em>: 6992</pre><p> 6993Level 0 is the running function, 6994level 1 is the function that called the running function, 6995etc. 6996 6997 6998<p> 6999This function is used to build a prefix for error messages. 7000 7001 7002 7003 7004 7005 7006 7007<h1>6 – <a name="6">Standard Libraries</a></h1> 7008 7009<p> 7010The standard Lua libraries provide useful functions 7011that are implemented directly through the C API. 7012Some of these functions provide essential services to the language 7013(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>); 7014others provide access to "outside" services (e.g., I/O); 7015and others could be implemented in Lua itself, 7016but are quite useful or have critical performance requirements that 7017deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>). 7018 7019 7020<p> 7021All libraries are implemented through the official C API 7022and are provided as separate C modules. 7023Currently, Lua has the following standard libraries: 7024 7025<ul> 7026 7027<li>basic library (<a href="#6.1">§6.1</a>);</li> 7028 7029<li>coroutine library (<a href="#6.2">§6.2</a>);</li> 7030 7031<li>package library (<a href="#6.3">§6.3</a>);</li> 7032 7033<li>string manipulation (<a href="#6.4">§6.4</a>);</li> 7034 7035<li>basic UTF-8 support (<a href="#6.5">§6.5</a>);</li> 7036 7037<li>table manipulation (<a href="#6.6">§6.6</a>);</li> 7038 7039<li>mathematical functions (<a href="#6.7">§6.7</a>) (sin, log, etc.);</li> 7040 7041<li>input and output (<a href="#6.8">§6.8</a>);</li> 7042 7043<li>operating system facilities (<a href="#6.9">§6.9</a>);</li> 7044 7045<li>debug facilities (<a href="#6.10">§6.10</a>).</li> 7046 7047</ul><p> 7048Except for the basic and the package libraries, 7049each library provides all its functions as fields of a global table 7050or as methods of its objects. 7051 7052 7053<p> 7054To have access to these libraries, 7055the C host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function, 7056which opens all standard libraries. 7057Alternatively, 7058the host program can open them individually by using 7059<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call 7060<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library), 7061<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library), 7062<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library), 7063<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library), 7064<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library), 7065<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library), 7066<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library), 7067<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library), 7068<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library), 7069and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library). 7070These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>. 7071 7072 7073 7074<h2>6.1 – <a name="6.1">Basic Functions</a></h2> 7075 7076<p> 7077The basic library provides core functions to Lua. 7078If you do not include this library in your application, 7079you should check carefully whether you need to provide 7080implementations for some of its facilities. 7081 7082 7083<p> 7084<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3> 7085 7086 7087<p> 7088Calls <a href="#pdf-error"><code>error</code></a> if 7089the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>); 7090otherwise, returns all its arguments. 7091In case of error, 7092<code>message</code> is the error object; 7093when absent, it defaults to "<code>assertion failed!</code>" 7094 7095 7096 7097 7098<p> 7099<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3> 7100 7101 7102<p> 7103This function is a generic interface to the garbage collector. 7104It performs different functions according to its first argument, <code>opt</code>: 7105 7106<ul> 7107 7108<li><b>"<code>collect</code>": </b> 7109performs a full garbage-collection cycle. 7110This is the default option. 7111</li> 7112 7113<li><b>"<code>stop</code>": </b> 7114stops automatic execution of the garbage collector. 7115The collector will run only when explicitly invoked, 7116until a call to restart it. 7117</li> 7118 7119<li><b>"<code>restart</code>": </b> 7120restarts automatic execution of the garbage collector. 7121</li> 7122 7123<li><b>"<code>count</code>": </b> 7124returns the total memory in use by Lua in Kbytes. 7125The value has a fractional part, 7126so that it multiplied by 1024 7127gives the exact number of bytes in use by Lua 7128(except for overflows). 7129</li> 7130 7131<li><b>"<code>step</code>": </b> 7132performs a garbage-collection step. 7133The step "size" is controlled by <code>arg</code>. 7134With a zero value, 7135the collector will perform one basic (indivisible) step. 7136For non-zero values, 7137the collector will perform as if that amount of memory 7138(in KBytes) had been allocated by Lua. 7139Returns <b>true</b> if the step finished a collection cycle. 7140</li> 7141 7142<li><b>"<code>setpause</code>": </b> 7143sets <code>arg</code> as the new value for the <em>pause</em> of 7144the collector (see <a href="#2.5">§2.5</a>). 7145Returns the previous value for <em>pause</em>. 7146</li> 7147 7148<li><b>"<code>setstepmul</code>": </b> 7149sets <code>arg</code> as the new value for the <em>step multiplier</em> of 7150the collector (see <a href="#2.5">§2.5</a>). 7151Returns the previous value for <em>step</em>. 7152</li> 7153 7154<li><b>"<code>isrunning</code>": </b> 7155returns a boolean that tells whether the collector is running 7156(i.e., not stopped). 7157</li> 7158 7159</ul> 7160 7161 7162 7163<p> 7164<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3> 7165Opens the named file and executes its contents as a Lua chunk. 7166When called without arguments, 7167<code>dofile</code> executes the contents of the standard input (<code>stdin</code>). 7168Returns all values returned by the chunk. 7169In case of errors, <code>dofile</code> propagates the error 7170to its caller (that is, <code>dofile</code> does not run in protected mode). 7171 7172 7173 7174 7175<p> 7176<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3> 7177Terminates the last protected function called 7178and returns <code>message</code> as the error object. 7179Function <code>error</code> never returns. 7180 7181 7182<p> 7183Usually, <code>error</code> adds some information about the error position 7184at the beginning of the message, if the message is a string. 7185The <code>level</code> argument specifies how to get the error position. 7186With level 1 (the default), the error position is where the 7187<code>error</code> function was called. 7188Level 2 points the error to where the function 7189that called <code>error</code> was called; and so on. 7190Passing a level 0 avoids the addition of error position information 7191to the message. 7192 7193 7194 7195 7196<p> 7197<hr><h3><a name="pdf-_G"><code>_G</code></a></h3> 7198A global variable (not a function) that 7199holds the global environment (see <a href="#2.2">§2.2</a>). 7200Lua itself does not use this variable; 7201changing its value does not affect any environment, 7202nor vice versa. 7203 7204 7205 7206 7207<p> 7208<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3> 7209 7210 7211<p> 7212If <code>object</code> does not have a metatable, returns <b>nil</b>. 7213Otherwise, 7214if the object's metatable has a <code>"__metatable"</code> field, 7215returns the associated value. 7216Otherwise, returns the metatable of the given object. 7217 7218 7219 7220 7221<p> 7222<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3> 7223 7224 7225<p> 7226Returns three values (an iterator function, the table <code>t</code>, and 0) 7227so that the construction 7228 7229<pre> 7230 for i,v in ipairs(t) do <em>body</em> end 7231</pre><p> 7232will iterate over the key–value pairs 7233(<code>1,t[1]</code>), (<code>2,t[2]</code>), ..., 7234up to the first nil value. 7235 7236 7237 7238 7239<p> 7240<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3> 7241 7242 7243<p> 7244Loads a chunk. 7245 7246 7247<p> 7248If <code>chunk</code> is a string, the chunk is this string. 7249If <code>chunk</code> is a function, 7250<code>load</code> calls it repeatedly to get the chunk pieces. 7251Each call to <code>chunk</code> must return a string that concatenates 7252with previous results. 7253A return of an empty string, <b>nil</b>, or no value signals the end of the chunk. 7254 7255 7256<p> 7257If there are no syntactic errors, 7258returns the compiled chunk as a function; 7259otherwise, returns <b>nil</b> plus the error message. 7260 7261 7262<p> 7263If the resulting function has upvalues, 7264the first upvalue is set to the value of <code>env</code>, 7265if that parameter is given, 7266or to the value of the global environment. 7267Other upvalues are initialized with <b>nil</b>. 7268(When you load a main chunk, 7269the resulting function will always have exactly one upvalue, 7270the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>). 7271However, 7272when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>), 7273the resulting function can have an arbitrary number of upvalues.) 7274All upvalues are fresh, that is, 7275they are not shared with any other function. 7276 7277 7278<p> 7279<code>chunkname</code> is used as the name of the chunk for error messages 7280and debug information (see <a href="#4.9">§4.9</a>). 7281When absent, 7282it defaults to <code>chunk</code>, if <code>chunk</code> is a string, 7283or to "<code>=(load)</code>" otherwise. 7284 7285 7286<p> 7287The string <code>mode</code> controls whether the chunk can be text or binary 7288(that is, a precompiled chunk). 7289It may be the string "<code>b</code>" (only binary chunks), 7290"<code>t</code>" (only text chunks), 7291or "<code>bt</code>" (both binary and text). 7292The default is "<code>bt</code>". 7293 7294 7295<p> 7296Lua does not check the consistency of binary chunks. 7297Maliciously crafted binary chunks can crash 7298the interpreter. 7299 7300 7301 7302 7303<p> 7304<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3> 7305 7306 7307<p> 7308Similar to <a href="#pdf-load"><code>load</code></a>, 7309but gets the chunk from file <code>filename</code> 7310or from the standard input, 7311if no file name is given. 7312 7313 7314 7315 7316<p> 7317<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3> 7318 7319 7320<p> 7321Allows a program to traverse all fields of a table. 7322Its first argument is a table and its second argument 7323is an index in this table. 7324<code>next</code> returns the next index of the table 7325and its associated value. 7326When called with <b>nil</b> as its second argument, 7327<code>next</code> returns an initial index 7328and its associated value. 7329When called with the last index, 7330or with <b>nil</b> in an empty table, 7331<code>next</code> returns <b>nil</b>. 7332If the second argument is absent, then it is interpreted as <b>nil</b>. 7333In particular, 7334you can use <code>next(t)</code> to check whether a table is empty. 7335 7336 7337<p> 7338The order in which the indices are enumerated is not specified, 7339<em>even for numeric indices</em>. 7340(To traverse a table in numerical order, 7341use a numerical <b>for</b>.) 7342 7343 7344<p> 7345The behavior of <code>next</code> is undefined if, 7346during the traversal, 7347you assign any value to a non-existent field in the table. 7348You may however modify existing fields. 7349In particular, you may clear existing fields. 7350 7351 7352 7353 7354<p> 7355<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3> 7356 7357 7358<p> 7359If <code>t</code> has a metamethod <code>__pairs</code>, 7360calls it with <code>t</code> as argument and returns the first three 7361results from the call. 7362 7363 7364<p> 7365Otherwise, 7366returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>, 7367so that the construction 7368 7369<pre> 7370 for k,v in pairs(t) do <em>body</em> end 7371</pre><p> 7372will iterate over all key–value pairs of table <code>t</code>. 7373 7374 7375<p> 7376See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying 7377the table during its traversal. 7378 7379 7380 7381 7382<p> 7383<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, ···])</code></a></h3> 7384 7385 7386<p> 7387Calls function <code>f</code> with 7388the given arguments in <em>protected mode</em>. 7389This means that any error inside <code>f</code> is not propagated; 7390instead, <code>pcall</code> catches the error 7391and returns a status code. 7392Its first result is the status code (a boolean), 7393which is true if the call succeeds without errors. 7394In such case, <code>pcall</code> also returns all results from the call, 7395after this first result. 7396In case of any error, <code>pcall</code> returns <b>false</b> plus the error message. 7397 7398 7399 7400 7401<p> 7402<hr><h3><a name="pdf-print"><code>print (···)</code></a></h3> 7403Receives any number of arguments 7404and prints their values to <code>stdout</code>, 7405using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string. 7406<code>print</code> is not intended for formatted output, 7407but only as a quick way to show a value, 7408for instance for debugging. 7409For complete control over the output, 7410use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>. 7411 7412 7413 7414 7415<p> 7416<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3> 7417Checks whether <code>v1</code> is equal to <code>v2</code>, 7418without invoking any metamethod. 7419Returns a boolean. 7420 7421 7422 7423 7424<p> 7425<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3> 7426Gets the real value of <code>table[index]</code>, 7427without invoking any metamethod. 7428<code>table</code> must be a table; 7429<code>index</code> may be any value. 7430 7431 7432 7433 7434<p> 7435<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3> 7436Returns the length of the object <code>v</code>, 7437which must be a table or a string, 7438without invoking any metamethod. 7439Returns an integer. 7440 7441 7442 7443 7444<p> 7445<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3> 7446Sets the real value of <code>table[index]</code> to <code>value</code>, 7447without invoking any metamethod. 7448<code>table</code> must be a table, 7449<code>index</code> any value different from <b>nil</b> and NaN, 7450and <code>value</code> any Lua value. 7451 7452 7453<p> 7454This function returns <code>table</code>. 7455 7456 7457 7458 7459<p> 7460<hr><h3><a name="pdf-select"><code>select (index, ···)</code></a></h3> 7461 7462 7463<p> 7464If <code>index</code> is a number, 7465returns all arguments after argument number <code>index</code>; 7466a negative number indexes from the end (-1 is the last argument). 7467Otherwise, <code>index</code> must be the string <code>"#"</code>, 7468and <code>select</code> returns the total number of extra arguments it received. 7469 7470 7471 7472 7473<p> 7474<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3> 7475 7476 7477<p> 7478Sets the metatable for the given table. 7479(You cannot change the metatable of other types from Lua, only from C.) 7480If <code>metatable</code> is <b>nil</b>, 7481removes the metatable of the given table. 7482If the original metatable has a <code>"__metatable"</code> field, 7483raises an error. 7484 7485 7486<p> 7487This function returns <code>table</code>. 7488 7489 7490 7491 7492<p> 7493<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3> 7494 7495 7496<p> 7497When called with no <code>base</code>, 7498<code>tonumber</code> tries to convert its argument to a number. 7499If the argument is already a number or 7500a string convertible to a number, 7501then <code>tonumber</code> returns this number; 7502otherwise, it returns <b>nil</b>. 7503 7504 7505<p> 7506The conversion of strings can result in integers or floats, 7507according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>). 7508(The string may have leading and trailing spaces and a sign.) 7509 7510 7511<p> 7512When called with <code>base</code>, 7513then <code>e</code> must be a string to be interpreted as 7514an integer numeral in that base. 7515The base may be any integer between 2 and 36, inclusive. 7516In bases above 10, the letter '<code>A</code>' (in either upper or lower case) 7517represents 10, '<code>B</code>' represents 11, and so forth, 7518with '<code>Z</code>' representing 35. 7519If the string <code>e</code> is not a valid numeral in the given base, 7520the function returns <b>nil</b>. 7521 7522 7523 7524 7525<p> 7526<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3> 7527Receives a value of any type and 7528converts it to a string in a human-readable format. 7529(For complete control of how numbers are converted, 7530use <a href="#pdf-string.format"><code>string.format</code></a>.) 7531 7532 7533<p> 7534If the metatable of <code>v</code> has a <code>"__tostring"</code> field, 7535then <code>tostring</code> calls the corresponding value 7536with <code>v</code> as argument, 7537and uses the result of the call as its result. 7538 7539 7540 7541 7542<p> 7543<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3> 7544Returns the type of its only argument, coded as a string. 7545The possible results of this function are 7546"<code>nil</code>" (a string, not the value <b>nil</b>), 7547"<code>number</code>", 7548"<code>string</code>", 7549"<code>boolean</code>", 7550"<code>table</code>", 7551"<code>function</code>", 7552"<code>thread</code>", 7553and "<code>userdata</code>". 7554 7555 7556 7557 7558<p> 7559<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3> 7560A global variable (not a function) that 7561holds a string containing the current interpreter version. 7562The current value of this variable is "<code>Lua 5.3</code>". 7563 7564 7565 7566 7567<p> 7568<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, ···])</code></a></h3> 7569 7570 7571<p> 7572This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>, 7573except that it sets a new message handler <code>msgh</code>. 7574 7575 7576 7577 7578 7579 7580 7581<h2>6.2 – <a name="6.2">Coroutine Manipulation</a></h2> 7582 7583<p> 7584This library comprises the operations to manipulate coroutines, 7585which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>. 7586See <a href="#2.6">§2.6</a> for a general description of coroutines. 7587 7588 7589<p> 7590<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3> 7591 7592 7593<p> 7594Creates a new coroutine, with body <code>f</code>. 7595<code>f</code> must be a function. 7596Returns this new coroutine, 7597an object with type <code>"thread"</code>. 7598 7599 7600 7601 7602<p> 7603<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3> 7604 7605 7606<p> 7607Returns true when the running coroutine can yield. 7608 7609 7610<p> 7611A running coroutine is yieldable if it is not the main thread and 7612it is not inside a non-yieldable C function. 7613 7614 7615 7616 7617<p> 7618<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, ···])</code></a></h3> 7619 7620 7621<p> 7622Starts or continues the execution of coroutine <code>co</code>. 7623The first time you resume a coroutine, 7624it starts running its body. 7625The values <code>val1</code>, ... are passed 7626as the arguments to the body function. 7627If the coroutine has yielded, 7628<code>resume</code> restarts it; 7629the values <code>val1</code>, ... are passed 7630as the results from the yield. 7631 7632 7633<p> 7634If the coroutine runs without any errors, 7635<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code> 7636(when the coroutine yields) or any values returned by the body function 7637(when the coroutine terminates). 7638If there is any error, 7639<code>resume</code> returns <b>false</b> plus the error message. 7640 7641 7642 7643 7644<p> 7645<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3> 7646 7647 7648<p> 7649Returns the running coroutine plus a boolean, 7650true when the running coroutine is the main one. 7651 7652 7653 7654 7655<p> 7656<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3> 7657 7658 7659<p> 7660Returns the status of coroutine <code>co</code>, as a string: 7661<code>"running"</code>, 7662if the coroutine is running (that is, it called <code>status</code>); 7663<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>, 7664or if it has not started running yet; 7665<code>"normal"</code> if the coroutine is active but not running 7666(that is, it has resumed another coroutine); 7667and <code>"dead"</code> if the coroutine has finished its body function, 7668or if it has stopped with an error. 7669 7670 7671 7672 7673<p> 7674<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3> 7675 7676 7677<p> 7678Creates a new coroutine, with body <code>f</code>. 7679<code>f</code> must be a function. 7680Returns a function that resumes the coroutine each time it is called. 7681Any arguments passed to the function behave as the 7682extra arguments to <code>resume</code>. 7683Returns the same values returned by <code>resume</code>, 7684except the first boolean. 7685In case of error, propagates the error. 7686 7687 7688 7689 7690<p> 7691<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (···)</code></a></h3> 7692 7693 7694<p> 7695Suspends the execution of the calling coroutine. 7696Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>. 7697 7698 7699 7700 7701 7702 7703 7704<h2>6.3 – <a name="6.3">Modules</a></h2> 7705 7706<p> 7707The package library provides basic 7708facilities for loading modules in Lua. 7709It exports one function directly in the global environment: 7710<a href="#pdf-require"><code>require</code></a>. 7711Everything else is exported in a table <a name="pdf-package"><code>package</code></a>. 7712 7713 7714<p> 7715<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3> 7716 7717 7718<p> 7719Loads the given module. 7720The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table 7721to determine whether <code>modname</code> is already loaded. 7722If it is, then <code>require</code> returns the value stored 7723at <code>package.loaded[modname]</code>. 7724Otherwise, it tries to find a <em>loader</em> for the module. 7725 7726 7727<p> 7728To find a loader, 7729<code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence. 7730By changing this sequence, 7731we can change how <code>require</code> looks for a module. 7732The following explanation is based on the default configuration 7733for <a href="#pdf-package.searchers"><code>package.searchers</code></a>. 7734 7735 7736<p> 7737First <code>require</code> queries <code>package.preload[modname]</code>. 7738If it has a value, 7739this value (which must be a function) is the loader. 7740Otherwise <code>require</code> searches for a Lua loader using the 7741path stored in <a href="#pdf-package.path"><code>package.path</code></a>. 7742If that also fails, it searches for a C loader using the 7743path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>. 7744If that also fails, 7745it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>). 7746 7747 7748<p> 7749Once a loader is found, 7750<code>require</code> calls the loader with two arguments: 7751<code>modname</code> and an extra value dependent on how it got the loader. 7752(If the loader came from a file, 7753this extra value is the file name.) 7754If the loader returns any non-nil value, 7755<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>. 7756If the loader does not return a non-nil value and 7757has not assigned any value to <code>package.loaded[modname]</code>, 7758then <code>require</code> assigns <b>true</b> to this entry. 7759In any case, <code>require</code> returns the 7760final value of <code>package.loaded[modname]</code>. 7761 7762 7763<p> 7764If there is any error loading or running the module, 7765or if it cannot find any loader for the module, 7766then <code>require</code> raises an error. 7767 7768 7769 7770 7771<p> 7772<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3> 7773 7774 7775<p> 7776A string describing some compile-time configurations for packages. 7777This string is a sequence of lines: 7778 7779<ul> 7780 7781<li>The first line is the directory separator string. 7782Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li> 7783 7784<li>The second line is the character that separates templates in a path. 7785Default is '<code>;</code>'.</li> 7786 7787<li>The third line is the string that marks the 7788substitution points in a template. 7789Default is '<code>?</code>'.</li> 7790 7791<li>The fourth line is a string that, in a path in Windows, 7792is replaced by the executable's directory. 7793Default is '<code>!</code>'.</li> 7794 7795<li>The fifth line is a mark to ignore all text after it 7796when building the <code>luaopen_</code> function name. 7797Default is '<code>-</code>'.</li> 7798 7799</ul> 7800 7801 7802 7803<p> 7804<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3> 7805 7806 7807<p> 7808The path used by <a href="#pdf-require"><code>require</code></a> to search for a C loader. 7809 7810 7811<p> 7812Lua initializes the C path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way 7813it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>, 7814using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a> 7815or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a> 7816or a default path defined in <code>luaconf.h</code>. 7817 7818 7819 7820 7821<p> 7822<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3> 7823 7824 7825<p> 7826A table used by <a href="#pdf-require"><code>require</code></a> to control which 7827modules are already loaded. 7828When you require a module <code>modname</code> and 7829<code>package.loaded[modname]</code> is not false, 7830<a href="#pdf-require"><code>require</code></a> simply returns the value stored there. 7831 7832 7833<p> 7834This variable is only a reference to the real table; 7835assignments to this variable do not change the 7836table used by <a href="#pdf-require"><code>require</code></a>. 7837 7838 7839 7840 7841<p> 7842<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3> 7843 7844 7845<p> 7846Dynamically links the host program with the C library <code>libname</code>. 7847 7848 7849<p> 7850If <code>funcname</code> is "<code>*</code>", 7851then it only links with the library, 7852making the symbols exported by the library 7853available to other dynamically linked libraries. 7854Otherwise, 7855it looks for a function <code>funcname</code> inside the library 7856and returns this function as a C function. 7857So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype 7858(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 7859 7860 7861<p> 7862This is a low-level function. 7863It completely bypasses the package and module system. 7864Unlike <a href="#pdf-require"><code>require</code></a>, 7865it does not perform any path searching and 7866does not automatically adds extensions. 7867<code>libname</code> must be the complete file name of the C library, 7868including if necessary a path and an extension. 7869<code>funcname</code> must be the exact name exported by the C library 7870(which may depend on the C compiler and linker used). 7871 7872 7873<p> 7874This function is not supported by Standard C. 7875As such, it is only available on some platforms 7876(Windows, Linux, Mac OS X, Solaris, BSD, 7877plus other Unix systems that support the <code>dlfcn</code> standard). 7878 7879 7880 7881 7882<p> 7883<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3> 7884 7885 7886<p> 7887The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader. 7888 7889 7890<p> 7891At start-up, Lua initializes this variable with 7892the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or 7893the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or 7894with a default path defined in <code>luaconf.h</code>, 7895if those environment variables are not defined. 7896Any "<code>;;</code>" in the value of the environment variable 7897is replaced by the default path. 7898 7899 7900 7901 7902<p> 7903<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3> 7904 7905 7906<p> 7907A table to store loaders for specific modules 7908(see <a href="#pdf-require"><code>require</code></a>). 7909 7910 7911<p> 7912This variable is only a reference to the real table; 7913assignments to this variable do not change the 7914table used by <a href="#pdf-require"><code>require</code></a>. 7915 7916 7917 7918 7919<p> 7920<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3> 7921 7922 7923<p> 7924A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules. 7925 7926 7927<p> 7928Each entry in this table is a <em>searcher function</em>. 7929When looking for a module, 7930<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order, 7931with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its 7932sole parameter. 7933The function can return another function (the module <em>loader</em>) 7934plus an extra value that will be passed to that loader, 7935or a string explaining why it did not find that module 7936(or <b>nil</b> if it has nothing to say). 7937 7938 7939<p> 7940Lua initializes this table with four searcher functions. 7941 7942 7943<p> 7944The first searcher simply looks for a loader in the 7945<a href="#pdf-package.preload"><code>package.preload</code></a> table. 7946 7947 7948<p> 7949The second searcher looks for a loader as a Lua library, 7950using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>. 7951The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 7952 7953 7954<p> 7955The third searcher looks for a loader as a C library, 7956using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>. 7957Again, 7958the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 7959For instance, 7960if the C path is the string 7961 7962<pre> 7963 "./?.so;./?.dll;/usr/local/?/init.so" 7964</pre><p> 7965the searcher for module <code>foo</code> 7966will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>, 7967and <code>/usr/local/foo/init.so</code>, in that order. 7968Once it finds a C library, 7969this searcher first uses a dynamic link facility to link the 7970application with the library. 7971Then it tries to find a C function inside the library to 7972be used as the loader. 7973The name of this C function is the string "<code>luaopen_</code>" 7974concatenated with a copy of the module name where each dot 7975is replaced by an underscore. 7976Moreover, if the module name has a hyphen, 7977its suffix after (and including) the first hyphen is removed. 7978For instance, if the module name is <code>a.b.c-v2.1</code>, 7979the function name will be <code>luaopen_a_b_c</code>. 7980 7981 7982<p> 7983The fourth searcher tries an <em>all-in-one loader</em>. 7984It searches the C path for a library for 7985the root name of the given module. 7986For instance, when requiring <code>a.b.c</code>, 7987it will search for a C library for <code>a</code>. 7988If found, it looks into it for an open function for 7989the submodule; 7990in our example, that would be <code>luaopen_a_b_c</code>. 7991With this facility, a package can pack several C submodules 7992into one single library, 7993with each submodule keeping its original open function. 7994 7995 7996<p> 7997All searchers except the first one (preload) return as the extra value 7998the file name where the module was found, 7999as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 8000The first searcher returns no extra value. 8001 8002 8003 8004 8005<p> 8006<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3> 8007 8008 8009<p> 8010Searches for the given <code>name</code> in the given <code>path</code>. 8011 8012 8013<p> 8014A path is a string containing a sequence of 8015<em>templates</em> separated by semicolons. 8016For each template, 8017the function replaces each interrogation mark (if any) 8018in the template with a copy of <code>name</code> 8019wherein all occurrences of <code>sep</code> 8020(a dot, by default) 8021were replaced by <code>rep</code> 8022(the system's directory separator, by default), 8023and then tries to open the resulting file name. 8024 8025 8026<p> 8027For instance, if the path is the string 8028 8029<pre> 8030 "./?.lua;./?.lc;/usr/local/?/init.lua" 8031</pre><p> 8032the search for the name <code>foo.a</code> 8033will try to open the files 8034<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and 8035<code>/usr/local/foo/a/init.lua</code>, in that order. 8036 8037 8038<p> 8039Returns the resulting name of the first file that it can 8040open in read mode (after closing the file), 8041or <b>nil</b> plus an error message if none succeeds. 8042(This error message lists all file names it tried to open.) 8043 8044 8045 8046 8047 8048 8049 8050<h2>6.4 – <a name="6.4">String Manipulation</a></h2> 8051 8052<p> 8053This library provides generic functions for string manipulation, 8054such as finding and extracting substrings, and pattern matching. 8055When indexing a string in Lua, the first character is at position 1 8056(not at 0, as in C). 8057Indices are allowed to be negative and are interpreted as indexing backwards, 8058from the end of the string. 8059Thus, the last character is at position -1, and so on. 8060 8061 8062<p> 8063The string library provides all its functions inside the table 8064<a name="pdf-string"><code>string</code></a>. 8065It also sets a metatable for strings 8066where the <code>__index</code> field points to the <code>string</code> table. 8067Therefore, you can use the string functions in object-oriented style. 8068For instance, <code>string.byte(s,i)</code> 8069can be written as <code>s:byte(i)</code>. 8070 8071 8072<p> 8073The string library assumes one-byte character encodings. 8074 8075 8076<p> 8077<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3> 8078Returns the internal numeric codes of the characters <code>s[i]</code>, 8079<code>s[i+1]</code>, ..., <code>s[j]</code>. 8080The default value for <code>i</code> is 1; 8081the default value for <code>j</code> is <code>i</code>. 8082These indices are corrected 8083following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>. 8084 8085 8086<p> 8087Numeric codes are not necessarily portable across platforms. 8088 8089 8090 8091 8092<p> 8093<hr><h3><a name="pdf-string.char"><code>string.char (···)</code></a></h3> 8094Receives zero or more integers. 8095Returns a string with length equal to the number of arguments, 8096in which each character has the internal numeric code equal 8097to its corresponding argument. 8098 8099 8100<p> 8101Numeric codes are not necessarily portable across platforms. 8102 8103 8104 8105 8106<p> 8107<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3> 8108 8109 8110<p> 8111Returns a string containing a binary representation 8112(a <em>binary chunk</em>) 8113of the given function, 8114so that a later <a href="#pdf-load"><code>load</code></a> on this string returns 8115a copy of the function (but with new upvalues). 8116If <code>strip</code> is a true value, 8117the binary representation may not include all debug information 8118about the function, 8119to save space. 8120 8121 8122<p> 8123Functions with upvalues have only their number of upvalues saved. 8124When (re)loaded, 8125those upvalues receive fresh instances containing <b>nil</b>. 8126(You can use the debug library to serialize 8127and reload the upvalues of a function 8128in a way adequate to your needs.) 8129 8130 8131 8132 8133<p> 8134<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3> 8135 8136 8137<p> 8138Looks for the first match of 8139<code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>. 8140If it finds a match, then <code>find</code> returns the indices of <code>s</code> 8141where this occurrence starts and ends; 8142otherwise, it returns <b>nil</b>. 8143A third, optional numeric argument <code>init</code> specifies 8144where to start the search; 8145its default value is 1 and can be negative. 8146A value of <b>true</b> as a fourth, optional argument <code>plain</code> 8147turns off the pattern matching facilities, 8148so the function does a plain "find substring" operation, 8149with no characters in <code>pattern</code> being considered magic. 8150Note that if <code>plain</code> is given, then <code>init</code> must be given as well. 8151 8152 8153<p> 8154If the pattern has captures, 8155then in a successful match 8156the captured values are also returned, 8157after the two indices. 8158 8159 8160 8161 8162<p> 8163<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, ···)</code></a></h3> 8164 8165 8166<p> 8167Returns a formatted version of its variable number of arguments 8168following the description given in its first argument (which must be a string). 8169The format string follows the same rules as the ISO C function <code>sprintf</code>. 8170The only differences are that the options/modifiers 8171<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>, 8172and <code>p</code> are not supported 8173and that there is an extra option, <code>q</code>. 8174The <code>q</code> option formats a string between double quotes, 8175using escape sequences when necessary to ensure that 8176it can safely be read back by the Lua interpreter. 8177For instance, the call 8178 8179<pre> 8180 string.format('%q', 'a string with "quotes" and \n new line') 8181</pre><p> 8182may produce the string: 8183 8184<pre> 8185 "a string with \"quotes\" and \ 8186 new line" 8187</pre> 8188 8189<p> 8190Options 8191<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>, 8192<code>G</code>, and <code>g</code> all expect a number as argument. 8193Options <code>c</code>, <code>d</code>, 8194<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> 8195expect an integer. 8196Option <code>q</code> expects a string. 8197Option <code>s</code> expects a string without embedded zeros; 8198if its argument is not a string, 8199it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>. 8200 8201 8202<p> 8203When Lua is compiled with a non-C99 compiler, 8204options <code>A</code> and <code>a</code> (hexadecimal floats) 8205do not support any modifier (flags, width, length). 8206 8207 8208 8209 8210<p> 8211<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3> 8212Returns an iterator function that, 8213each time it is called, 8214returns the next captures from <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) 8215over the string <code>s</code>. 8216If <code>pattern</code> specifies no captures, 8217then the whole match is produced in each call. 8218 8219 8220<p> 8221As an example, the following loop 8222will iterate over all the words from string <code>s</code>, 8223printing one per line: 8224 8225<pre> 8226 s = "hello world from Lua" 8227 for w in string.gmatch(s, "%a+") do 8228 print(w) 8229 end 8230</pre><p> 8231The next example collects all pairs <code>key=value</code> from the 8232given string into a table: 8233 8234<pre> 8235 t = {} 8236 s = "from=world, to=Lua" 8237 for k, v in string.gmatch(s, "(%w+)=(%w+)") do 8238 t[k] = v 8239 end 8240</pre> 8241 8242<p> 8243For this function, a caret '<code>^</code>' at the start of a pattern does not 8244work as an anchor, as this would prevent the iteration. 8245 8246 8247 8248 8249<p> 8250<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3> 8251Returns a copy of <code>s</code> 8252in which all (or the first <code>n</code>, if given) 8253occurrences of the <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) have been 8254replaced by a replacement string specified by <code>repl</code>, 8255which can be a string, a table, or a function. 8256<code>gsub</code> also returns, as its second value, 8257the total number of matches that occurred. 8258The name <code>gsub</code> comes from <em>Global SUBstitution</em>. 8259 8260 8261<p> 8262If <code>repl</code> is a string, then its value is used for replacement. 8263The character <code>%</code> works as an escape character: 8264any sequence in <code>repl</code> of the form <code>%<em>d</em></code>, 8265with <em>d</em> between 1 and 9, 8266stands for the value of the <em>d</em>-th captured substring. 8267The sequence <code>%0</code> stands for the whole match. 8268The sequence <code>%%</code> stands for a single <code>%</code>. 8269 8270 8271<p> 8272If <code>repl</code> is a table, then the table is queried for every match, 8273using the first capture as the key. 8274 8275 8276<p> 8277If <code>repl</code> is a function, then this function is called every time a 8278match occurs, with all captured substrings passed as arguments, 8279in order. 8280 8281 8282<p> 8283In any case, 8284if the pattern specifies no captures, 8285then it behaves as if the whole pattern was inside a capture. 8286 8287 8288<p> 8289If the value returned by the table query or by the function call 8290is a string or a number, 8291then it is used as the replacement string; 8292otherwise, if it is <b>false</b> or <b>nil</b>, 8293then there is no replacement 8294(that is, the original match is kept in the string). 8295 8296 8297<p> 8298Here are some examples: 8299 8300<pre> 8301 x = string.gsub("hello world", "(%w+)", "%1 %1") 8302 --> x="hello hello world world" 8303 8304 x = string.gsub("hello world", "%w+", "%0 %0", 1) 8305 --> x="hello hello world" 8306 8307 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") 8308 --> x="world hello Lua from" 8309 8310 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) 8311 --> x="home = /home/roberto, user = roberto" 8312 8313 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) 8314 return load(s)() 8315 end) 8316 --> x="4+5 = 9" 8317 8318 local t = {name="lua", version="5.3"} 8319 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) 8320 --> x="lua-5.3.tar.gz" 8321</pre> 8322 8323 8324 8325<p> 8326<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3> 8327Receives a string and returns its length. 8328The empty string <code>""</code> has length 0. 8329Embedded zeros are counted, 8330so <code>"a\000bc\000"</code> has length 5. 8331 8332 8333 8334 8335<p> 8336<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3> 8337Receives a string and returns a copy of this string with all 8338uppercase letters changed to lowercase. 8339All other characters are left unchanged. 8340The definition of what an uppercase letter is depends on the current locale. 8341 8342 8343 8344 8345<p> 8346<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3> 8347Looks for the first <em>match</em> of 8348<code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>. 8349If it finds one, then <code>match</code> returns 8350the captures from the pattern; 8351otherwise it returns <b>nil</b>. 8352If <code>pattern</code> specifies no captures, 8353then the whole match is returned. 8354A third, optional numeric argument <code>init</code> specifies 8355where to start the search; 8356its default value is 1 and can be negative. 8357 8358 8359 8360 8361<p> 8362<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, ···)</code></a></h3> 8363 8364 8365<p> 8366Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc. 8367packed (that is, serialized in binary form) 8368according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>). 8369 8370 8371 8372 8373<p> 8374<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3> 8375 8376 8377<p> 8378Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a> 8379with the given format. 8380The format string cannot have the variable-length options 8381'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">§6.4.2</a>). 8382 8383 8384 8385 8386<p> 8387<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3> 8388Returns a string that is the concatenation of <code>n</code> copies of 8389the string <code>s</code> separated by the string <code>sep</code>. 8390The default value for <code>sep</code> is the empty string 8391(that is, no separator). 8392Returns the empty string if <code>n</code> is not positive. 8393 8394 8395 8396 8397<p> 8398<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3> 8399Returns a string that is the string <code>s</code> reversed. 8400 8401 8402 8403 8404<p> 8405<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3> 8406Returns the substring of <code>s</code> that 8407starts at <code>i</code> and continues until <code>j</code>; 8408<code>i</code> and <code>j</code> can be negative. 8409If <code>j</code> is absent, then it is assumed to be equal to -1 8410(which is the same as the string length). 8411In particular, 8412the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code> 8413with length <code>j</code>, 8414and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code> 8415with length <code>i</code>. 8416 8417 8418<p> 8419If, after the translation of negative indices, 8420<code>i</code> is less than 1, 8421it is corrected to 1. 8422If <code>j</code> is greater than the string length, 8423it is corrected to that length. 8424If, after these corrections, 8425<code>i</code> is greater than <code>j</code>, 8426the function returns the empty string. 8427 8428 8429 8430 8431<p> 8432<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3> 8433 8434 8435<p> 8436Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>) 8437according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>). 8438An optional <code>pos</code> marks where 8439to start reading in <code>s</code> (default is 1). 8440After the read values, 8441this function also returns the index of the first unread byte in <code>s</code>. 8442 8443 8444 8445 8446<p> 8447<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3> 8448Receives a string and returns a copy of this string with all 8449lowercase letters changed to uppercase. 8450All other characters are left unchanged. 8451The definition of what a lowercase letter is depends on the current locale. 8452 8453 8454 8455 8456 8457<h3>6.4.1 – <a name="6.4.1">Patterns</a></h3> 8458 8459<p> 8460Patterns in Lua are described by regular strings, 8461which are interpreted as patterns by the pattern-matching functions 8462<a href="#pdf-string.find"><code>string.find</code></a>, 8463<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>, 8464<a href="#pdf-string.gsub"><code>string.gsub</code></a>, 8465and <a href="#pdf-string.match"><code>string.match</code></a>. 8466This section describes the syntax and the meaning 8467(that is, what they match) of these strings. 8468 8469 8470 8471<h4>Character Class:</h4><p> 8472A <em>character class</em> is used to represent a set of characters. 8473The following combinations are allowed in describing a character class: 8474 8475<ul> 8476 8477<li><b><em>x</em>: </b> 8478(where <em>x</em> is not one of the <em>magic characters</em> 8479<code>^$()%.[]*+-?</code>) 8480represents the character <em>x</em> itself. 8481</li> 8482 8483<li><b><code>.</code>: </b> (a dot) represents all characters.</li> 8484 8485<li><b><code>%a</code>: </b> represents all letters.</li> 8486 8487<li><b><code>%c</code>: </b> represents all control characters.</li> 8488 8489<li><b><code>%d</code>: </b> represents all digits.</li> 8490 8491<li><b><code>%g</code>: </b> represents all printable characters except space.</li> 8492 8493<li><b><code>%l</code>: </b> represents all lowercase letters.</li> 8494 8495<li><b><code>%p</code>: </b> represents all punctuation characters.</li> 8496 8497<li><b><code>%s</code>: </b> represents all space characters.</li> 8498 8499<li><b><code>%u</code>: </b> represents all uppercase letters.</li> 8500 8501<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li> 8502 8503<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li> 8504 8505<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character) 8506represents the character <em>x</em>. 8507This is the standard way to escape the magic characters. 8508Any non-alphanumeric character 8509(including all punctuation characters, even the non-magical) 8510can be preceded by a '<code>%</code>' 8511when used to represent itself in a pattern. 8512</li> 8513 8514<li><b><code>[<em>set</em>]</code>: </b> 8515represents the class which is the union of all 8516characters in <em>set</em>. 8517A range of characters can be specified by 8518separating the end characters of the range, 8519in ascending order, with a '<code>-</code>'. 8520All classes <code>%</code><em>x</em> described above can also be used as 8521components in <em>set</em>. 8522All other characters in <em>set</em> represent themselves. 8523For example, <code>[%w_]</code> (or <code>[_%w]</code>) 8524represents all alphanumeric characters plus the underscore, 8525<code>[0-7]</code> represents the octal digits, 8526and <code>[0-7%l%-]</code> represents the octal digits plus 8527the lowercase letters plus the '<code>-</code>' character. 8528 8529 8530<p> 8531The interaction between ranges and classes is not defined. 8532Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code> 8533have no meaning. 8534</li> 8535 8536<li><b><code>[^<em>set</em>]</code>: </b> 8537represents the complement of <em>set</em>, 8538where <em>set</em> is interpreted as above. 8539</li> 8540 8541</ul><p> 8542For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.), 8543the corresponding uppercase letter represents the complement of the class. 8544For instance, <code>%S</code> represents all non-space characters. 8545 8546 8547<p> 8548The definitions of letter, space, and other character groups 8549depend on the current locale. 8550In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>. 8551 8552 8553 8554 8555 8556<h4>Pattern Item:</h4><p> 8557A <em>pattern item</em> can be 8558 8559<ul> 8560 8561<li> 8562a single character class, 8563which matches any single character in the class; 8564</li> 8565 8566<li> 8567a single character class followed by '<code>*</code>', 8568which matches zero or more repetitions of characters in the class. 8569These repetition items will always match the longest possible sequence; 8570</li> 8571 8572<li> 8573a single character class followed by '<code>+</code>', 8574which matches one or more repetitions of characters in the class. 8575These repetition items will always match the longest possible sequence; 8576</li> 8577 8578<li> 8579a single character class followed by '<code>-</code>', 8580which also matches zero or more repetitions of characters in the class. 8581Unlike '<code>*</code>', 8582these repetition items will always match the shortest possible sequence; 8583</li> 8584 8585<li> 8586a single character class followed by '<code>?</code>', 8587which matches zero or one occurrence of a character in the class. 8588It always matches one occurrence if possible; 8589</li> 8590 8591<li> 8592<code>%<em>n</em></code>, for <em>n</em> between 1 and 9; 8593such item matches a substring equal to the <em>n</em>-th captured string 8594(see below); 8595</li> 8596 8597<li> 8598<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters; 8599such item matches strings that start with <em>x</em>, end with <em>y</em>, 8600and where the <em>x</em> and <em>y</em> are <em>balanced</em>. 8601This means that, if one reads the string from left to right, 8602counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>, 8603the ending <em>y</em> is the first <em>y</em> where the count reaches 0. 8604For instance, the item <code>%b()</code> matches expressions with 8605balanced parentheses. 8606</li> 8607 8608<li> 8609<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>; 8610such item matches an empty string at any position such that 8611the next character belongs to <em>set</em> 8612and the previous character does not belong to <em>set</em>. 8613The set <em>set</em> is interpreted as previously described. 8614The beginning and the end of the subject are handled as if 8615they were the character '<code>\0</code>'. 8616</li> 8617 8618</ul> 8619 8620 8621 8622 8623<h4>Pattern:</h4><p> 8624A <em>pattern</em> is a sequence of pattern items. 8625A caret '<code>^</code>' at the beginning of a pattern anchors the match at the 8626beginning of the subject string. 8627A '<code>$</code>' at the end of a pattern anchors the match at the 8628end of the subject string. 8629At other positions, 8630'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves. 8631 8632 8633 8634 8635 8636<h4>Captures:</h4><p> 8637A pattern can contain sub-patterns enclosed in parentheses; 8638they describe <em>captures</em>. 8639When a match succeeds, the substrings of the subject string 8640that match captures are stored (<em>captured</em>) for future use. 8641Captures are numbered according to their left parentheses. 8642For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>, 8643the part of the string matching <code>"a*(.)%w(%s*)"</code> is 8644stored as the first capture (and therefore has number 1); 8645the character matching "<code>.</code>" is captured with number 2, 8646and the part matching "<code>%s*</code>" has number 3. 8647 8648 8649<p> 8650As a special case, the empty capture <code>()</code> captures 8651the current string position (a number). 8652For instance, if we apply the pattern <code>"()aa()"</code> on the 8653string <code>"flaaap"</code>, there will be two captures: 3 and 5. 8654 8655 8656 8657 8658 8659 8660 8661<h3>6.4.2 – <a name="6.4.2">Format Strings for Pack and Unpack</a></h3> 8662 8663<p> 8664The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>, 8665<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a> 8666is a format string, 8667which describes the layout of the structure being created or read. 8668 8669 8670<p> 8671A format string is a sequence of conversion options. 8672The conversion options are as follows: 8673 8674<ul> 8675<li><b><code><</code>: </b>sets little endian</li> 8676<li><b><code>></code>: </b>sets big endian</li> 8677<li><b><code>=</code>: </b>sets native endian</li> 8678<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code> 8679(default is native alignment)</li> 8680<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li> 8681<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li> 8682<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li> 8683<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li> 8684<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li> 8685<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li> 8686<li><b><code>j</code>: </b>a <code>lua_Integer</code></li> 8687<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li> 8688<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li> 8689<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes 8690(default is native size)</li> 8691<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes 8692(default is native size)</li> 8693<li><b><code>f</code>: </b>a <code>float</code> (native size)</li> 8694<li><b><code>d</code>: </b>a <code>double</code> (native size)</li> 8695<li><b><code>n</code>: </b>a <code>lua_Number</code></li> 8696<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li> 8697<li><b><code>z</code>: </b>a zero-terminated string</li> 8698<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length 8699coded as an unsigned integer with <code>n</code> bytes 8700(default is a <code>size_t</code>)</li> 8701<li><b><code>x</code>: </b>one byte of padding</li> 8702<li><b><code>X<em>op</em></code>: </b>an empty item that aligns 8703according to option <code>op</code> 8704(which is otherwise ignored)</li> 8705<li><b>'<code> </code>': </b>(empty space) ignored</li> 8706</ul><p> 8707(A "<code>[<em>n</em>]</code>" means an optional integral numeral.) 8708Except for padding, spaces, and configurations 8709(options "<code>xX <=>!</code>"), 8710each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>) 8711or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>). 8712 8713 8714<p> 8715For options "<code>!<em>n</em></code>", "<code>s<em>n</em></code>", "<code>i<em>n</em></code>", and "<code>I<em>n</em></code>", 8716<code>n</code> can be any integer between 1 and 16. 8717All integral options check overflows; 8718<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size; 8719<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer. 8720 8721 8722<p> 8723Any format string starts as if prefixed by "<code>!1=</code>", 8724that is, 8725with maximum alignment of 1 (no alignment) 8726and native endianness. 8727 8728 8729<p> 8730Alignment works as follows: 8731For each option, 8732the format gets extra padding until the data starts 8733at an offset that is a multiple of the minimum between the 8734option size and the maximum alignment; 8735this minimum must be a power of 2. 8736Options "<code>c</code>" and "<code>z</code>" are not aligned; 8737option "<code>s</code>" follows the alignment of its starting integer. 8738 8739 8740<p> 8741All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a> 8742(and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>). 8743 8744 8745 8746 8747 8748 8749 8750<h2>6.5 – <a name="6.5">UTF-8 Support</a></h2> 8751 8752<p> 8753This library provides basic support for UTF-8 encoding. 8754It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>. 8755This library does not provide any support for Unicode other 8756than the handling of the encoding. 8757Any operation that needs the meaning of a character, 8758such as character classification, is outside its scope. 8759 8760 8761<p> 8762Unless stated otherwise, 8763all functions that expect a byte position as a parameter 8764assume that the given position is either the start of a byte sequence 8765or one plus the length of the subject string. 8766As in the string library, 8767negative indices count from the end of the string. 8768 8769 8770<p> 8771<hr><h3><a name="pdf-utf8.char"><code>utf8.char (···)</code></a></h3> 8772Receives zero or more integers, 8773converts each one to its corresponding UTF-8 byte sequence 8774and returns a string with the concatenation of all these sequences. 8775 8776 8777 8778 8779<p> 8780<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3> 8781The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>" 8782(see <a href="#6.4.1">§6.4.1</a>), 8783which matches exactly one UTF-8 byte sequence, 8784assuming that the subject is a valid UTF-8 string. 8785 8786 8787 8788 8789<p> 8790<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3> 8791 8792 8793<p> 8794Returns values so that the construction 8795 8796<pre> 8797 for p, c in utf8.codes(s) do <em>body</em> end 8798</pre><p> 8799will iterate over all characters in string <code>s</code>, 8800with <code>p</code> being the position (in bytes) and <code>c</code> the code point 8801of each character. 8802It raises an error if it meets any invalid byte sequence. 8803 8804 8805 8806 8807<p> 8808<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3> 8809Returns the codepoints (as integers) from all characters in <code>s</code> 8810that start between byte position <code>i</code> and <code>j</code> (both included). 8811The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>. 8812It raises an error if it meets any invalid byte sequence. 8813 8814 8815 8816 8817<p> 8818<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3> 8819Returns the number of UTF-8 characters in string <code>s</code> 8820that start between positions <code>i</code> and <code>j</code> (both inclusive). 8821The default for <code>i</code> is 1 and for <code>j</code> is -1. 8822If it finds any invalid byte sequence, 8823returns a false value plus the position of the first invalid byte. 8824 8825 8826 8827 8828<p> 8829<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3> 8830Returns the position (in bytes) where the encoding of the 8831<code>n</code>-th character of <code>s</code> 8832(counting from position <code>i</code>) starts. 8833A negative <code>n</code> gets characters before position <code>i</code>. 8834The default for <code>i</code> is 1 when <code>n</code> is non-negative 8835and <code>#s + 1</code> otherwise, 8836so that <code>utf8.offset(s, -n)</code> gets the offset of the 8837<code>n</code>-th character from the end of the string. 8838If the specified character is neither in the subject 8839nor right after its end, 8840the function returns <b>nil</b>. 8841 8842 8843<p> 8844As a special case, 8845when <code>n</code> is 0 the function returns the start of the encoding 8846of the character that contains the <code>i</code>-th byte of <code>s</code>. 8847 8848 8849<p> 8850This function assumes that <code>s</code> is a valid UTF-8 string. 8851 8852 8853 8854 8855 8856 8857 8858<h2>6.6 – <a name="6.6">Table Manipulation</a></h2> 8859 8860<p> 8861This library provides generic functions for table manipulation. 8862It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>. 8863 8864 8865<p> 8866Remember that, whenever an operation needs the length of a table, 8867the table must be a proper sequence 8868or have a <code>__len</code> metamethod (see <a href="#3.4.7">§3.4.7</a>). 8869All functions ignore non-numeric keys 8870in the tables given as arguments. 8871 8872 8873<p> 8874<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3> 8875 8876 8877<p> 8878Given a list where all elements are strings or numbers, 8879returns the string <code>list[i]..sep..list[i+1] ··· sep..list[j]</code>. 8880The default value for <code>sep</code> is the empty string, 8881the default for <code>i</code> is 1, 8882and the default for <code>j</code> is <code>#list</code>. 8883If <code>i</code> is greater than <code>j</code>, returns the empty string. 8884 8885 8886 8887 8888<p> 8889<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3> 8890 8891 8892<p> 8893Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>, 8894shifting up the elements 8895<code>list[pos], list[pos+1], ···, list[#list]</code>. 8896The default value for <code>pos</code> is <code>#list+1</code>, 8897so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end 8898of list <code>t</code>. 8899 8900 8901 8902 8903<p> 8904<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3> 8905 8906 8907<p> 8908Moves elements from table <code>a1</code> to table <code>a2</code>. 8909This function performs the equivalent to the following 8910multiple assignment: 8911<code>a2[t],··· = a1[f],···,a1[e]</code>. 8912The default for <code>a2</code> is <code>a1</code>. 8913The destination range can overlap with the source range. 8914The number of elements to be moved must fit in a Lua integer. 8915 8916 8917 8918 8919<p> 8920<hr><h3><a name="pdf-table.pack"><code>table.pack (···)</code></a></h3> 8921 8922 8923<p> 8924Returns a new table with all parameters stored into keys 1, 2, etc. 8925and with a field "<code>n</code>" with the total number of parameters. 8926Note that the resulting table may not be a sequence. 8927 8928 8929 8930 8931<p> 8932<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3> 8933 8934 8935<p> 8936Removes from <code>list</code> the element at position <code>pos</code>, 8937returning the value of the removed element. 8938When <code>pos</code> is an integer between 1 and <code>#list</code>, 8939it shifts down the elements 8940<code>list[pos+1], list[pos+2], ···, list[#list]</code> 8941and erases element <code>list[#list]</code>; 8942The index <code>pos</code> can also be 0 when <code>#list</code> is 0, 8943or <code>#list + 1</code>; 8944in those cases, the function erases the element <code>list[pos]</code>. 8945 8946 8947<p> 8948The default value for <code>pos</code> is <code>#list</code>, 8949so that a call <code>table.remove(l)</code> removes the last element 8950of list <code>l</code>. 8951 8952 8953 8954 8955<p> 8956<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3> 8957 8958 8959<p> 8960Sorts list elements in a given order, <em>in-place</em>, 8961from <code>list[1]</code> to <code>list[#list]</code>. 8962If <code>comp</code> is given, 8963then it must be a function that receives two list elements 8964and returns true when the first element must come 8965before the second in the final order 8966(so that <code>not comp(list[i+1],list[i])</code> will be true after the sort). 8967If <code>comp</code> is not given, 8968then the standard Lua operator <code><</code> is used instead. 8969 8970 8971<p> 8972The sort algorithm is not stable; 8973that is, elements considered equal by the given order 8974may have their relative positions changed by the sort. 8975 8976 8977 8978 8979<p> 8980<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3> 8981 8982 8983<p> 8984Returns the elements from the given list. 8985This function is equivalent to 8986 8987<pre> 8988 return list[i], list[i+1], ···, list[j] 8989</pre><p> 8990By default, <code>i</code> is 1 and <code>j</code> is <code>#list</code>. 8991 8992 8993 8994 8995 8996 8997 8998<h2>6.7 – <a name="6.7">Mathematical Functions</a></h2> 8999 9000<p> 9001This library provides basic mathematical functions. 9002It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>. 9003Functions with the annotation "<code>integer/float</code>" give 9004integer results for integer arguments 9005and float results for float (or mixed) arguments. 9006Rounding functions 9007(<a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>) 9008return an integer when the result fits in the range of an integer, 9009or a float otherwise. 9010 9011 9012<p> 9013<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3> 9014 9015 9016<p> 9017Returns the absolute value of <code>x</code>. (integer/float) 9018 9019 9020 9021 9022<p> 9023<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3> 9024 9025 9026<p> 9027Returns the arc cosine of <code>x</code> (in radians). 9028 9029 9030 9031 9032<p> 9033<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3> 9034 9035 9036<p> 9037Returns the arc sine of <code>x</code> (in radians). 9038 9039 9040 9041 9042<p> 9043<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3> 9044 9045 9046<p> 9047 9048Returns the arc tangent of <code>y/x</code> (in radians), 9049but uses the signs of both parameters to find the 9050quadrant of the result. 9051(It also handles correctly the case of <code>x</code> being zero.) 9052 9053 9054<p> 9055The default value for <code>x</code> is 1, 9056so that the call <code>math.atan(y)</code> 9057returns the arc tangent of <code>y</code>. 9058 9059 9060 9061 9062<p> 9063<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3> 9064 9065 9066<p> 9067Returns the smallest integral value larger than or equal to <code>x</code>. 9068 9069 9070 9071 9072<p> 9073<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3> 9074 9075 9076<p> 9077Returns the cosine of <code>x</code> (assumed to be in radians). 9078 9079 9080 9081 9082<p> 9083<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3> 9084 9085 9086<p> 9087Converts the angle <code>x</code> from radians to degrees. 9088 9089 9090 9091 9092<p> 9093<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3> 9094 9095 9096<p> 9097Returns the value <em>e<sup>x</sup></em> 9098(where <code>e</code> is the base of natural logarithms). 9099 9100 9101 9102 9103<p> 9104<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3> 9105 9106 9107<p> 9108Returns the largest integral value smaller than or equal to <code>x</code>. 9109 9110 9111 9112 9113<p> 9114<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3> 9115 9116 9117<p> 9118Returns the remainder of the division of <code>x</code> by <code>y</code> 9119that rounds the quotient towards zero. (integer/float) 9120 9121 9122 9123 9124<p> 9125<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3> 9126 9127 9128<p> 9129The float value <code>HUGE_VAL</code>, 9130a value larger than any other numeric value. 9131 9132 9133 9134 9135<p> 9136<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3> 9137 9138 9139<p> 9140Returns the logarithm of <code>x</code> in the given base. 9141The default for <code>base</code> is <em>e</em> 9142(so that the function returns the natural logarithm of <code>x</code>). 9143 9144 9145 9146 9147<p> 9148<hr><h3><a name="pdf-math.max"><code>math.max (x, ···)</code></a></h3> 9149 9150 9151<p> 9152Returns the argument with the maximum value, 9153according to the Lua operator <code><</code>. (integer/float) 9154 9155 9156 9157 9158<p> 9159<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3> 9160An integer with the maximum value for an integer. 9161 9162 9163 9164 9165<p> 9166<hr><h3><a name="pdf-math.min"><code>math.min (x, ···)</code></a></h3> 9167 9168 9169<p> 9170Returns the argument with the minimum value, 9171according to the Lua operator <code><</code>. (integer/float) 9172 9173 9174 9175 9176<p> 9177<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3> 9178An integer with the minimum value for an integer. 9179 9180 9181 9182 9183<p> 9184<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3> 9185 9186 9187<p> 9188Returns the integral part of <code>x</code> and the fractional part of <code>x</code>. 9189Its second result is always a float. 9190 9191 9192 9193 9194<p> 9195<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3> 9196 9197 9198<p> 9199The value of <em>π</em>. 9200 9201 9202 9203 9204<p> 9205<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3> 9206 9207 9208<p> 9209Converts the angle <code>x</code> from degrees to radians. 9210 9211 9212 9213 9214<p> 9215<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3> 9216 9217 9218<p> 9219When called without arguments, 9220returns a pseudo-random float with uniform distribution 9221in the range <em>[0,1)</em>. 9222When called with two integers <code>m</code> and <code>n</code>, 9223<code>math.random</code> returns a pseudo-random integer 9224with uniform distribution in the range <em>[m, n]</em>. 9225(The value <em>m-n</em> cannot be negative and must fit in a Lua integer.) 9226The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>. 9227 9228 9229<p> 9230This function is an interface to the underling 9231pseudo-random generator function provided by C. 9232No guarantees can be given for its statistical properties. 9233 9234 9235 9236 9237<p> 9238<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3> 9239 9240 9241<p> 9242Sets <code>x</code> as the "seed" 9243for the pseudo-random generator: 9244equal seeds produce equal sequences of numbers. 9245 9246 9247 9248 9249<p> 9250<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3> 9251 9252 9253<p> 9254Returns the sine of <code>x</code> (assumed to be in radians). 9255 9256 9257 9258 9259<p> 9260<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3> 9261 9262 9263<p> 9264Returns the square root of <code>x</code>. 9265(You can also use the expression <code>x^0.5</code> to compute this value.) 9266 9267 9268 9269 9270<p> 9271<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3> 9272 9273 9274<p> 9275Returns the tangent of <code>x</code> (assumed to be in radians). 9276 9277 9278 9279 9280<p> 9281<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3> 9282 9283 9284<p> 9285If the value <code>x</code> is convertible to an integer, 9286returns that integer. 9287Otherwise, returns <b>nil</b>. 9288 9289 9290 9291 9292<p> 9293<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3> 9294 9295 9296<p> 9297Returns "<code>integer</code>" if <code>x</code> is an integer, 9298"<code>float</code>" if it is a float, 9299or <b>nil</b> if <code>x</code> is not a number. 9300 9301 9302 9303 9304<p> 9305<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3> 9306 9307 9308<p> 9309Returns a boolean, 9310true if integer <code>m</code> is below integer <code>n</code> when 9311they are compared as unsigned integers. 9312 9313 9314 9315 9316 9317 9318 9319<h2>6.8 – <a name="6.8">Input and Output Facilities</a></h2> 9320 9321<p> 9322The I/O library provides two different styles for file manipulation. 9323The first one uses implicit file handles; 9324that is, there are operations to set a default input file and a 9325default output file, 9326and all input/output operations are over these default files. 9327The second style uses explicit file handles. 9328 9329 9330<p> 9331When using implicit file handles, 9332all operations are supplied by table <a name="pdf-io"><code>io</code></a>. 9333When using explicit file handles, 9334the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle 9335and then all operations are supplied as methods of the file handle. 9336 9337 9338<p> 9339The table <code>io</code> also provides 9340three predefined file handles with their usual meanings from C: 9341<a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>. 9342The I/O library never closes these files. 9343 9344 9345<p> 9346Unless otherwise stated, 9347all I/O functions return <b>nil</b> on failure 9348(plus an error message as a second result and 9349a system-dependent error code as a third result) 9350and some value different from <b>nil</b> on success. 9351On non-POSIX systems, 9352the computation of the error message and error code 9353in case of errors 9354may be not thread safe, 9355because they rely on the global C variable <code>errno</code>. 9356 9357 9358<p> 9359<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3> 9360 9361 9362<p> 9363Equivalent to <code>file:close()</code>. 9364Without a <code>file</code>, closes the default output file. 9365 9366 9367 9368 9369<p> 9370<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3> 9371 9372 9373<p> 9374Equivalent to <code>io.output():flush()</code>. 9375 9376 9377 9378 9379<p> 9380<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3> 9381 9382 9383<p> 9384When called with a file name, it opens the named file (in text mode), 9385and sets its handle as the default input file. 9386When called with a file handle, 9387it simply sets this file handle as the default input file. 9388When called without parameters, 9389it returns the current default input file. 9390 9391 9392<p> 9393In case of errors this function raises the error, 9394instead of returning an error code. 9395 9396 9397 9398 9399<p> 9400<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename ···])</code></a></h3> 9401 9402 9403<p> 9404Opens the given file name in read mode 9405and returns an iterator function that 9406works like <code>file:lines(···)</code> over the opened file. 9407When the iterator function detects the end of file, 9408it returns no values (to finish the loop) and automatically closes the file. 9409 9410 9411<p> 9412The call <code>io.lines()</code> (with no file name) is equivalent 9413to <code>io.input():lines("*l")</code>; 9414that is, it iterates over the lines of the default input file. 9415In this case it does not close the file when the loop ends. 9416 9417 9418<p> 9419In case of errors this function raises the error, 9420instead of returning an error code. 9421 9422 9423 9424 9425<p> 9426<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3> 9427 9428 9429<p> 9430This function opens a file, 9431in the mode specified in the string <code>mode</code>. 9432It returns a new file handle, 9433or, in case of errors, <b>nil</b> plus an error message. 9434 9435 9436<p> 9437The <code>mode</code> string can be any of the following: 9438 9439<ul> 9440<li><b>"<code>r</code>": </b> read mode (the default);</li> 9441<li><b>"<code>w</code>": </b> write mode;</li> 9442<li><b>"<code>a</code>": </b> append mode;</li> 9443<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li> 9444<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li> 9445<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved, 9446 writing is only allowed at the end of file.</li> 9447</ul><p> 9448The <code>mode</code> string can also have a '<code>b</code>' at the end, 9449which is needed in some systems to open the file in binary mode. 9450 9451 9452 9453 9454<p> 9455<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3> 9456 9457 9458<p> 9459Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file. 9460 9461 9462 9463 9464<p> 9465<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3> 9466 9467 9468<p> 9469This function is system dependent and is not available 9470on all platforms. 9471 9472 9473<p> 9474Starts program <code>prog</code> in a separated process and returns 9475a file handle that you can use to read data from this program 9476(if <code>mode</code> is <code>"r"</code>, the default) 9477or to write data to this program 9478(if <code>mode</code> is <code>"w"</code>). 9479 9480 9481 9482 9483<p> 9484<hr><h3><a name="pdf-io.read"><code>io.read (···)</code></a></h3> 9485 9486 9487<p> 9488Equivalent to <code>io.input():read(···)</code>. 9489 9490 9491 9492 9493<p> 9494<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3> 9495 9496 9497<p> 9498Returns a handle for a temporary file. 9499This file is opened in update mode 9500and it is automatically removed when the program ends. 9501 9502 9503 9504 9505<p> 9506<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3> 9507 9508 9509<p> 9510Checks whether <code>obj</code> is a valid file handle. 9511Returns the string <code>"file"</code> if <code>obj</code> is an open file handle, 9512<code>"closed file"</code> if <code>obj</code> is a closed file handle, 9513or <b>nil</b> if <code>obj</code> is not a file handle. 9514 9515 9516 9517 9518<p> 9519<hr><h3><a name="pdf-io.write"><code>io.write (···)</code></a></h3> 9520 9521 9522<p> 9523Equivalent to <code>io.output():write(···)</code>. 9524 9525 9526 9527 9528<p> 9529<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3> 9530 9531 9532<p> 9533Closes <code>file</code>. 9534Note that files are automatically closed when 9535their handles are garbage collected, 9536but that takes an unpredictable amount of time to happen. 9537 9538 9539<p> 9540When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>, 9541<a href="#pdf-file:close"><code>file:close</code></a> returns the same values 9542returned by <a href="#pdf-os.execute"><code>os.execute</code></a>. 9543 9544 9545 9546 9547<p> 9548<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3> 9549 9550 9551<p> 9552Saves any written data to <code>file</code>. 9553 9554 9555 9556 9557<p> 9558<hr><h3><a name="pdf-file:lines"><code>file:lines (···)</code></a></h3> 9559 9560 9561<p> 9562Returns an iterator function that, 9563each time it is called, 9564reads the file according to the given formats. 9565When no format is given, 9566uses "<code>l</code>" as a default. 9567As an example, the construction 9568 9569<pre> 9570 for c in file:lines(1) do <em>body</em> end 9571</pre><p> 9572will iterate over all characters of the file, 9573starting at the current position. 9574Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file 9575when the loop ends. 9576 9577 9578<p> 9579In case of errors this function raises the error, 9580instead of returning an error code. 9581 9582 9583 9584 9585<p> 9586<hr><h3><a name="pdf-file:read"><code>file:read (···)</code></a></h3> 9587 9588 9589<p> 9590Reads the file <code>file</code>, 9591according to the given formats, which specify what to read. 9592For each format, 9593the function returns a string or a number with the characters read, 9594or <b>nil</b> if it cannot read data with the specified format. 9595(In this latter case, 9596the function does not read subsequent formats.) 9597When called without formats, 9598it uses a default format that reads the next line 9599(see below). 9600 9601 9602<p> 9603The available formats are 9604 9605<ul> 9606 9607<li><b>"<code>n</code>": </b> 9608reads a numeral and returns it as a float or an integer, 9609following the lexical conventions of Lua. 9610(The numeral may have leading spaces and a sign.) 9611This format always reads the longest input sequence that 9612is a valid prefix for a numeral; 9613if that prefix does not form a valid numeral 9614(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"), 9615it is discarded and the function returns <b>nil</b>. 9616</li> 9617 9618<li><b>"<code>a</code>": </b> 9619reads the whole file, starting at the current position. 9620On end of file, it returns the empty string. 9621</li> 9622 9623<li><b>"<code>l</code>": </b> 9624reads the next line skipping the end of line, 9625returning <b>nil</b> on end of file. 9626This is the default format. 9627</li> 9628 9629<li><b>"<code>L</code>": </b> 9630reads the next line keeping the end-of-line character (if present), 9631returning <b>nil</b> on end of file. 9632</li> 9633 9634<li><b><em>number</em>: </b> 9635reads a string with up to this number of bytes, 9636returning <b>nil</b> on end of file. 9637If <code>number</code> is zero, 9638it reads nothing and returns an empty string, 9639or <b>nil</b> on end of file. 9640</li> 9641 9642</ul><p> 9643The formats "<code>l</code>" and "<code>L</code>" should be used only for text files. 9644 9645 9646 9647 9648<p> 9649<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3> 9650 9651 9652<p> 9653Sets and gets the file position, 9654measured from the beginning of the file, 9655to the position given by <code>offset</code> plus a base 9656specified by the string <code>whence</code>, as follows: 9657 9658<ul> 9659<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li> 9660<li><b>"<code>cur</code>": </b> base is current position;</li> 9661<li><b>"<code>end</code>": </b> base is end of file;</li> 9662</ul><p> 9663In case of success, <code>seek</code> returns the final file position, 9664measured in bytes from the beginning of the file. 9665If <code>seek</code> fails, it returns <b>nil</b>, 9666plus a string describing the error. 9667 9668 9669<p> 9670The default value for <code>whence</code> is <code>"cur"</code>, 9671and for <code>offset</code> is 0. 9672Therefore, the call <code>file:seek()</code> returns the current 9673file position, without changing it; 9674the call <code>file:seek("set")</code> sets the position to the 9675beginning of the file (and returns 0); 9676and the call <code>file:seek("end")</code> sets the position to the 9677end of the file, and returns its size. 9678 9679 9680 9681 9682<p> 9683<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3> 9684 9685 9686<p> 9687Sets the buffering mode for an output file. 9688There are three available modes: 9689 9690<ul> 9691 9692<li><b>"<code>no</code>": </b> 9693no buffering; the result of any output operation appears immediately. 9694</li> 9695 9696<li><b>"<code>full</code>": </b> 9697full buffering; output operation is performed only 9698when the buffer is full or when 9699you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>). 9700</li> 9701 9702<li><b>"<code>line</code>": </b> 9703line buffering; output is buffered until a newline is output 9704or there is any input from some special files 9705(such as a terminal device). 9706</li> 9707 9708</ul><p> 9709For the last two cases, <code>size</code> 9710specifies the size of the buffer, in bytes. 9711The default is an appropriate size. 9712 9713 9714 9715 9716<p> 9717<hr><h3><a name="pdf-file:write"><code>file:write (···)</code></a></h3> 9718 9719 9720<p> 9721Writes the value of each of its arguments to <code>file</code>. 9722The arguments must be strings or numbers. 9723 9724 9725<p> 9726In case of success, this function returns <code>file</code>. 9727Otherwise it returns <b>nil</b> plus a string describing the error. 9728 9729 9730 9731 9732 9733 9734 9735<h2>6.9 – <a name="6.9">Operating System Facilities</a></h2> 9736 9737<p> 9738This library is implemented through table <a name="pdf-os"><code>os</code></a>. 9739 9740 9741<p> 9742<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3> 9743 9744 9745<p> 9746Returns an approximation of the amount in seconds of CPU time 9747used by the program. 9748 9749 9750 9751 9752<p> 9753<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3> 9754 9755 9756<p> 9757Returns a string or a table containing date and time, 9758formatted according to the given string <code>format</code>. 9759 9760 9761<p> 9762If the <code>time</code> argument is present, 9763this is the time to be formatted 9764(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value). 9765Otherwise, <code>date</code> formats the current time. 9766 9767 9768<p> 9769If <code>format</code> starts with '<code>!</code>', 9770then the date is formatted in Coordinated Universal Time. 9771After this optional character, 9772if <code>format</code> is the string "<code>*t</code>", 9773then <code>date</code> returns a table with the following fields: 9774<code>year</code> (four digits), <code>month</code> (1–12), <code>day</code> (1–31), 9775<code>hour</code> (0–23), <code>min</code> (0–59), <code>sec</code> (0–61), 9776<code>wday</code> (weekday, Sunday is 1), 9777<code>yday</code> (day of the year), 9778and <code>isdst</code> (daylight saving flag, a boolean). 9779This last field may be absent 9780if the information is not available. 9781 9782 9783<p> 9784If <code>format</code> is not "<code>*t</code>", 9785then <code>date</code> returns the date as a string, 9786formatted according to the same rules as the ISO C function <code>strftime</code>. 9787 9788 9789<p> 9790When called without arguments, 9791<code>date</code> returns a reasonable date and time representation that depends on 9792the host system and on the current locale 9793(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>). 9794 9795 9796<p> 9797On non-POSIX systems, 9798this function may be not thread safe 9799because of its reliance on C function <code>gmtime</code> and C function <code>localtime</code>. 9800 9801 9802 9803 9804<p> 9805<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3> 9806 9807 9808<p> 9809Returns the difference, in seconds, 9810from time <code>t1</code> to time <code>t2</code> 9811(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>). 9812In POSIX, Windows, and some other systems, 9813this value is exactly <code>t2</code><em>-</em><code>t1</code>. 9814 9815 9816 9817 9818<p> 9819<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3> 9820 9821 9822<p> 9823This function is equivalent to the ISO C function <code>system</code>. 9824It passes <code>command</code> to be executed by an operating system shell. 9825Its first result is <b>true</b> 9826if the command terminated successfully, 9827or <b>nil</b> otherwise. 9828After this first result 9829the function returns a string plus a number, 9830as follows: 9831 9832<ul> 9833 9834<li><b>"<code>exit</code>": </b> 9835the command terminated normally; 9836the following number is the exit status of the command. 9837</li> 9838 9839<li><b>"<code>signal</code>": </b> 9840the command was terminated by a signal; 9841the following number is the signal that terminated the command. 9842</li> 9843 9844</ul> 9845 9846<p> 9847When called without a <code>command</code>, 9848<code>os.execute</code> returns a boolean that is true if a shell is available. 9849 9850 9851 9852 9853<p> 9854<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3> 9855 9856 9857<p> 9858Calls the ISO C function <code>exit</code> to terminate the host program. 9859If <code>code</code> is <b>true</b>, 9860the returned status is <code>EXIT_SUCCESS</code>; 9861if <code>code</code> is <b>false</b>, 9862the returned status is <code>EXIT_FAILURE</code>; 9863if <code>code</code> is a number, 9864the returned status is this number. 9865The default value for <code>code</code> is <b>true</b>. 9866 9867 9868<p> 9869If the optional second argument <code>close</code> is true, 9870closes the Lua state before exiting. 9871 9872 9873 9874 9875<p> 9876<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3> 9877 9878 9879<p> 9880Returns the value of the process environment variable <code>varname</code>, 9881or <b>nil</b> if the variable is not defined. 9882 9883 9884 9885 9886<p> 9887<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3> 9888 9889 9890<p> 9891Deletes the file (or empty directory, on POSIX systems) 9892with the given name. 9893If this function fails, it returns <b>nil</b>, 9894plus a string describing the error and the error code. 9895 9896 9897 9898 9899<p> 9900<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3> 9901 9902 9903<p> 9904Renames file or directory named <code>oldname</code> to <code>newname</code>. 9905If this function fails, it returns <b>nil</b>, 9906plus a string describing the error and the error code. 9907 9908 9909 9910 9911<p> 9912<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3> 9913 9914 9915<p> 9916Sets the current locale of the program. 9917<code>locale</code> is a system-dependent string specifying a locale; 9918<code>category</code> is an optional string describing which category to change: 9919<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>, 9920<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>; 9921the default category is <code>"all"</code>. 9922The function returns the name of the new locale, 9923or <b>nil</b> if the request cannot be honored. 9924 9925 9926<p> 9927If <code>locale</code> is the empty string, 9928the current locale is set to an implementation-defined native locale. 9929If <code>locale</code> is the string "<code>C</code>", 9930the current locale is set to the standard C locale. 9931 9932 9933<p> 9934When called with <b>nil</b> as the first argument, 9935this function only returns the name of the current locale 9936for the given category. 9937 9938 9939<p> 9940This function may be not thread safe 9941because of its reliance on C function <code>setlocale</code>. 9942 9943 9944 9945 9946<p> 9947<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3> 9948 9949 9950<p> 9951Returns the current time when called without arguments, 9952or a time representing the local date and time specified by the given table. 9953This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>, 9954and may have fields 9955<code>hour</code> (default is 12), 9956<code>min</code> (default is 0), 9957<code>sec</code> (default is 0), 9958and <code>isdst</code> (default is <b>nil</b>). 9959Other fields are ignored. 9960For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function. 9961 9962 9963<p> 9964The values in these fields do not need to be inside their valid ranges. 9965For instance, if <code>sec</code> is -10, 9966it means -10 seconds from the time specified by the other fields; 9967if <code>hour</code> is 1000, 9968it means +1000 hours from the time specified by the other fields. 9969 9970 9971<p> 9972The returned value is a number, whose meaning depends on your system. 9973In POSIX, Windows, and some other systems, 9974this number counts the number 9975of seconds since some given start time (the "epoch"). 9976In other systems, the meaning is not specified, 9977and the number returned by <code>time</code> can be used only as an argument to 9978<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>. 9979 9980 9981 9982 9983<p> 9984<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3> 9985 9986 9987<p> 9988Returns a string with a file name that can 9989be used for a temporary file. 9990The file must be explicitly opened before its use 9991and explicitly removed when no longer needed. 9992 9993 9994<p> 9995On POSIX systems, 9996this function also creates a file with that name, 9997to avoid security risks. 9998(Someone else might create the file with wrong permissions 9999in the time between getting the name and creating the file.) 10000You still have to open the file to use it 10001and to remove it (even if you do not use it). 10002 10003 10004<p> 10005When possible, 10006you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>, 10007which automatically removes the file when the program ends. 10008 10009 10010 10011 10012 10013 10014 10015<h2>6.10 – <a name="6.10">The Debug Library</a></h2> 10016 10017<p> 10018This library provides 10019the functionality of the debug interface (<a href="#4.9">§4.9</a>) to Lua programs. 10020You should exert care when using this library. 10021Several of its functions 10022violate basic assumptions about Lua code 10023(e.g., that variables local to a function 10024cannot be accessed from outside; 10025that userdata metatables cannot be changed by Lua code; 10026that Lua programs do not crash) 10027and therefore can compromise otherwise secure code. 10028Moreover, some functions in this library may be slow. 10029 10030 10031<p> 10032All functions in this library are provided 10033inside the <a name="pdf-debug"><code>debug</code></a> table. 10034All functions that operate over a thread 10035have an optional first argument which is the 10036thread to operate over. 10037The default is always the current thread. 10038 10039 10040<p> 10041<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3> 10042 10043 10044<p> 10045Enters an interactive mode with the user, 10046running each string that the user enters. 10047Using simple commands and other debug facilities, 10048the user can inspect global and local variables, 10049change their values, evaluate expressions, and so on. 10050A line containing only the word <code>cont</code> finishes this function, 10051so that the caller continues its execution. 10052 10053 10054<p> 10055Note that commands for <code>debug.debug</code> are not lexically nested 10056within any function and so have no direct access to local variables. 10057 10058 10059 10060 10061<p> 10062<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3> 10063 10064 10065<p> 10066Returns the current hook settings of the thread, as three values: 10067the current hook function, the current hook mask, 10068and the current hook count 10069(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function). 10070 10071 10072 10073 10074<p> 10075<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3> 10076 10077 10078<p> 10079Returns a table with information about a function. 10080You can give the function directly 10081or you can give a number as the value of <code>f</code>, 10082which means the function running at level <code>f</code> of the call stack 10083of the given thread: 10084level 0 is the current function (<code>getinfo</code> itself); 10085level 1 is the function that called <code>getinfo</code> 10086(except for tail calls, which do not count on the stack); 10087and so on. 10088If <code>f</code> is a number larger than the number of active functions, 10089then <code>getinfo</code> returns <b>nil</b>. 10090 10091 10092<p> 10093The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>, 10094with the string <code>what</code> describing which fields to fill in. 10095The default for <code>what</code> is to get all information available, 10096except the table of valid lines. 10097If present, 10098the option '<code>f</code>' 10099adds a field named <code>func</code> with the function itself. 10100If present, 10101the option '<code>L</code>' 10102adds a field named <code>activelines</code> with the table of 10103valid lines. 10104 10105 10106<p> 10107For instance, the expression <code>debug.getinfo(1,"n").name</code> returns 10108a name for the current function, 10109if a reasonable name can be found, 10110and the expression <code>debug.getinfo(print)</code> 10111returns a table with all available information 10112about the <a href="#pdf-print"><code>print</code></a> function. 10113 10114 10115 10116 10117<p> 10118<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3> 10119 10120 10121<p> 10122This function returns the name and the value of the local variable 10123with index <code>local</code> of the function at level <code>f</code> of the stack. 10124This function accesses not only explicit local variables, 10125but also parameters, temporaries, etc. 10126 10127 10128<p> 10129The first parameter or local variable has index 1, and so on, 10130following the order that they are declared in the code, 10131counting only the variables that are active 10132in the current scope of the function. 10133Negative indices refer to vararg parameters; 10134-1 is the first vararg parameter. 10135The function returns <b>nil</b> if there is no variable with the given index, 10136and raises an error when called with a level out of range. 10137(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.) 10138 10139 10140<p> 10141Variable names starting with '<code>(</code>' (open parenthesis) 10142represent variables with no known names 10143(internal variables such as loop control variables, 10144and variables from chunks saved without debug information). 10145 10146 10147<p> 10148The parameter <code>f</code> may also be a function. 10149In that case, <code>getlocal</code> returns only the name of function parameters. 10150 10151 10152 10153 10154<p> 10155<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3> 10156 10157 10158<p> 10159Returns the metatable of the given <code>value</code> 10160or <b>nil</b> if it does not have a metatable. 10161 10162 10163 10164 10165<p> 10166<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3> 10167 10168 10169<p> 10170Returns the registry table (see <a href="#4.5">§4.5</a>). 10171 10172 10173 10174 10175<p> 10176<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3> 10177 10178 10179<p> 10180This function returns the name and the value of the upvalue 10181with index <code>up</code> of the function <code>f</code>. 10182The function returns <b>nil</b> if there is no upvalue with the given index. 10183 10184 10185<p> 10186Variable names starting with '<code>(</code>' (open parenthesis) 10187represent variables with no known names 10188(variables from chunks saved without debug information). 10189 10190 10191 10192 10193<p> 10194<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3> 10195 10196 10197<p> 10198Returns the Lua value associated to <code>u</code>. 10199If <code>u</code> is not a userdata, 10200returns <b>nil</b>. 10201 10202 10203 10204 10205<p> 10206<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3> 10207 10208 10209<p> 10210Sets the given function as a hook. 10211The string <code>mask</code> and the number <code>count</code> describe 10212when the hook will be called. 10213The string mask may have any combination of the following characters, 10214with the given meaning: 10215 10216<ul> 10217<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li> 10218<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li> 10219<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li> 10220</ul><p> 10221Moreover, 10222with a <code>count</code> different from zero, 10223the hook is called also after every <code>count</code> instructions. 10224 10225 10226<p> 10227When called without arguments, 10228<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook. 10229 10230 10231<p> 10232When the hook is called, its first parameter is a string 10233describing the event that has triggered its call: 10234<code>"call"</code> (or <code>"tail call"</code>), 10235<code>"return"</code>, 10236<code>"line"</code>, and <code>"count"</code>. 10237For line events, 10238the hook also gets the new line number as its second parameter. 10239Inside a hook, 10240you can call <code>getinfo</code> with level 2 to get more information about 10241the running function 10242(level 0 is the <code>getinfo</code> function, 10243and level 1 is the hook function). 10244 10245 10246 10247 10248<p> 10249<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3> 10250 10251 10252<p> 10253This function assigns the value <code>value</code> to the local variable 10254with index <code>local</code> of the function at level <code>level</code> of the stack. 10255The function returns <b>nil</b> if there is no local 10256variable with the given index, 10257and raises an error when called with a <code>level</code> out of range. 10258(You can call <code>getinfo</code> to check whether the level is valid.) 10259Otherwise, it returns the name of the local variable. 10260 10261 10262<p> 10263See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about 10264variable indices and names. 10265 10266 10267 10268 10269<p> 10270<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3> 10271 10272 10273<p> 10274Sets the metatable for the given <code>value</code> to the given <code>table</code> 10275(which can be <b>nil</b>). 10276Returns <code>value</code>. 10277 10278 10279 10280 10281<p> 10282<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3> 10283 10284 10285<p> 10286This function assigns the value <code>value</code> to the upvalue 10287with index <code>up</code> of the function <code>f</code>. 10288The function returns <b>nil</b> if there is no upvalue 10289with the given index. 10290Otherwise, it returns the name of the upvalue. 10291 10292 10293 10294 10295<p> 10296<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3> 10297 10298 10299<p> 10300Sets the given <code>value</code> as 10301the Lua value associated to the given <code>udata</code>. 10302<code>udata</code> must be a full userdata. 10303 10304 10305<p> 10306Returns <code>udata</code>. 10307 10308 10309 10310 10311<p> 10312<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3> 10313 10314 10315<p> 10316If <code>message</code> is present but is neither a string nor <b>nil</b>, 10317this function returns <code>message</code> without further processing. 10318Otherwise, 10319it returns a string with a traceback of the call stack. 10320The optional <code>message</code> string is appended 10321at the beginning of the traceback. 10322An optional <code>level</code> number tells at which level 10323to start the traceback 10324(default is 1, the function calling <code>traceback</code>). 10325 10326 10327 10328 10329<p> 10330<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3> 10331 10332 10333<p> 10334Returns a unique identifier (as a light userdata) 10335for the upvalue numbered <code>n</code> 10336from the given function. 10337 10338 10339<p> 10340These unique identifiers allow a program to check whether different 10341closures share upvalues. 10342Lua closures that share an upvalue 10343(that is, that access a same external local variable) 10344will return identical ids for those upvalue indices. 10345 10346 10347 10348 10349<p> 10350<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3> 10351 10352 10353<p> 10354Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code> 10355refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>. 10356 10357 10358 10359 10360 10361 10362 10363<h1>7 – <a name="7">Lua Standalone</a></h1> 10364 10365<p> 10366Although Lua has been designed as an extension language, 10367to be embedded in a host C program, 10368it is also frequently used as a standalone language. 10369An interpreter for Lua as a standalone language, 10370called simply <code>lua</code>, 10371is provided with the standard distribution. 10372The standalone interpreter includes 10373all standard libraries, including the debug library. 10374Its usage is: 10375 10376<pre> 10377 lua [options] [script [args]] 10378</pre><p> 10379The options are: 10380 10381<ul> 10382<li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li> 10383<li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em>;</li> 10384<li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li> 10385<li><b><code>-v</code>: </b> prints version information;</li> 10386<li><b><code>-E</code>: </b> ignores environment variables;</li> 10387<li><b><code>--</code>: </b> stops handling options;</li> 10388<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li> 10389</ul><p> 10390After handling its options, <code>lua</code> runs the given <em>script</em>. 10391When called without arguments, 10392<code>lua</code> behaves as <code>lua -v -i</code> 10393when the standard input (<code>stdin</code>) is a terminal, 10394and as <code>lua -</code> otherwise. 10395 10396 10397<p> 10398When called without option <code>-E</code>, 10399the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a> 10400(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined) 10401before running any argument. 10402If the variable content has the format <code>@<em>filename</em></code>, 10403then <code>lua</code> executes the file. 10404Otherwise, <code>lua</code> executes the string itself. 10405 10406 10407<p> 10408When called with option <code>-E</code>, 10409besides ignoring <code>LUA_INIT</code>, 10410Lua also ignores 10411the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>, 10412setting the values of 10413<a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a> 10414with the default paths defined in <code>luaconf.h</code>. 10415 10416 10417<p> 10418All options are handled in order, except <code>-i</code> and <code>-E</code>. 10419For instance, an invocation like 10420 10421<pre> 10422 $ lua -e'a=1' -e 'print(a)' script.lua 10423</pre><p> 10424will first set <code>a</code> to 1, then print the value of <code>a</code>, 10425and finally run the file <code>script.lua</code> with no arguments. 10426(Here <code>$</code> is the shell prompt. Your prompt may be different.) 10427 10428 10429<p> 10430Before running any code, 10431<code>lua</code> collects all command-line arguments 10432in a global table called <code>arg</code>. 10433The script name goes to index 0, 10434the first argument after the script name goes to index 1, 10435and so on. 10436Any arguments before the script name 10437(that is, the interpreter name plus its options) 10438go to negative indices. 10439For instance, in the call 10440 10441<pre> 10442 $ lua -la b.lua t1 t2 10443</pre><p> 10444the table is like this: 10445 10446<pre> 10447 arg = { [-2] = "lua", [-1] = "-la", 10448 [0] = "b.lua", 10449 [1] = "t1", [2] = "t2" } 10450</pre><p> 10451If there is no script in the call, 10452the interpreter name goes to index 0, 10453followed by the other arguments. 10454For instance, the call 10455 10456<pre> 10457 $ lua -e "print(arg[1])" 10458</pre><p> 10459will print "<code>-e</code>". 10460If there is a script, 10461the script is called with parameters 10462<code>arg[1]</code>, ···, <code>arg[#arg]</code>. 10463(Like all chunks in Lua, 10464the script is compiled as a vararg function.) 10465 10466 10467<p> 10468In interactive mode, 10469Lua repeatedly prompts and waits for a line. 10470After reading a line, 10471Lua first try to interpret the line as an expression. 10472If it succeeds, it prints its value. 10473Otherwise, it interprets the line as a statement. 10474If you write an incomplete statement, 10475the interpreter waits for its completion 10476by issuing a different prompt. 10477 10478 10479<p> 10480In case of unprotected errors in the script, 10481the interpreter reports the error to the standard error stream. 10482If the error object is not a string but 10483has a metamethod <code>__tostring</code>, 10484the interpreter calls this metamethod to produce the final message. 10485Otherwise, the interpreter converts the error object to a string 10486and adds a stack traceback to it. 10487 10488 10489<p> 10490When finishing normally, 10491the interpreter closes its main Lua state 10492(see <a href="#lua_close"><code>lua_close</code></a>). 10493The script can avoid this step by 10494calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate. 10495 10496 10497<p> 10498To allow the use of Lua as a 10499script interpreter in Unix systems, 10500the standalone interpreter skips 10501the first line of a chunk if it starts with <code>#</code>. 10502Therefore, Lua scripts can be made into executable programs 10503by using <code>chmod +x</code> and the <code>#!</code> form, 10504as in 10505 10506<pre> 10507 #!/usr/local/bin/lua 10508</pre><p> 10509(Of course, 10510the location of the Lua interpreter may be different in your machine. 10511If <code>lua</code> is in your <code>PATH</code>, 10512then 10513 10514<pre> 10515 #!/usr/bin/env lua 10516</pre><p> 10517is a more portable solution.) 10518 10519 10520 10521<h1>8 – <a name="8">Incompatibilities with the Previous Version</a></h1> 10522 10523<p> 10524Here we list the incompatibilities that you may find when moving a program 10525from Lua 5.2 to Lua 5.3. 10526You can avoid some incompatibilities by compiling Lua with 10527appropriate options (see file <code>luaconf.h</code>). 10528However, 10529all these compatibility options will be removed in the future. 10530 10531 10532<p> 10533Lua versions can always change the C API in ways that 10534do not imply source-code changes in a program, 10535such as the numeric values for constants 10536or the implementation of functions as macros. 10537Therefore, 10538you should not assume that binaries are compatible between 10539different Lua versions. 10540Always recompile clients of the Lua API when 10541using a new version. 10542 10543 10544<p> 10545Similarly, Lua versions can always change the internal representation 10546of precompiled chunks; 10547precompiled chunks are not compatible between different Lua versions. 10548 10549 10550<p> 10551The standard paths in the official distribution may 10552change between versions. 10553 10554 10555 10556<h2>8.1 – <a name="8.1">Changes in the Language</a></h2> 10557<ul> 10558 10559<li> 10560The main difference between Lua 5.2 and Lua 5.3 is the 10561introduction of an integer subtype for numbers. 10562Although this change should not affect "normal" computations, 10563some computations 10564(mainly those that involve some kind of overflow) 10565can give different results. 10566 10567 10568<p> 10569You can fix these differences by forcing a number to be a float 10570(in Lua 5.2 all numbers were float), 10571in particular writing constants with an ending <code>.0</code> 10572or using <code>x = x + 0.0</code> to convert a variable. 10573(This recommendation is only for a quick fix 10574for an occasional incompatibility; 10575it is not a general guideline for good programming. 10576For good programming, 10577use floats where you need floats 10578and integers where you need integers.) 10579</li> 10580 10581<li> 10582The conversion of a float to a string now adds a <code>.0</code> suffix 10583to the result if it looks like an integer. 10584(For instance, the float 2.0 will be printed as <code>2.0</code>, 10585not as <code>2</code>.) 10586You should always use an explicit format 10587when you need a specific format for numbers. 10588 10589 10590<p> 10591(Formally this is not an incompatibility, 10592because Lua does not specify how numbers are formatted as strings, 10593but some programs assumed a specific format.) 10594</li> 10595 10596<li> 10597The generational mode for the garbage collector was removed. 10598(It was an experimental feature in Lua 5.2.) 10599</li> 10600 10601</ul> 10602 10603 10604 10605 10606<h2>8.2 – <a name="8.2">Changes in the Libraries</a></h2> 10607<ul> 10608 10609<li> 10610The <code>bit32</code> library has been deprecated. 10611It is easy to require a compatible external library or, 10612better yet, to replace its functions with appropriate bitwise operations. 10613(Keep in mind that <code>bit32</code> operates on 32-bit integers, 10614while the bitwise operators in Lua 5.3 operate on Lua integers, 10615which by default have 64 bits.) 10616</li> 10617 10618<li> 10619The Table library now respects metamethods 10620for setting and getting elements. 10621</li> 10622 10623<li> 10624The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and 10625its <code>__ipairs</code> metamethod has been deprecated. 10626</li> 10627 10628<li> 10629Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore. 10630For compatibility, Lua will continue to accept (and ignore) this character. 10631</li> 10632 10633<li> 10634The following functions were deprecated in the mathematical library: 10635<code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>, 10636<code>frexp</code>, and <code>ldexp</code>. 10637You can replace <code>math.pow(x,y)</code> with <code>x^y</code>; 10638you can replace <code>math.atan2</code> with <code>math.atan</code>, 10639which now accepts one or two parameters; 10640you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>. 10641For the other operations, 10642you can either use an external library or 10643implement them in Lua. 10644</li> 10645 10646<li> 10647The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a> 10648changed the way it handles versioned names. 10649Now, the version should come after the module name 10650(as is usual in most other tools). 10651For compatibility, that searcher still tries the old format 10652if it cannot find an open function according to the new style. 10653(Lua 5.2 already worked that way, 10654but it did not document the change.) 10655</li> 10656 10657<li> 10658The call <code>collectgarbage("count")</code> now returns only one result. 10659(You can compute that second result from the fractional part 10660of the first result.) 10661</li> 10662 10663</ul> 10664 10665 10666 10667 10668<h2>8.3 – <a name="8.3">Changes in the API</a></h2> 10669 10670 10671<ul> 10672 10673<li> 10674Continuation functions now receive as parameters what they needed 10675to get through <code>lua_getctx</code>, 10676so <code>lua_getctx</code> has been removed. 10677Adapt your code accordingly. 10678</li> 10679 10680<li> 10681Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>. 10682Use 0 as the value of this parameter to get the old behavior. 10683</li> 10684 10685<li> 10686Functions to inject/project unsigned integers 10687(<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>, 10688<code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>) 10689were deprecated. 10690Use their signed equivalents with a type cast. 10691</li> 10692 10693<li> 10694Macros to project non-default integer types 10695(<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>) 10696were deprecated. 10697Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast 10698(or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code). 10699</li> 10700 10701</ul> 10702 10703 10704 10705 10706<h1>9 – <a name="9">The Complete Syntax of Lua</a></h1> 10707 10708<p> 10709Here is the complete syntax of Lua in extended BNF. 10710As usual in extended BNF, 10711{A} means 0 or more As, 10712and [A] means an optional A. 10713(For operator precedences, see <a href="#3.4.8">§3.4.8</a>; 10714for a description of the terminals 10715Name, Numeral, 10716and LiteralString, see <a href="#3.1">§3.1</a>.) 10717 10718 10719 10720 10721<pre> 10722 10723 chunk ::= block 10724 10725 block ::= {stat} [retstat] 10726 10727 stat ::= ‘<b>;</b>’ | 10728 varlist ‘<b>=</b>’ explist | 10729 functioncall | 10730 label | 10731 <b>break</b> | 10732 <b>goto</b> Name | 10733 <b>do</b> block <b>end</b> | 10734 <b>while</b> exp <b>do</b> block <b>end</b> | 10735 <b>repeat</b> block <b>until</b> exp | 10736 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 10737 <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b> | 10738 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> | 10739 <b>function</b> funcname funcbody | 10740 <b>local</b> <b>function</b> Name funcbody | 10741 <b>local</b> namelist [‘<b>=</b>’ explist] 10742 10743 retstat ::= <b>return</b> [explist] [‘<b>;</b>’] 10744 10745 label ::= ‘<b>::</b>’ Name ‘<b>::</b>’ 10746 10747 funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name] 10748 10749 varlist ::= var {‘<b>,</b>’ var} 10750 10751 var ::= Name | prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ | prefixexp ‘<b>.</b>’ Name 10752 10753 namelist ::= Name {‘<b>,</b>’ Name} 10754 10755 explist ::= exp {‘<b>,</b>’ exp} 10756 10757 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | ‘<b>...</b>’ | functiondef | 10758 prefixexp | tableconstructor | exp binop exp | unop exp 10759 10760 prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’ 10761 10762 functioncall ::= prefixexp args | prefixexp ‘<b>:</b>’ Name args 10763 10764 args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ | tableconstructor | LiteralString 10765 10766 functiondef ::= <b>function</b> funcbody 10767 10768 funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b> 10769 10770 parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’ 10771 10772 tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’ 10773 10774 fieldlist ::= field {fieldsep field} [fieldsep] 10775 10776 field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp 10777 10778 fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’ 10779 10780 binop ::= ‘<b>+</b>’ | ‘<b>-</b>’ | ‘<b>*</b>’ | ‘<b>/</b>’ | ‘<b>//</b>’ | ‘<b>^</b>’ | ‘<b>%</b>’ | 10781 ‘<b>&</b>’ | ‘<b>~</b>’ | ‘<b>|</b>’ | ‘<b>>></b>’ | ‘<b><<</b>’ | ‘<b>..</b>’ | 10782 ‘<b><</b>’ | ‘<b><=</b>’ | ‘<b>></b>’ | ‘<b>>=</b>’ | ‘<b>==</b>’ | ‘<b>~=</b>’ | 10783 <b>and</b> | <b>or</b> 10784 10785 unop ::= ‘<b>-</b>’ | <b>not</b> | ‘<b>#</b>’ | ‘<b>~</b>’ 10786 10787</pre> 10788 10789<p> 10790 10791 10792 10793 10794 10795 10796 10797 10798<P CLASS="footer"> 10799Last update: 10800Wed Jun 10 18:31:15 BRT 2015 10801</P> 10802<!-- 10803Last change: revised for Lua 5.3.1 10804--> 10805 10806</body></html> 10807 10808