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.153 2015/11/25 16:57:42 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 should 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 and 1055not being a reserved word. 1056Identifiers are used to name variables, table fields, and labels. 1057 1058 1059<p> 1060The following <em>keywords</em> are reserved 1061and cannot be used as names: 1062 1063 1064<pre> 1065 and break do else elseif end 1066 false for function goto if in 1067 local nil not or repeat return 1068 then true until while 1069</pre> 1070 1071<p> 1072Lua is a case-sensitive language: 1073<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code> 1074are two different, valid names. 1075As a convention, 1076programs should avoid creating 1077names that start with an underscore followed by 1078one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>). 1079 1080 1081<p> 1082The following strings denote other tokens: 1083 1084<pre> 1085 + - * / % ^ # 1086 & ~ | << >> // 1087 == ~= <= >= < > = 1088 ( ) { } [ ] :: 1089 ; : , . .. ... 1090</pre> 1091 1092<p> 1093<em>Literal strings</em> 1094can be delimited by matching single or double quotes, 1095and can contain the following C-like escape sequences: 1096'<code>\a</code>' (bell), 1097'<code>\b</code>' (backspace), 1098'<code>\f</code>' (form feed), 1099'<code>\n</code>' (newline), 1100'<code>\r</code>' (carriage return), 1101'<code>\t</code>' (horizontal tab), 1102'<code>\v</code>' (vertical tab), 1103'<code>\\</code>' (backslash), 1104'<code>\"</code>' (quotation mark [double quote]), 1105and '<code>\'</code>' (apostrophe [single quote]). 1106A backslash followed by a real newline 1107results in a newline in the string. 1108The escape sequence '<code>\z</code>' skips the following span 1109of white-space characters, 1110including line breaks; 1111it is particularly useful to break and indent a long literal string 1112into multiple lines without adding the newlines and spaces 1113into the string contents. 1114 1115 1116<p> 1117Strings in Lua can contain any 8-bit value, including embedded zeros, 1118which can be specified as '<code>\0</code>'. 1119More generally, 1120we can specify any byte in a literal string by its numeric value. 1121This can be done 1122with the escape sequence <code>\x<em>XX</em></code>, 1123where <em>XX</em> is a sequence of exactly two hexadecimal digits, 1124or with the escape sequence <code>\<em>ddd</em></code>, 1125where <em>ddd</em> is a sequence of up to three decimal digits. 1126(Note that if a decimal escape sequence is to be followed by a digit, 1127it must be expressed using exactly three digits.) 1128 1129 1130<p> 1131The UTF-8 encoding of a Unicode character 1132can be inserted in a literal string with 1133the escape sequence <code>\u{<em>XXX</em>}</code> 1134(note the mandatory enclosing brackets), 1135where <em>XXX</em> is a sequence of one or more hexadecimal digits 1136representing the character code point. 1137 1138 1139<p> 1140Literal strings can also be defined using a long format 1141enclosed by <em>long brackets</em>. 1142We define an <em>opening long bracket of level <em>n</em></em> as an opening 1143square bracket followed by <em>n</em> equal signs followed by another 1144opening square bracket. 1145So, an opening long bracket of level 0 is written as <code>[[</code>, 1146an opening long bracket of level 1 is written as <code>[=[</code>, 1147and so on. 1148A <em>closing long bracket</em> is defined similarly; 1149for instance, 1150a closing long bracket of level 4 is written as <code>]====]</code>. 1151A <em>long literal</em> starts with an opening long bracket of any level and 1152ends at the first closing long bracket of the same level. 1153It can contain any text except a closing bracket of the same level. 1154Literals in this bracketed form can run for several lines, 1155do not interpret any escape sequences, 1156and ignore long brackets of any other level. 1157Any kind of end-of-line sequence 1158(carriage return, newline, carriage return followed by newline, 1159or newline followed by carriage return) 1160is converted to a simple newline. 1161 1162 1163<p> 1164Any byte in a literal string not 1165explicitly affected by the previous rules represents itself. 1166However, Lua opens files for parsing in text mode, 1167and the system file functions may have problems with 1168some control characters. 1169So, it is safer to represent 1170non-text data as a quoted literal with 1171explicit escape sequences for non-text characters. 1172 1173 1174<p> 1175For convenience, 1176when the opening long bracket is immediately followed by a newline, 1177the newline is not included in the string. 1178As an example, in a system using ASCII 1179(in which '<code>a</code>' is coded as 97, 1180newline is coded as 10, and '<code>1</code>' is coded as 49), 1181the five literal strings below denote the same string: 1182 1183<pre> 1184 a = 'alo\n123"' 1185 a = "alo\n123\"" 1186 a = '\97lo\10\04923"' 1187 a = [[alo 1188 123"]] 1189 a = [==[ 1190 alo 1191 123"]==] 1192</pre> 1193 1194<p> 1195A <em>numeric constant</em> (or <em>numeral</em>) 1196can be written with an optional fractional part 1197and an optional decimal exponent, 1198marked by a letter '<code>e</code>' or '<code>E</code>'. 1199Lua also accepts hexadecimal constants, 1200which start with <code>0x</code> or <code>0X</code>. 1201Hexadecimal constants also accept an optional fractional part 1202plus an optional binary exponent, 1203marked by a letter '<code>p</code>' or '<code>P</code>'. 1204A numeric constant with a fractional dot or an exponent 1205denotes a float; 1206otherwise it denotes an integer. 1207Examples of valid integer constants are 1208 1209<pre> 1210 3 345 0xff 0xBEBADA 1211</pre><p> 1212Examples of valid float constants are 1213 1214<pre> 1215 3.0 3.1416 314.16e-2 0.31416E1 34e1 1216 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 1217</pre> 1218 1219<p> 1220A <em>comment</em> starts with a double hyphen (<code>--</code>) 1221anywhere outside a string. 1222If the text immediately after <code>--</code> is not an opening long bracket, 1223the comment is a <em>short comment</em>, 1224which runs until the end of the line. 1225Otherwise, it is a <em>long comment</em>, 1226which runs until the corresponding closing long bracket. 1227Long comments are frequently used to disable code temporarily. 1228 1229 1230 1231 1232 1233<h2>3.2 – <a name="3.2">Variables</a></h2> 1234 1235<p> 1236Variables are places that store values. 1237There are three kinds of variables in Lua: 1238global variables, local variables, and table fields. 1239 1240 1241<p> 1242A single name can denote a global variable or a local variable 1243(or a function's formal parameter, 1244which is a particular kind of local variable): 1245 1246<pre> 1247 var ::= Name 1248</pre><p> 1249Name denotes identifiers, as defined in <a href="#3.1">§3.1</a>. 1250 1251 1252<p> 1253Any variable name is assumed to be global unless explicitly declared 1254as a local (see <a href="#3.3.7">§3.3.7</a>). 1255Local variables are <em>lexically scoped</em>: 1256local variables can be freely accessed by functions 1257defined inside their scope (see <a href="#3.5">§3.5</a>). 1258 1259 1260<p> 1261Before the first assignment to a variable, its value is <b>nil</b>. 1262 1263 1264<p> 1265Square brackets are used to index a table: 1266 1267<pre> 1268 var ::= prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ 1269</pre><p> 1270The meaning of accesses to table fields can be changed via metatables. 1271An access to an indexed variable <code>t[i]</code> is equivalent to 1272a call <code>gettable_event(t,i)</code>. 1273(See <a href="#2.4">§2.4</a> for a complete description of the 1274<code>gettable_event</code> function. 1275This function is not defined or callable in Lua. 1276We use it here only for explanatory purposes.) 1277 1278 1279<p> 1280The syntax <code>var.Name</code> is just syntactic sugar for 1281<code>var["Name"]</code>: 1282 1283<pre> 1284 var ::= prefixexp ‘<b>.</b>’ Name 1285</pre> 1286 1287<p> 1288An access to a global variable <code>x</code> 1289is equivalent to <code>_ENV.x</code>. 1290Due to the way that chunks are compiled, 1291<code>_ENV</code> is never a global name (see <a href="#2.2">§2.2</a>). 1292 1293 1294 1295 1296 1297<h2>3.3 – <a name="3.3">Statements</a></h2> 1298 1299<p> 1300Lua supports an almost conventional set of statements, 1301similar to those in Pascal or C. 1302This set includes 1303assignments, control structures, function calls, 1304and variable declarations. 1305 1306 1307 1308<h3>3.3.1 – <a name="3.3.1">Blocks</a></h3> 1309 1310<p> 1311A block is a list of statements, 1312which are executed sequentially: 1313 1314<pre> 1315 block ::= {stat} 1316</pre><p> 1317Lua has <em>empty statements</em> 1318that allow you to separate statements with semicolons, 1319start a block with a semicolon 1320or write two semicolons in sequence: 1321 1322<pre> 1323 stat ::= ‘<b>;</b>’ 1324</pre> 1325 1326<p> 1327Function calls and assignments 1328can start with an open parenthesis. 1329This possibility leads to an ambiguity in Lua's grammar. 1330Consider the following fragment: 1331 1332<pre> 1333 a = b + c 1334 (print or io.write)('done') 1335</pre><p> 1336The grammar could see it in two ways: 1337 1338<pre> 1339 a = b + c(print or io.write)('done') 1340 1341 a = b + c; (print or io.write)('done') 1342</pre><p> 1343The current parser always sees such constructions 1344in the first way, 1345interpreting the open parenthesis 1346as the start of the arguments to a call. 1347To avoid this ambiguity, 1348it is a good practice to always precede with a semicolon 1349statements that start with a parenthesis: 1350 1351<pre> 1352 ;(print or io.write)('done') 1353</pre> 1354 1355<p> 1356A block can be explicitly delimited to produce a single statement: 1357 1358<pre> 1359 stat ::= <b>do</b> block <b>end</b> 1360</pre><p> 1361Explicit blocks are useful 1362to control the scope of variable declarations. 1363Explicit blocks are also sometimes used to 1364add a <b>return</b> statement in the middle 1365of another block (see <a href="#3.3.4">§3.3.4</a>). 1366 1367 1368 1369 1370 1371<h3>3.3.2 – <a name="3.3.2">Chunks</a></h3> 1372 1373<p> 1374The unit of compilation of Lua is called a <em>chunk</em>. 1375Syntactically, 1376a chunk is simply a block: 1377 1378<pre> 1379 chunk ::= block 1380</pre> 1381 1382<p> 1383Lua handles a chunk as the body of an anonymous function 1384with a variable number of arguments 1385(see <a href="#3.4.11">§3.4.11</a>). 1386As such, chunks can define local variables, 1387receive arguments, and return values. 1388Moreover, such anonymous function is compiled as in the 1389scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">§2.2</a>). 1390The resulting function always has <code>_ENV</code> as its only upvalue, 1391even if it does not use that variable. 1392 1393 1394<p> 1395A chunk can be stored in a file or in a string inside the host program. 1396To execute a chunk, 1397Lua first <em>loads</em> it, 1398precompiling the chunk's code into instructions for a virtual machine, 1399and then Lua executes the compiled code 1400with an interpreter for the virtual machine. 1401 1402 1403<p> 1404Chunks can also be precompiled into binary form; 1405see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details. 1406Programs in source and compiled forms are interchangeable; 1407Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>). 1408 1409 1410 1411 1412 1413<h3>3.3.3 – <a name="3.3.3">Assignment</a></h3> 1414 1415<p> 1416Lua allows multiple assignments. 1417Therefore, the syntax for assignment 1418defines a list of variables on the left side 1419and a list of expressions on the right side. 1420The elements in both lists are separated by commas: 1421 1422<pre> 1423 stat ::= varlist ‘<b>=</b>’ explist 1424 varlist ::= var {‘<b>,</b>’ var} 1425 explist ::= exp {‘<b>,</b>’ exp} 1426</pre><p> 1427Expressions are discussed in <a href="#3.4">§3.4</a>. 1428 1429 1430<p> 1431Before the assignment, 1432the list of values is <em>adjusted</em> to the length of 1433the list of variables. 1434If there are more values than needed, 1435the excess values are thrown away. 1436If there are fewer values than needed, 1437the list is extended with as many <b>nil</b>'s as needed. 1438If the list of expressions ends with a function call, 1439then all values returned by that call enter the list of values, 1440before the adjustment 1441(except when the call is enclosed in parentheses; see <a href="#3.4">§3.4</a>). 1442 1443 1444<p> 1445The assignment statement first evaluates all its expressions 1446and only then the assignments are performed. 1447Thus the code 1448 1449<pre> 1450 i = 3 1451 i, a[i] = i+1, 20 1452</pre><p> 1453sets <code>a[3]</code> to 20, without affecting <code>a[4]</code> 1454because the <code>i</code> in <code>a[i]</code> is evaluated (to 3) 1455before it is assigned 4. 1456Similarly, the line 1457 1458<pre> 1459 x, y = y, x 1460</pre><p> 1461exchanges the values of <code>x</code> and <code>y</code>, 1462and 1463 1464<pre> 1465 x, y, z = y, z, x 1466</pre><p> 1467cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>. 1468 1469 1470<p> 1471The meaning of assignments to global variables 1472and table fields can be changed via metatables. 1473An assignment to an indexed variable <code>t[i] = val</code> is equivalent to 1474<code>settable_event(t,i,val)</code>. 1475(See <a href="#2.4">§2.4</a> for a complete description of the 1476<code>settable_event</code> function. 1477This function is not defined or callable in Lua. 1478We use it here only for explanatory purposes.) 1479 1480 1481<p> 1482An assignment to a global name <code>x = val</code> 1483is equivalent to the assignment 1484<code>_ENV.x = val</code> (see <a href="#2.2">§2.2</a>). 1485 1486 1487 1488 1489 1490<h3>3.3.4 – <a name="3.3.4">Control Structures</a></h3><p> 1491The control structures 1492<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and 1493familiar syntax: 1494 1495 1496 1497 1498<pre> 1499 stat ::= <b>while</b> exp <b>do</b> block <b>end</b> 1500 stat ::= <b>repeat</b> block <b>until</b> exp 1501 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> 1502</pre><p> 1503Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">§3.3.5</a>). 1504 1505 1506<p> 1507The condition expression of a 1508control structure can return any value. 1509Both <b>false</b> and <b>nil</b> are considered false. 1510All values different from <b>nil</b> and <b>false</b> are considered true 1511(in particular, the number 0 and the empty string are also true). 1512 1513 1514<p> 1515In the <b>repeat</b>–<b>until</b> loop, 1516the inner block does not end at the <b>until</b> keyword, 1517but only after the condition. 1518So, the condition can refer to local variables 1519declared inside the loop block. 1520 1521 1522<p> 1523The <b>goto</b> statement transfers the program control to a label. 1524For syntactical reasons, 1525labels in Lua are considered statements too: 1526 1527 1528 1529<pre> 1530 stat ::= <b>goto</b> Name 1531 stat ::= label 1532 label ::= ‘<b>::</b>’ Name ‘<b>::</b>’ 1533</pre> 1534 1535<p> 1536A label is visible in the entire block where it is defined, 1537except 1538inside nested blocks where a label with the same name is defined and 1539inside nested functions. 1540A goto may jump to any visible label as long as it does not 1541enter into the scope of a local variable. 1542 1543 1544<p> 1545Labels and empty statements are called <em>void statements</em>, 1546as they perform no actions. 1547 1548 1549<p> 1550The <b>break</b> statement terminates the execution of a 1551<b>while</b>, <b>repeat</b>, or <b>for</b> loop, 1552skipping to the next statement after the loop: 1553 1554 1555<pre> 1556 stat ::= <b>break</b> 1557</pre><p> 1558A <b>break</b> ends the innermost enclosing loop. 1559 1560 1561<p> 1562The <b>return</b> statement is used to return values 1563from a function or a chunk 1564(which is an anonymous function). 1565 1566Functions can return more than one value, 1567so the syntax for the <b>return</b> statement is 1568 1569<pre> 1570 stat ::= <b>return</b> [explist] [‘<b>;</b>’] 1571</pre> 1572 1573<p> 1574The <b>return</b> statement can only be written 1575as the last statement of a block. 1576If it is really necessary to <b>return</b> in the middle of a block, 1577then an explicit inner block can be used, 1578as in the idiom <code>do return end</code>, 1579because now <b>return</b> is the last statement in its (inner) block. 1580 1581 1582 1583 1584 1585<h3>3.3.5 – <a name="3.3.5">For Statement</a></h3> 1586 1587<p> 1588 1589The <b>for</b> statement has two forms: 1590one numerical and one generic. 1591 1592 1593<p> 1594The numerical <b>for</b> loop repeats a block of code while a 1595control variable runs through an arithmetic progression. 1596It has the following syntax: 1597 1598<pre> 1599 stat ::= <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b> 1600</pre><p> 1601The <em>block</em> is repeated for <em>name</em> starting at the value of 1602the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the 1603third <em>exp</em>. 1604More precisely, a <b>for</b> statement like 1605 1606<pre> 1607 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end 1608</pre><p> 1609is equivalent to the code: 1610 1611<pre> 1612 do 1613 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>) 1614 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end 1615 <em>var</em> = <em>var</em> - <em>step</em> 1616 while true do 1617 <em>var</em> = <em>var</em> + <em>step</em> 1618 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 1619 break 1620 end 1621 local v = <em>var</em> 1622 <em>block</em> 1623 end 1624 end 1625</pre> 1626 1627<p> 1628Note the following: 1629 1630<ul> 1631 1632<li> 1633All three control expressions are evaluated only once, 1634before the loop starts. 1635They must all result in numbers. 1636</li> 1637 1638<li> 1639<code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables. 1640The names shown here are for explanatory purposes only. 1641</li> 1642 1643<li> 1644If the third expression (the step) is absent, 1645then a step of 1 is used. 1646</li> 1647 1648<li> 1649You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop. 1650</li> 1651 1652<li> 1653The loop variable <code>v</code> is local to the loop body. 1654If you need its value after the loop, 1655assign it to another variable before exiting the loop. 1656</li> 1657 1658</ul> 1659 1660<p> 1661The generic <b>for</b> statement works over functions, 1662called <em>iterators</em>. 1663On each iteration, the iterator function is called to produce a new value, 1664stopping when this new value is <b>nil</b>. 1665The generic <b>for</b> loop has the following syntax: 1666 1667<pre> 1668 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> 1669 namelist ::= Name {‘<b>,</b>’ Name} 1670</pre><p> 1671A <b>for</b> statement like 1672 1673<pre> 1674 for <em>var_1</em>, ···, <em>var_n</em> in <em>explist</em> do <em>block</em> end 1675</pre><p> 1676is equivalent to the code: 1677 1678<pre> 1679 do 1680 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em> 1681 while true do 1682 local <em>var_1</em>, ···, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>) 1683 if <em>var_1</em> == nil then break end 1684 <em>var</em> = <em>var_1</em> 1685 <em>block</em> 1686 end 1687 end 1688</pre><p> 1689Note the following: 1690 1691<ul> 1692 1693<li> 1694<code><em>explist</em></code> is evaluated only once. 1695Its results are an <em>iterator</em> function, 1696a <em>state</em>, 1697and an initial value for the first <em>iterator variable</em>. 1698</li> 1699 1700<li> 1701<code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables. 1702The names are here for explanatory purposes only. 1703</li> 1704 1705<li> 1706You can use <b>break</b> to exit a <b>for</b> loop. 1707</li> 1708 1709<li> 1710The loop variables <code><em>var_i</em></code> are local to the loop; 1711you cannot use their values after the <b>for</b> ends. 1712If you need these values, 1713then assign them to other variables before breaking or exiting the loop. 1714</li> 1715 1716</ul> 1717 1718 1719 1720 1721<h3>3.3.6 – <a name="3.3.6">Function Calls as Statements</a></h3><p> 1722To allow possible side-effects, 1723function calls can be executed as statements: 1724 1725<pre> 1726 stat ::= functioncall 1727</pre><p> 1728In this case, all returned values are thrown away. 1729Function calls are explained in <a href="#3.4.10">§3.4.10</a>. 1730 1731 1732 1733 1734 1735<h3>3.3.7 – <a name="3.3.7">Local Declarations</a></h3><p> 1736Local variables can be declared anywhere inside a block. 1737The declaration can include an initial assignment: 1738 1739<pre> 1740 stat ::= <b>local</b> namelist [‘<b>=</b>’ explist] 1741</pre><p> 1742If present, an initial assignment has the same semantics 1743of a multiple assignment (see <a href="#3.3.3">§3.3.3</a>). 1744Otherwise, all variables are initialized with <b>nil</b>. 1745 1746 1747<p> 1748A chunk is also a block (see <a href="#3.3.2">§3.3.2</a>), 1749and so local variables can be declared in a chunk outside any explicit block. 1750 1751 1752<p> 1753The visibility rules for local variables are explained in <a href="#3.5">§3.5</a>. 1754 1755 1756 1757 1758 1759 1760 1761<h2>3.4 – <a name="3.4">Expressions</a></h2> 1762 1763<p> 1764The basic expressions in Lua are the following: 1765 1766<pre> 1767 exp ::= prefixexp 1768 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> 1769 exp ::= Numeral 1770 exp ::= LiteralString 1771 exp ::= functiondef 1772 exp ::= tableconstructor 1773 exp ::= ‘<b>...</b>’ 1774 exp ::= exp binop exp 1775 exp ::= unop exp 1776 prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’ 1777</pre> 1778 1779<p> 1780Numerals and literal strings are explained in <a href="#3.1">§3.1</a>; 1781variables are explained in <a href="#3.2">§3.2</a>; 1782function definitions are explained in <a href="#3.4.11">§3.4.11</a>; 1783function calls are explained in <a href="#3.4.10">§3.4.10</a>; 1784table constructors are explained in <a href="#3.4.9">§3.4.9</a>. 1785Vararg expressions, 1786denoted by three dots ('<code>...</code>'), can only be used when 1787directly inside a vararg function; 1788they are explained in <a href="#3.4.11">§3.4.11</a>. 1789 1790 1791<p> 1792Binary operators comprise arithmetic operators (see <a href="#3.4.1">§3.4.1</a>), 1793bitwise operators (see <a href="#3.4.2">§3.4.2</a>), 1794relational operators (see <a href="#3.4.4">§3.4.4</a>), logical operators (see <a href="#3.4.5">§3.4.5</a>), 1795and the concatenation operator (see <a href="#3.4.6">§3.4.6</a>). 1796Unary operators comprise the unary minus (see <a href="#3.4.1">§3.4.1</a>), 1797the unary bitwise not (see <a href="#3.4.2">§3.4.2</a>), 1798the unary logical <b>not</b> (see <a href="#3.4.5">§3.4.5</a>), 1799and the unary <em>length operator</em> (see <a href="#3.4.7">§3.4.7</a>). 1800 1801 1802<p> 1803Both function calls and vararg expressions can result in multiple values. 1804If a function call is used as a statement (see <a href="#3.3.6">§3.3.6</a>), 1805then its return list is adjusted to zero elements, 1806thus discarding all returned values. 1807If an expression is used as the last (or the only) element 1808of a list of expressions, 1809then no adjustment is made 1810(unless the expression is enclosed in parentheses). 1811In all other contexts, 1812Lua adjusts the result list to one element, 1813either discarding all values except the first one 1814or adding a single <b>nil</b> if there are no values. 1815 1816 1817<p> 1818Here are some examples: 1819 1820<pre> 1821 f() -- adjusted to 0 results 1822 g(f(), x) -- f() is adjusted to 1 result 1823 g(x, f()) -- g gets x plus all results from f() 1824 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) 1825 a,b = ... -- a gets the first vararg parameter, b gets 1826 -- the second (both a and b can get nil if there 1827 -- is no corresponding vararg parameter) 1828 1829 a,b,c = x, f() -- f() is adjusted to 2 results 1830 a,b,c = f() -- f() is adjusted to 3 results 1831 return f() -- returns all results from f() 1832 return ... -- returns all received vararg parameters 1833 return x,y,f() -- returns x, y, and all results from f() 1834 {f()} -- creates a list with all results from f() 1835 {...} -- creates a list with all vararg parameters 1836 {f(), nil} -- f() is adjusted to 1 result 1837</pre> 1838 1839<p> 1840Any expression enclosed in parentheses always results in only one value. 1841Thus, 1842<code>(f(x,y,z))</code> is always a single value, 1843even if <code>f</code> returns several values. 1844(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code> 1845or <b>nil</b> if <code>f</code> does not return any values.) 1846 1847 1848 1849<h3>3.4.1 – <a name="3.4.1">Arithmetic Operators</a></h3><p> 1850Lua supports the following arithmetic operators: 1851 1852<ul> 1853<li><b><code>+</code>: </b>addition</li> 1854<li><b><code>-</code>: </b>subtraction</li> 1855<li><b><code>*</code>: </b>multiplication</li> 1856<li><b><code>/</code>: </b>float division</li> 1857<li><b><code>//</code>: </b>floor division</li> 1858<li><b><code>%</code>: </b>modulo</li> 1859<li><b><code>^</code>: </b>exponentiation</li> 1860<li><b><code>-</code>: </b>unary minus</li> 1861</ul> 1862 1863<p> 1864With the exception of exponentiation and float division, 1865the arithmetic operators work as follows: 1866If both operands are integers, 1867the operation is performed over integers and the result is an integer. 1868Otherwise, if both operands are numbers 1869or strings that can be converted to 1870numbers (see <a href="#3.4.3">§3.4.3</a>), 1871then they are converted to floats, 1872the operation is performed following the usual rules 1873for floating-point arithmetic 1874(usually the IEEE 754 standard), 1875and the result is a float. 1876 1877 1878<p> 1879Exponentiation and float division (<code>/</code>) 1880always convert their operands to floats 1881and the result is always a float. 1882Exponentiation uses the ISO C function <code>pow</code>, 1883so that it works for non-integer exponents too. 1884 1885 1886<p> 1887Floor division (<code>//</code>) is a division 1888that rounds the quotient towards minus infinity, 1889that is, the floor of the division of its operands. 1890 1891 1892<p> 1893Modulo is defined as the remainder of a division 1894that rounds the quotient towards minus infinity (floor division). 1895 1896 1897<p> 1898In case of overflows in integer arithmetic, 1899all operations <em>wrap around</em>, 1900according to the usual rules of two-complement arithmetic. 1901(In other words, 1902they return the unique representable integer 1903that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.) 1904 1905 1906 1907<h3>3.4.2 – <a name="3.4.2">Bitwise Operators</a></h3><p> 1908Lua supports the following bitwise operators: 1909 1910<ul> 1911<li><b><code>&</code>: </b>bitwise and</li> 1912<li><b><code>|</code>: </b>bitwise or</li> 1913<li><b><code>~</code>: </b>bitwise exclusive or</li> 1914<li><b><code>>></code>: </b>right shift</li> 1915<li><b><code><<</code>: </b>left shift</li> 1916<li><b><code>~</code>: </b>unary bitwise not</li> 1917</ul> 1918 1919<p> 1920All bitwise operations convert its operands to integers 1921(see <a href="#3.4.3">§3.4.3</a>), 1922operate on all bits of those integers, 1923and result in an integer. 1924 1925 1926<p> 1927Both right and left shifts fill the vacant bits with zeros. 1928Negative displacements shift to the other direction; 1929displacements with absolute values equal to or higher than 1930the number of bits in an integer 1931result in zero (as all bits are shifted out). 1932 1933 1934 1935 1936 1937<h3>3.4.3 – <a name="3.4.3">Coercions and Conversions</a></h3><p> 1938Lua provides some automatic conversions between some 1939types and representations at run time. 1940Bitwise operators always convert float operands to integers. 1941Exponentiation and float division 1942always convert integer operands to floats. 1943All other arithmetic operations applied to mixed numbers 1944(integers and floats) convert the integer operand to a float; 1945this is called the <em>usual rule</em>. 1946The C API also converts both integers to floats and 1947floats to integers, as needed. 1948Moreover, string concatenation accepts numbers as arguments, 1949besides strings. 1950 1951 1952<p> 1953Lua also converts strings to numbers, 1954whenever a number is expected. 1955 1956 1957<p> 1958In a conversion from integer to float, 1959if the integer value has an exact representation as a float, 1960that is the result. 1961Otherwise, 1962the conversion gets the nearest higher or 1963the nearest lower representable value. 1964This kind of conversion never fails. 1965 1966 1967<p> 1968The conversion from float to integer 1969checks whether the float has an exact representation as an integer 1970(that is, the float has an integral value and 1971it is in the range of integer representation). 1972If it does, that representation is the result. 1973Otherwise, the conversion fails. 1974 1975 1976<p> 1977The conversion from strings to numbers goes as follows: 1978First, the string is converted to an integer or a float, 1979following its syntax and the rules of the Lua lexer. 1980(The string may have also leading and trailing spaces and a sign.) 1981Then, the resulting number (float or integer) 1982is converted to the type (float or integer) required by the context 1983(e.g., the operation that forced the conversion). 1984 1985 1986<p> 1987The conversion from numbers to strings uses a 1988non-specified human-readable format. 1989For complete control over how numbers are converted to strings, 1990use the <code>format</code> function from the string library 1991(see <a href="#pdf-string.format"><code>string.format</code></a>). 1992 1993 1994 1995 1996 1997<h3>3.4.4 – <a name="3.4.4">Relational Operators</a></h3><p> 1998Lua supports the following relational operators: 1999 2000<ul> 2001<li><b><code>==</code>: </b>equality</li> 2002<li><b><code>~=</code>: </b>inequality</li> 2003<li><b><code><</code>: </b>less than</li> 2004<li><b><code>></code>: </b>greater than</li> 2005<li><b><code><=</code>: </b>less or equal</li> 2006<li><b><code>>=</code>: </b>greater or equal</li> 2007</ul><p> 2008These operators always result in <b>false</b> or <b>true</b>. 2009 2010 2011<p> 2012Equality (<code>==</code>) first compares the type of its operands. 2013If the types are different, then the result is <b>false</b>. 2014Otherwise, the values of the operands are compared. 2015Strings are compared in the obvious way. 2016Numbers are equal if they denote the same mathematical value. 2017 2018 2019<p> 2020Tables, userdata, and threads 2021are compared by reference: 2022two objects are considered equal only if they are the same object. 2023Every time you create a new object 2024(a table, userdata, or thread), 2025this new object is different from any previously existing object. 2026Closures with the same reference are always equal. 2027Closures with any detectable difference 2028(different behavior, different definition) are always different. 2029 2030 2031<p> 2032You can change the way that Lua compares tables and userdata 2033by using the "eq" metamethod (see <a href="#2.4">§2.4</a>). 2034 2035 2036<p> 2037Equality comparisons do not convert strings to numbers 2038or vice versa. 2039Thus, <code>"0"==0</code> evaluates to <b>false</b>, 2040and <code>t[0]</code> and <code>t["0"]</code> denote different 2041entries in a table. 2042 2043 2044<p> 2045The operator <code>~=</code> is exactly the negation of equality (<code>==</code>). 2046 2047 2048<p> 2049The order operators work as follows. 2050If both arguments are numbers, 2051then they are compared according to their mathematical values 2052(regardless of their subtypes). 2053Otherwise, if both arguments are strings, 2054then their values are compared according to the current locale. 2055Otherwise, Lua tries to call the "lt" or the "le" 2056metamethod (see <a href="#2.4">§2.4</a>). 2057A comparison <code>a > b</code> is translated to <code>b < a</code> 2058and <code>a >= b</code> is translated to <code>b <= a</code>. 2059 2060 2061<p> 2062Following the IEEE 754 standard, 2063NaN is considered neither smaller than, 2064nor equal to, nor greater than any value (including itself). 2065 2066 2067 2068 2069 2070<h3>3.4.5 – <a name="3.4.5">Logical Operators</a></h3><p> 2071The logical operators in Lua are 2072<b>and</b>, <b>or</b>, and <b>not</b>. 2073Like the control structures (see <a href="#3.3.4">§3.3.4</a>), 2074all logical operators consider both <b>false</b> and <b>nil</b> as false 2075and anything else as true. 2076 2077 2078<p> 2079The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>. 2080The conjunction operator <b>and</b> returns its first argument 2081if this value is <b>false</b> or <b>nil</b>; 2082otherwise, <b>and</b> returns its second argument. 2083The disjunction operator <b>or</b> returns its first argument 2084if this value is different from <b>nil</b> and <b>false</b>; 2085otherwise, <b>or</b> returns its second argument. 2086Both <b>and</b> and <b>or</b> use short-circuit evaluation; 2087that is, 2088the second operand is evaluated only if necessary. 2089Here are some examples: 2090 2091<pre> 2092 10 or 20 --> 10 2093 10 or error() --> 10 2094 nil or "a" --> "a" 2095 nil and 10 --> nil 2096 false and error() --> false 2097 false and nil --> false 2098 false or nil --> nil 2099 10 and 20 --> 20 2100</pre><p> 2101(In this manual, 2102<code>--></code> indicates the result of the preceding expression.) 2103 2104 2105 2106 2107 2108<h3>3.4.6 – <a name="3.4.6">Concatenation</a></h3><p> 2109The string concatenation operator in Lua is 2110denoted by two dots ('<code>..</code>'). 2111If both operands are strings or numbers, then they are converted to 2112strings according to the rules described in <a href="#3.4.3">§3.4.3</a>. 2113Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">§2.4</a>). 2114 2115 2116 2117 2118 2119<h3>3.4.7 – <a name="3.4.7">The Length Operator</a></h3> 2120 2121<p> 2122The length operator is denoted by the unary prefix operator <code>#</code>. 2123The length of a string is its number of bytes 2124(that is, the usual meaning of string length when each 2125character is one byte). 2126 2127 2128<p> 2129A program can modify the behavior of the length operator for 2130any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">§2.4</a>). 2131 2132 2133<p> 2134Unless a <code>__len</code> metamethod is given, 2135the length of a table <code>t</code> is only defined if the 2136table is a <em>sequence</em>, 2137that is, 2138the set of its positive numeric keys is equal to <em>{1..n}</em> 2139for some non-negative integer <em>n</em>. 2140In that case, <em>n</em> is its length. 2141Note that a table like 2142 2143<pre> 2144 {10, 20, nil, 40} 2145</pre><p> 2146is not a sequence, because it has the key <code>4</code> 2147but does not have the key <code>3</code>. 2148(So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal 2149to the set of positive numeric keys of that table.) 2150Note, however, that non-numeric keys do not interfere 2151with whether a table is a sequence. 2152 2153 2154 2155 2156 2157<h3>3.4.8 – <a name="3.4.8">Precedence</a></h3><p> 2158Operator precedence in Lua follows the table below, 2159from lower to higher priority: 2160 2161<pre> 2162 or 2163 and 2164 < > <= >= ~= == 2165 | 2166 ~ 2167 & 2168 << >> 2169 .. 2170 + - 2171 * / // % 2172 unary operators (not # - ~) 2173 ^ 2174</pre><p> 2175As usual, 2176you can use parentheses to change the precedences of an expression. 2177The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>') 2178operators are right associative. 2179All other binary operators are left associative. 2180 2181 2182 2183 2184 2185<h3>3.4.9 – <a name="3.4.9">Table Constructors</a></h3><p> 2186Table constructors are expressions that create tables. 2187Every time a constructor is evaluated, a new table is created. 2188A constructor can be used to create an empty table 2189or to create a table and initialize some of its fields. 2190The general syntax for constructors is 2191 2192<pre> 2193 tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’ 2194 fieldlist ::= field {fieldsep field} [fieldsep] 2195 field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp 2196 fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’ 2197</pre> 2198 2199<p> 2200Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry 2201with key <code>exp1</code> and value <code>exp2</code>. 2202A field of the form <code>name = exp</code> is equivalent to 2203<code>["name"] = exp</code>. 2204Finally, fields of the form <code>exp</code> are equivalent to 2205<code>[i] = exp</code>, where <code>i</code> are consecutive integers 2206starting with 1. 2207Fields in the other formats do not affect this counting. 2208For example, 2209 2210<pre> 2211 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } 2212</pre><p> 2213is equivalent to 2214 2215<pre> 2216 do 2217 local t = {} 2218 t[f(1)] = g 2219 t[1] = "x" -- 1st exp 2220 t[2] = "y" -- 2nd exp 2221 t.x = 1 -- t["x"] = 1 2222 t[3] = f(x) -- 3rd exp 2223 t[30] = 23 2224 t[4] = 45 -- 4th exp 2225 a = t 2226 end 2227</pre> 2228 2229<p> 2230The order of the assignments in a constructor is undefined. 2231(This order would be relevant only when there are repeated keys.) 2232 2233 2234<p> 2235If the last field in the list has the form <code>exp</code> 2236and the expression is a function call or a vararg expression, 2237then all values returned by this expression enter the list consecutively 2238(see <a href="#3.4.10">§3.4.10</a>). 2239 2240 2241<p> 2242The field list can have an optional trailing separator, 2243as a convenience for machine-generated code. 2244 2245 2246 2247 2248 2249<h3>3.4.10 – <a name="3.4.10">Function Calls</a></h3><p> 2250A function call in Lua has the following syntax: 2251 2252<pre> 2253 functioncall ::= prefixexp args 2254</pre><p> 2255In a function call, 2256first prefixexp and args are evaluated. 2257If the value of prefixexp has type <em>function</em>, 2258then this function is called 2259with the given arguments. 2260Otherwise, the prefixexp "call" metamethod is called, 2261having as first parameter the value of prefixexp, 2262followed by the original call arguments 2263(see <a href="#2.4">§2.4</a>). 2264 2265 2266<p> 2267The form 2268 2269<pre> 2270 functioncall ::= prefixexp ‘<b>:</b>’ Name args 2271</pre><p> 2272can be used to call "methods". 2273A call <code>v:name(<em>args</em>)</code> 2274is syntactic sugar for <code>v.name(v,<em>args</em>)</code>, 2275except that <code>v</code> is evaluated only once. 2276 2277 2278<p> 2279Arguments have the following syntax: 2280 2281<pre> 2282 args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ 2283 args ::= tableconstructor 2284 args ::= LiteralString 2285</pre><p> 2286All argument expressions are evaluated before the call. 2287A call of the form <code>f{<em>fields</em>}</code> is 2288syntactic sugar for <code>f({<em>fields</em>})</code>; 2289that is, the argument list is a single new table. 2290A call of the form <code>f'<em>string</em>'</code> 2291(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>) 2292is syntactic sugar for <code>f('<em>string</em>')</code>; 2293that is, the argument list is a single literal string. 2294 2295 2296<p> 2297A call of the form <code>return <em>functioncall</em></code> is called 2298a <em>tail call</em>. 2299Lua implements <em>proper tail calls</em> 2300(or <em>proper tail recursion</em>): 2301in a tail call, 2302the called function reuses the stack entry of the calling function. 2303Therefore, there is no limit on the number of nested tail calls that 2304a program can execute. 2305However, a tail call erases any debug information about the 2306calling function. 2307Note that a tail call only happens with a particular syntax, 2308where the <b>return</b> has one single function call as argument; 2309this syntax makes the calling function return exactly 2310the returns of the called function. 2311So, none of the following examples are tail calls: 2312 2313<pre> 2314 return (f(x)) -- results adjusted to 1 2315 return 2 * f(x) 2316 return x, f(x) -- additional results 2317 f(x); return -- results discarded 2318 return x or f(x) -- results adjusted to 1 2319</pre> 2320 2321 2322 2323 2324<h3>3.4.11 – <a name="3.4.11">Function Definitions</a></h3> 2325 2326<p> 2327The syntax for function definition is 2328 2329<pre> 2330 functiondef ::= <b>function</b> funcbody 2331 funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b> 2332</pre> 2333 2334<p> 2335The following syntactic sugar simplifies function definitions: 2336 2337<pre> 2338 stat ::= <b>function</b> funcname funcbody 2339 stat ::= <b>local</b> <b>function</b> Name funcbody 2340 funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name] 2341</pre><p> 2342The statement 2343 2344<pre> 2345 function f () <em>body</em> end 2346</pre><p> 2347translates to 2348 2349<pre> 2350 f = function () <em>body</em> end 2351</pre><p> 2352The statement 2353 2354<pre> 2355 function t.a.b.c.f () <em>body</em> end 2356</pre><p> 2357translates to 2358 2359<pre> 2360 t.a.b.c.f = function () <em>body</em> end 2361</pre><p> 2362The statement 2363 2364<pre> 2365 local function f () <em>body</em> end 2366</pre><p> 2367translates to 2368 2369<pre> 2370 local f; f = function () <em>body</em> end 2371</pre><p> 2372not to 2373 2374<pre> 2375 local f = function () <em>body</em> end 2376</pre><p> 2377(This only makes a difference when the body of the function 2378contains references to <code>f</code>.) 2379 2380 2381<p> 2382A function definition is an executable expression, 2383whose value has type <em>function</em>. 2384When Lua precompiles a chunk, 2385all its function bodies are precompiled too. 2386Then, whenever Lua executes the function definition, 2387the function is <em>instantiated</em> (or <em>closed</em>). 2388This function instance (or <em>closure</em>) 2389is the final value of the expression. 2390 2391 2392<p> 2393Parameters act as local variables that are 2394initialized with the argument values: 2395 2396<pre> 2397 parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’ 2398</pre><p> 2399When a function is called, 2400the list of arguments is adjusted to 2401the length of the list of parameters, 2402unless the function is a <em>vararg function</em>, 2403which is indicated by three dots ('<code>...</code>') 2404at the end of its parameter list. 2405A vararg function does not adjust its argument list; 2406instead, it collects all extra arguments and supplies them 2407to the function through a <em>vararg expression</em>, 2408which is also written as three dots. 2409The value of this expression is a list of all actual extra arguments, 2410similar to a function with multiple results. 2411If a vararg expression is used inside another expression 2412or in the middle of a list of expressions, 2413then its return list is adjusted to one element. 2414If the expression is used as the last element of a list of expressions, 2415then no adjustment is made 2416(unless that last expression is enclosed in parentheses). 2417 2418 2419<p> 2420As an example, consider the following definitions: 2421 2422<pre> 2423 function f(a, b) end 2424 function g(a, b, ...) end 2425 function r() return 1,2,3 end 2426</pre><p> 2427Then, we have the following mapping from arguments to parameters and 2428to the vararg expression: 2429 2430<pre> 2431 CALL PARAMETERS 2432 2433 f(3) a=3, b=nil 2434 f(3, 4) a=3, b=4 2435 f(3, 4, 5) a=3, b=4 2436 f(r(), 10) a=1, b=10 2437 f(r()) a=1, b=2 2438 2439 g(3) a=3, b=nil, ... --> (nothing) 2440 g(3, 4) a=3, b=4, ... --> (nothing) 2441 g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 2442 g(5, r()) a=5, b=1, ... --> 2 3 2443</pre> 2444 2445<p> 2446Results are returned using the <b>return</b> statement (see <a href="#3.3.4">§3.3.4</a>). 2447If control reaches the end of a function 2448without encountering a <b>return</b> statement, 2449then the function returns with no results. 2450 2451 2452<p> 2453 2454There is a system-dependent limit on the number of values 2455that a function may return. 2456This limit is guaranteed to be larger than 1000. 2457 2458 2459<p> 2460The <em>colon</em> syntax 2461is used for defining <em>methods</em>, 2462that is, functions that have an implicit extra parameter <code>self</code>. 2463Thus, the statement 2464 2465<pre> 2466 function t.a.b.c:f (<em>params</em>) <em>body</em> end 2467</pre><p> 2468is syntactic sugar for 2469 2470<pre> 2471 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end 2472</pre> 2473 2474 2475 2476 2477 2478 2479<h2>3.5 – <a name="3.5">Visibility Rules</a></h2> 2480 2481<p> 2482 2483Lua is a lexically scoped language. 2484The scope of a local variable begins at the first statement after 2485its declaration and lasts until the last non-void statement 2486of the innermost block that includes the declaration. 2487Consider the following example: 2488 2489<pre> 2490 x = 10 -- global variable 2491 do -- new block 2492 local x = x -- new 'x', with value 10 2493 print(x) --> 10 2494 x = x+1 2495 do -- another block 2496 local x = x+1 -- another 'x' 2497 print(x) --> 12 2498 end 2499 print(x) --> 11 2500 end 2501 print(x) --> 10 (the global one) 2502</pre> 2503 2504<p> 2505Notice that, in a declaration like <code>local x = x</code>, 2506the new <code>x</code> being declared is not in scope yet, 2507and so the second <code>x</code> refers to the outside variable. 2508 2509 2510<p> 2511Because of the lexical scoping rules, 2512local variables can be freely accessed by functions 2513defined inside their scope. 2514A local variable used by an inner function is called 2515an <em>upvalue</em>, or <em>external local variable</em>, 2516inside the inner function. 2517 2518 2519<p> 2520Notice that each execution of a <b>local</b> statement 2521defines new local variables. 2522Consider the following example: 2523 2524<pre> 2525 a = {} 2526 local x = 20 2527 for i=1,10 do 2528 local y = 0 2529 a[i] = function () y=y+1; return x+y end 2530 end 2531</pre><p> 2532The loop creates ten closures 2533(that is, ten instances of the anonymous function). 2534Each of these closures uses a different <code>y</code> variable, 2535while all of them share the same <code>x</code>. 2536 2537 2538 2539 2540 2541<h1>4 – <a name="4">The Application Program Interface</a></h1> 2542 2543<p> 2544 2545This section describes the C API for Lua, that is, 2546the set of C functions available to the host program to communicate 2547with Lua. 2548All API functions and related types and constants 2549are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>. 2550 2551 2552<p> 2553Even when we use the term "function", 2554any facility in the API may be provided as a macro instead. 2555Except where stated otherwise, 2556all such macros use each of their arguments exactly once 2557(except for the first argument, which is always a Lua state), 2558and so do not generate any hidden side-effects. 2559 2560 2561<p> 2562As in most C libraries, 2563the Lua API functions do not check their arguments for validity or consistency. 2564However, you can change this behavior by compiling Lua 2565with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined. 2566 2567 2568 2569<h2>4.1 – <a name="4.1">The Stack</a></h2> 2570 2571<p> 2572Lua uses a <em>virtual stack</em> to pass values to and from C. 2573Each element in this stack represents a Lua value 2574(<b>nil</b>, number, string, etc.). 2575 2576 2577<p> 2578Whenever Lua calls C, the called function gets a new stack, 2579which is independent of previous stacks and of stacks of 2580C functions that are still active. 2581This stack initially contains any arguments to the C function 2582and it is where the C function pushes its results 2583to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 2584 2585 2586<p> 2587For convenience, 2588most query operations in the API do not follow a strict stack discipline. 2589Instead, they can refer to any element in the stack 2590by using an <em>index</em>: 2591A positive index represents an absolute stack position 2592(starting at 1); 2593a negative index represents an offset relative to the top of the stack. 2594More specifically, if the stack has <em>n</em> elements, 2595then index 1 represents the first element 2596(that is, the element that was pushed onto the stack first) 2597and 2598index <em>n</em> represents the last element; 2599index -1 also represents the last element 2600(that is, the element at the top) 2601and index <em>-n</em> represents the first element. 2602 2603 2604 2605 2606 2607<h2>4.2 – <a name="4.2">Stack Size</a></h2> 2608 2609<p> 2610When you interact with the Lua API, 2611you are responsible for ensuring consistency. 2612In particular, 2613<em>you are responsible for controlling stack overflow</em>. 2614You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a> 2615to ensure that the stack has enough space for pushing new elements. 2616 2617 2618<p> 2619Whenever Lua calls C, 2620it ensures that the stack has space for 2621at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots. 2622<code>LUA_MINSTACK</code> is defined as 20, 2623so that usually you do not have to worry about stack space 2624unless your code has loops pushing elements onto the stack. 2625 2626 2627<p> 2628When you call a Lua function 2629without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>), 2630Lua ensures that the stack has enough space for all results, 2631but it does not ensure any extra space. 2632So, before pushing anything in the stack after such a call 2633you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>. 2634 2635 2636 2637 2638 2639<h2>4.3 – <a name="4.3">Valid and Acceptable Indices</a></h2> 2640 2641<p> 2642Any function in the API that receives stack indices 2643works only with <em>valid indices</em> or <em>acceptable indices</em>. 2644 2645 2646<p> 2647A <em>valid index</em> is an index that refers to a 2648position that stores a modifiable Lua value. 2649It comprises stack indices between 1 and the stack top 2650(<code>1 ≤ abs(index) ≤ top</code>) 2651 2652plus <em>pseudo-indices</em>, 2653which represent some positions that are accessible to C code 2654but that are not in the stack. 2655Pseudo-indices are used to access the registry (see <a href="#4.5">§4.5</a>) 2656and the upvalues of a C function (see <a href="#4.4">§4.4</a>). 2657 2658 2659<p> 2660Functions that do not need a specific mutable position, 2661but only a value (e.g., query functions), 2662can be called with acceptable indices. 2663An <em>acceptable index</em> can be any valid index, 2664but it also can be any positive index after the stack top 2665within the space allocated for the stack, 2666that is, indices up to the stack size. 2667(Note that 0 is never an acceptable index.) 2668Except when noted otherwise, 2669functions in the API work with acceptable indices. 2670 2671 2672<p> 2673Acceptable indices serve to avoid extra tests 2674against the stack top when querying the stack. 2675For instance, a C function can query its third argument 2676without the need to first check whether there is a third argument, 2677that is, without the need to check whether 3 is a valid index. 2678 2679 2680<p> 2681For functions that can be called with acceptable indices, 2682any non-valid index is treated as if it 2683contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>, 2684which behaves like a nil value. 2685 2686 2687 2688 2689 2690<h2>4.4 – <a name="4.4">C Closures</a></h2> 2691 2692<p> 2693When a C function is created, 2694it is possible to associate some values with it, 2695thus creating a <em>C closure</em> 2696(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>); 2697these values are called <em>upvalues</em> and are 2698accessible to the function whenever it is called. 2699 2700 2701<p> 2702Whenever a C function is called, 2703its upvalues are located at specific pseudo-indices. 2704These pseudo-indices are produced by the macro 2705<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>. 2706The first upvalue associated with a function is at index 2707<code>lua_upvalueindex(1)</code>, and so on. 2708Any access to <code>lua_upvalueindex(<em>n</em>)</code>, 2709where <em>n</em> is greater than the number of upvalues of the 2710current function 2711(but not greater than 256, 2712which is one plus the maximum number of upvalues in a closure), 2713produces an acceptable but invalid index. 2714 2715 2716 2717 2718 2719<h2>4.5 – <a name="4.5">Registry</a></h2> 2720 2721<p> 2722Lua provides a <em>registry</em>, 2723a predefined table that can be used by any C code to 2724store whatever Lua values it needs to store. 2725The registry table is always located at pseudo-index 2726<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>. 2727Any C library can store data into this table, 2728but it must take care to choose keys 2729that are different from those used 2730by other libraries, to avoid collisions. 2731Typically, you should use as key a string containing your library name, 2732or a light userdata with the address of a C object in your code, 2733or any Lua object created by your code. 2734As with variable names, 2735string keys starting with an underscore followed by 2736uppercase letters are reserved for Lua. 2737 2738 2739<p> 2740The integer keys in the registry are used 2741by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>) 2742and by some predefined values. 2743Therefore, integer keys must not be used for other purposes. 2744 2745 2746<p> 2747When you create a new Lua state, 2748its registry comes with some predefined values. 2749These predefined values are indexed with integer keys 2750defined as constants in <code>lua.h</code>. 2751The following constants are defined: 2752 2753<ul> 2754<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has 2755the main thread of the state. 2756(The main thread is the one created together with the state.) 2757</li> 2758 2759<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has 2760the global environment. 2761</li> 2762</ul> 2763 2764 2765 2766 2767<h2>4.6 – <a name="4.6">Error Handling in C</a></h2> 2768 2769<p> 2770Internally, Lua uses the C <code>longjmp</code> facility to handle errors. 2771(Lua will use exceptions if you compile it as C++; 2772search for <code>LUAI_THROW</code> in the source code for details.) 2773When Lua faces any error 2774(such as a memory allocation error, type errors, syntax errors, 2775and runtime errors) 2776it <em>raises</em> an error; 2777that is, it does a long jump. 2778A <em>protected environment</em> uses <code>setjmp</code> 2779to set a recovery point; 2780any error jumps to the most recent active recovery point. 2781 2782 2783<p> 2784If an error happens outside any protected environment, 2785Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) 2786and then calls <code>abort</code>, 2787thus exiting the host application. 2788Your panic function can avoid this exit by 2789never returning 2790(e.g., doing a long jump to your own recovery point outside Lua). 2791 2792 2793<p> 2794The panic function runs as if it were a message handler (see <a href="#2.3">§2.3</a>); 2795in particular, the error message is at the top of the stack. 2796However, there is no guarantee about stack space. 2797To push anything on the stack, 2798the panic function must first check the available space (see <a href="#4.2">§4.2</a>). 2799 2800 2801<p> 2802Most functions in the API can raise an error, 2803for instance due to a memory allocation error. 2804The documentation for each function indicates whether 2805it can raise errors. 2806 2807 2808<p> 2809Inside a C function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>. 2810 2811 2812 2813 2814 2815<h2>4.7 – <a name="4.7">Handling Yields in C</a></h2> 2816 2817<p> 2818Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine. 2819Therefore, if a C function <code>foo</code> calls an API function 2820and this API function yields 2821(directly or indirectly by calling another function that yields), 2822Lua cannot return to <code>foo</code> any more, 2823because the <code>longjmp</code> removes its frame from the C stack. 2824 2825 2826<p> 2827To avoid this kind of problem, 2828Lua raises an error whenever it tries to yield across an API call, 2829except for three functions: 2830<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>. 2831All those functions receive a <em>continuation function</em> 2832(as a parameter named <code>k</code>) to continue execution after a yield. 2833 2834 2835<p> 2836We need to set some terminology to explain continuations. 2837We have a C function called from Lua which we will call 2838the <em>original function</em>. 2839This original function then calls one of those three functions in the C API, 2840which we will call the <em>callee function</em>, 2841that then yields the current thread. 2842(This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 2843or 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> 2844and the function called by them yields.) 2845 2846 2847<p> 2848Suppose the running thread yields while executing the callee function. 2849After the thread resumes, 2850it eventually will finish running the callee function. 2851However, 2852the callee function cannot return to the original function, 2853because its frame in the C stack was destroyed by the yield. 2854Instead, Lua calls a <em>continuation function</em>, 2855which was given as an argument to the callee function. 2856As the name implies, 2857the continuation function should continue the task 2858of the original function. 2859 2860 2861<p> 2862As an illustration, consider the following function: 2863 2864<pre> 2865 int original_function (lua_State *L) { 2866 ... /* code 1 */ 2867 status = lua_pcall(L, n, m, h); /* calls Lua */ 2868 ... /* code 2 */ 2869 } 2870</pre><p> 2871Now we want to allow 2872the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield. 2873First, we can rewrite our function like here: 2874 2875<pre> 2876 int k (lua_State *L, int status, lua_KContext ctx) { 2877 ... /* code 2 */ 2878 } 2879 2880 int original_function (lua_State *L) { 2881 ... /* code 1 */ 2882 return k(L, lua_pcall(L, n, m, h), ctx); 2883 } 2884</pre><p> 2885In the above code, 2886the new function <code>k</code> is a 2887<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>), 2888which should do all the work that the original function 2889was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>. 2890Now, we must inform Lua that it must call <code>k</code> if the Lua code 2891being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way 2892(errors or yielding), 2893so we rewrite the code as here, 2894replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>: 2895 2896<pre> 2897 int original_function (lua_State *L) { 2898 ... /* code 1 */ 2899 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); 2900 } 2901</pre><p> 2902Note the external, explicit call to the continuation: 2903Lua will call the continuation only if needed, that is, 2904in case of errors or resuming after a yield. 2905If the called function returns normally without ever yielding, 2906<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally. 2907(Of course, instead of calling the continuation in that case, 2908you can do the equivalent work directly inside the original function.) 2909 2910 2911<p> 2912Besides the Lua state, 2913the continuation function has two other parameters: 2914the final status of the call plus the context value (<code>ctx</code>) that 2915was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>. 2916(Lua does not use this context value; 2917it only passes this value from the original function to the 2918continuation function.) 2919For <a href="#lua_pcallk"><code>lua_pcallk</code></a>, 2920the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>, 2921except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield 2922(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>). 2923For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>, 2924the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation. 2925(For these two functions, 2926Lua will not call the continuation in case of errors, 2927because they do not handle errors.) 2928Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>, 2929you should call the continuation function 2930with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status. 2931(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling 2932directly the continuation function, 2933because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.) 2934 2935 2936<p> 2937Lua treats the continuation function as if it were the original function. 2938The continuation function receives the same Lua stack 2939from the original function, 2940in the same state it would be if the callee function had returned. 2941(For instance, 2942after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are 2943removed from the stack and replaced by the results from the call.) 2944It also has the same upvalues. 2945Whatever it returns is handled by Lua as if it were the return 2946of the original function. 2947 2948 2949 2950 2951 2952<h2>4.8 – <a name="4.8">Functions and Types</a></h2> 2953 2954<p> 2955Here we list all functions and types from the C API in 2956alphabetical order. 2957Each function has an indicator like this: 2958<span class="apii">[-o, +p, <em>x</em>]</span> 2959 2960 2961<p> 2962The first field, <code>o</code>, 2963is how many elements the function pops from the stack. 2964The second field, <code>p</code>, 2965is how many elements the function pushes onto the stack. 2966(Any function always pushes its results after popping its arguments.) 2967A field in the form <code>x|y</code> means the function can push (or pop) 2968<code>x</code> or <code>y</code> elements, 2969depending on the situation; 2970an interrogation mark '<code>?</code>' means that 2971we cannot know how many elements the function pops/pushes 2972by looking only at its arguments 2973(e.g., they may depend on what is on the stack). 2974The third field, <code>x</code>, 2975tells whether the function may raise errors: 2976'<code>-</code>' means the function never raises any error; 2977'<code>m</code>' means the function may raise memory errors; 2978'<code>e</code>' means the function may raise errors; 2979'<code>v</code>' means the function may raise an error on purpose. 2980 2981 2982 2983<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p> 2984<span class="apii">[-0, +0, –]</span> 2985<pre>int lua_absindex (lua_State *L, int idx);</pre> 2986 2987<p> 2988Converts the acceptable index <code>idx</code> 2989into an equivalent absolute index 2990(that is, one that does not depend on the stack top). 2991 2992 2993 2994 2995 2996<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3> 2997<pre>typedef void * (*lua_Alloc) (void *ud, 2998 void *ptr, 2999 size_t osize, 3000 size_t nsize);</pre> 3001 3002<p> 3003The type of the memory-allocation function used by Lua states. 3004The allocator function must provide a 3005functionality similar to <code>realloc</code>, 3006but not exactly the same. 3007Its arguments are 3008<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>; 3009<code>ptr</code>, a pointer to the block being allocated/reallocated/freed; 3010<code>osize</code>, the original size of the block or some code about what 3011is being allocated; 3012and <code>nsize</code>, the new size of the block. 3013 3014 3015<p> 3016When <code>ptr</code> is not <code>NULL</code>, 3017<code>osize</code> is the size of the block pointed by <code>ptr</code>, 3018that is, the size given when it was allocated or reallocated. 3019 3020 3021<p> 3022When <code>ptr</code> is <code>NULL</code>, 3023<code>osize</code> encodes the kind of object that Lua is allocating. 3024<code>osize</code> is any of 3025<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>, 3026<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) 3027Lua is creating a new object of that type. 3028When <code>osize</code> is some other value, 3029Lua is allocating memory for something else. 3030 3031 3032<p> 3033Lua assumes the following behavior from the allocator function: 3034 3035 3036<p> 3037When <code>nsize</code> is zero, 3038the allocator must behave like <code>free</code> 3039and return <code>NULL</code>. 3040 3041 3042<p> 3043When <code>nsize</code> is not zero, 3044the allocator must behave like <code>realloc</code>. 3045The allocator returns <code>NULL</code> 3046if and only if it cannot fulfill the request. 3047Lua assumes that the allocator never fails when 3048<code>osize >= nsize</code>. 3049 3050 3051<p> 3052Here is a simple implementation for the allocator function. 3053It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>. 3054 3055<pre> 3056 static void *l_alloc (void *ud, void *ptr, size_t osize, 3057 size_t nsize) { 3058 (void)ud; (void)osize; /* not used */ 3059 if (nsize == 0) { 3060 free(ptr); 3061 return NULL; 3062 } 3063 else 3064 return realloc(ptr, nsize); 3065 } 3066</pre><p> 3067Note that Standard C ensures 3068that <code>free(NULL)</code> has no effect and that 3069<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>. 3070This code assumes that <code>realloc</code> does not fail when shrinking a block. 3071(Although Standard C does not ensure this behavior, 3072it seems to be a safe assumption.) 3073 3074 3075 3076 3077 3078<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p> 3079<span class="apii">[-(2|1), +1, <em>e</em>]</span> 3080<pre>void lua_arith (lua_State *L, int op);</pre> 3081 3082<p> 3083Performs an arithmetic or bitwise operation over the two values 3084(or one, in the case of negations) 3085at the top of the stack, 3086with the value at the top being the second operand, 3087pops these values, and pushes the result of the operation. 3088The function follows the semantics of the corresponding Lua operator 3089(that is, it may call metamethods). 3090 3091 3092<p> 3093The value of <code>op</code> must be one of the following constants: 3094 3095<ul> 3096 3097<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li> 3098<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li> 3099<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li> 3100<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li> 3101<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li> 3102<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li> 3103<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li> 3104<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li> 3105<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise negation (<code>~</code>)</li> 3106<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise and (<code>&</code>)</li> 3107<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise or (<code>|</code>)</li> 3108<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive or (<code>~</code>)</li> 3109<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code><<</code>)</li> 3110<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>>></code>)</li> 3111 3112</ul> 3113 3114 3115 3116 3117<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p> 3118<span class="apii">[-0, +0, –]</span> 3119<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre> 3120 3121<p> 3122Sets a new panic function and returns the old one (see <a href="#4.6">§4.6</a>). 3123 3124 3125 3126 3127 3128<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p> 3129<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span> 3130<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre> 3131 3132<p> 3133Calls a function. 3134 3135 3136<p> 3137To call a function you must use the following protocol: 3138first, the function to be called is pushed onto the stack; 3139then, the arguments to the function are pushed 3140in direct order; 3141that is, the first argument is pushed first. 3142Finally you call <a href="#lua_call"><code>lua_call</code></a>; 3143<code>nargs</code> is the number of arguments that you pushed onto the stack. 3144All arguments and the function value are popped from the stack 3145when the function is called. 3146The function results are pushed onto the stack when the function returns. 3147The number of results is adjusted to <code>nresults</code>, 3148unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>. 3149In this case, all results from the function are pushed. 3150Lua takes care that the returned values fit into the stack space, 3151but it does not ensure any extra space in the stack. 3152The function results are pushed onto the stack in direct order 3153(the first result is pushed first), 3154so that after the call the last result is on the top of the stack. 3155 3156 3157<p> 3158Any error inside the called function is propagated upwards 3159(with a <code>longjmp</code>). 3160 3161 3162<p> 3163The following example shows how the host program can do the 3164equivalent to this Lua code: 3165 3166<pre> 3167 a = f("how", t.x, 14) 3168</pre><p> 3169Here it is in C: 3170 3171<pre> 3172 lua_getglobal(L, "f"); /* function to be called */ 3173 lua_pushliteral(L, "how"); /* 1st argument */ 3174 lua_getglobal(L, "t"); /* table to be indexed */ 3175 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ 3176 lua_remove(L, -2); /* remove 't' from the stack */ 3177 lua_pushinteger(L, 14); /* 3rd argument */ 3178 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */ 3179 lua_setglobal(L, "a"); /* set global 'a' */ 3180</pre><p> 3181Note that the code above is <em>balanced</em>: 3182at its end, the stack is back to its original configuration. 3183This is considered good programming practice. 3184 3185 3186 3187 3188 3189<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p> 3190<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span> 3191<pre>void lua_callk (lua_State *L, 3192 int nargs, 3193 int nresults, 3194 lua_KContext ctx, 3195 lua_KFunction k);</pre> 3196 3197<p> 3198This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>, 3199but allows the called function to yield (see <a href="#4.7">§4.7</a>). 3200 3201 3202 3203 3204 3205<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3> 3206<pre>typedef int (*lua_CFunction) (lua_State *L);</pre> 3207 3208<p> 3209Type for C functions. 3210 3211 3212<p> 3213In order to communicate properly with Lua, 3214a C function must use the following protocol, 3215which defines the way parameters and results are passed: 3216a C function receives its arguments from Lua in its stack 3217in direct order (the first argument is pushed first). 3218So, when the function starts, 3219<code>lua_gettop(L)</code> returns the number of arguments received by the function. 3220The first argument (if any) is at index 1 3221and its last argument is at index <code>lua_gettop(L)</code>. 3222To return values to Lua, a C function just pushes them onto the stack, 3223in direct order (the first result is pushed first), 3224and returns the number of results. 3225Any other value in the stack below the results will be properly 3226discarded by Lua. 3227Like a Lua function, a C function called by Lua can also return 3228many results. 3229 3230 3231<p> 3232As an example, the following function receives a variable number 3233of numeric arguments and returns their average and their sum: 3234 3235<pre> 3236 static int foo (lua_State *L) { 3237 int n = lua_gettop(L); /* number of arguments */ 3238 lua_Number sum = 0.0; 3239 int i; 3240 for (i = 1; i <= n; i++) { 3241 if (!lua_isnumber(L, i)) { 3242 lua_pushliteral(L, "incorrect argument"); 3243 lua_error(L); 3244 } 3245 sum += lua_tonumber(L, i); 3246 } 3247 lua_pushnumber(L, sum/n); /* first result */ 3248 lua_pushnumber(L, sum); /* second result */ 3249 return 2; /* number of results */ 3250 } 3251</pre> 3252 3253 3254 3255 3256<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p> 3257<span class="apii">[-0, +0, –]</span> 3258<pre>int lua_checkstack (lua_State *L, int n);</pre> 3259 3260<p> 3261Ensures that the stack has space for at least <code>n</code> extra slots 3262(that is, that you can safely push up to <code>n</code> values into it). 3263It returns false if it cannot fulfill the request, 3264either because it would cause the stack 3265to be larger than a fixed maximum size 3266(typically at least several thousand elements) or 3267because it cannot allocate memory for the extra space. 3268This function never shrinks the stack; 3269if the stack already has space for the extra slots, 3270it is left unchanged. 3271 3272 3273 3274 3275 3276<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p> 3277<span class="apii">[-0, +0, –]</span> 3278<pre>void lua_close (lua_State *L);</pre> 3279 3280<p> 3281Destroys all objects in the given Lua state 3282(calling the corresponding garbage-collection metamethods, if any) 3283and frees all dynamic memory used by this state. 3284On several platforms, you may not need to call this function, 3285because all resources are naturally released when the host program ends. 3286On the other hand, long-running programs that create multiple states, 3287such as daemons or web servers, 3288will probably need to close states as soon as they are not needed. 3289 3290 3291 3292 3293 3294<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p> 3295<span class="apii">[-0, +0, <em>e</em>]</span> 3296<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre> 3297 3298<p> 3299Compares two Lua values. 3300Returns 1 if the value at index <code>index1</code> satisfies <code>op</code> 3301when compared with the value at index <code>index2</code>, 3302following the semantics of the corresponding Lua operator 3303(that is, it may call metamethods). 3304Otherwise returns 0. 3305Also returns 0 if any of the indices is not valid. 3306 3307 3308<p> 3309The value of <code>op</code> must be one of the following constants: 3310 3311<ul> 3312 3313<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li> 3314<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code><</code>)</li> 3315<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code><=</code>)</li> 3316 3317</ul> 3318 3319 3320 3321 3322<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p> 3323<span class="apii">[-n, +1, <em>e</em>]</span> 3324<pre>void lua_concat (lua_State *L, int n);</pre> 3325 3326<p> 3327Concatenates the <code>n</code> values at the top of the stack, 3328pops them, and leaves the result at the top. 3329If <code>n</code> is 1, the result is the single value on the stack 3330(that is, the function does nothing); 3331if <code>n</code> is 0, the result is the empty string. 3332Concatenation is performed following the usual semantics of Lua 3333(see <a href="#3.4.6">§3.4.6</a>). 3334 3335 3336 3337 3338 3339<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p> 3340<span class="apii">[-0, +0, –]</span> 3341<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre> 3342 3343<p> 3344Copies the element at index <code>fromidx</code> 3345into the valid index <code>toidx</code>, 3346replacing the value at that position. 3347Values at other positions are not affected. 3348 3349 3350 3351 3352 3353<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p> 3354<span class="apii">[-0, +1, <em>m</em>]</span> 3355<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre> 3356 3357<p> 3358Creates a new empty table and pushes it onto the stack. 3359Parameter <code>narr</code> is a hint for how many elements the table 3360will have as a sequence; 3361parameter <code>nrec</code> is a hint for how many other elements 3362the table will have. 3363Lua may use these hints to preallocate memory for the new table. 3364This preallocation is useful for performance when you know in advance 3365how many elements the table will have. 3366Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>. 3367 3368 3369 3370 3371 3372<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p> 3373<span class="apii">[-0, +0, –]</span> 3374<pre>int lua_dump (lua_State *L, 3375 lua_Writer writer, 3376 void *data, 3377 int strip);</pre> 3378 3379<p> 3380Dumps a function as a binary chunk. 3381Receives a Lua function on the top of the stack 3382and produces a binary chunk that, 3383if loaded again, 3384results in a function equivalent to the one dumped. 3385As it produces parts of the chunk, 3386<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>) 3387with the given <code>data</code> 3388to write them. 3389 3390 3391<p> 3392If <code>strip</code> is true, 3393the binary representation may not include all debug information 3394about the function, 3395to save space. 3396 3397 3398<p> 3399The value returned is the error code returned by the last 3400call to the writer; 34010 means no errors. 3402 3403 3404<p> 3405This function does not pop the Lua function from the stack. 3406 3407 3408 3409 3410 3411<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p> 3412<span class="apii">[-1, +0, <em>v</em>]</span> 3413<pre>int lua_error (lua_State *L);</pre> 3414 3415<p> 3416Generates a Lua error, 3417using the value at the top of the stack as the error object. 3418This function does a long jump, 3419and therefore never returns 3420(see <a href="#luaL_error"><code>luaL_error</code></a>). 3421 3422 3423 3424 3425 3426<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p> 3427<span class="apii">[-0, +0, <em>e</em>]</span> 3428<pre>int lua_gc (lua_State *L, int what, int data);</pre> 3429 3430<p> 3431Controls the garbage collector. 3432 3433 3434<p> 3435This function performs several tasks, 3436according to the value of the parameter <code>what</code>: 3437 3438<ul> 3439 3440<li><b><code>LUA_GCSTOP</code>: </b> 3441stops the garbage collector. 3442</li> 3443 3444<li><b><code>LUA_GCRESTART</code>: </b> 3445restarts the garbage collector. 3446</li> 3447 3448<li><b><code>LUA_GCCOLLECT</code>: </b> 3449performs a full garbage-collection cycle. 3450</li> 3451 3452<li><b><code>LUA_GCCOUNT</code>: </b> 3453returns the current amount of memory (in Kbytes) in use by Lua. 3454</li> 3455 3456<li><b><code>LUA_GCCOUNTB</code>: </b> 3457returns the remainder of dividing the current amount of bytes of 3458memory in use by Lua by 1024. 3459</li> 3460 3461<li><b><code>LUA_GCSTEP</code>: </b> 3462performs an incremental step of garbage collection. 3463</li> 3464 3465<li><b><code>LUA_GCSETPAUSE</code>: </b> 3466sets <code>data</code> as the new value 3467for the <em>pause</em> of the collector (see <a href="#2.5">§2.5</a>) 3468and returns the previous value of the pause. 3469</li> 3470 3471<li><b><code>LUA_GCSETSTEPMUL</code>: </b> 3472sets <code>data</code> as the new value for the <em>step multiplier</em> of 3473the collector (see <a href="#2.5">§2.5</a>) 3474and returns the previous value of the step multiplier. 3475</li> 3476 3477<li><b><code>LUA_GCISRUNNING</code>: </b> 3478returns a boolean that tells whether the collector is running 3479(i.e., not stopped). 3480</li> 3481 3482</ul> 3483 3484<p> 3485For more details about these options, 3486see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>. 3487 3488 3489 3490 3491 3492<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p> 3493<span class="apii">[-0, +0, –]</span> 3494<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre> 3495 3496<p> 3497Returns the memory-allocation function of a given state. 3498If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the 3499opaque pointer given when the memory-allocator function was set. 3500 3501 3502 3503 3504 3505<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p> 3506<span class="apii">[-0, +1, <em>e</em>]</span> 3507<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre> 3508 3509<p> 3510Pushes onto the stack the value <code>t[k]</code>, 3511where <code>t</code> is the value at the given index. 3512As in Lua, this function may trigger a metamethod 3513for the "index" event (see <a href="#2.4">§2.4</a>). 3514 3515 3516<p> 3517Returns the type of the pushed value. 3518 3519 3520 3521 3522 3523<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p> 3524<span class="apii">[-0, +0, –]</span> 3525<pre>void *lua_getextraspace (lua_State *L);</pre> 3526 3527<p> 3528Returns a pointer to a raw memory area associated with the 3529given Lua state. 3530The application can use this area for any purpose; 3531Lua does not use it for anything. 3532 3533 3534<p> 3535Each new thread has this area initialized with a copy 3536of the area of the main thread. 3537 3538 3539<p> 3540By default, this area has the size of a pointer to void, 3541but you can recompile Lua with a different size for this area. 3542(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.) 3543 3544 3545 3546 3547 3548<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p> 3549<span class="apii">[-0, +1, <em>e</em>]</span> 3550<pre>int lua_getglobal (lua_State *L, const char *name);</pre> 3551 3552<p> 3553Pushes onto the stack the value of the global <code>name</code>. 3554Returns the type of that value. 3555 3556 3557 3558 3559 3560<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p> 3561<span class="apii">[-0, +1, <em>e</em>]</span> 3562<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre> 3563 3564<p> 3565Pushes onto the stack the value <code>t[i]</code>, 3566where <code>t</code> is the value at the given index. 3567As in Lua, this function may trigger a metamethod 3568for the "index" event (see <a href="#2.4">§2.4</a>). 3569 3570 3571<p> 3572Returns the type of the pushed value. 3573 3574 3575 3576 3577 3578<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p> 3579<span class="apii">[-0, +(0|1), –]</span> 3580<pre>int lua_getmetatable (lua_State *L, int index);</pre> 3581 3582<p> 3583If the value at the given index has a metatable, 3584the function pushes that metatable onto the stack and returns 1. 3585Otherwise, 3586the function returns 0 and pushes nothing on the stack. 3587 3588 3589 3590 3591 3592<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p> 3593<span class="apii">[-1, +1, <em>e</em>]</span> 3594<pre>int lua_gettable (lua_State *L, int index);</pre> 3595 3596<p> 3597Pushes onto the stack the value <code>t[k]</code>, 3598where <code>t</code> is the value at the given index 3599and <code>k</code> is the value at the top of the stack. 3600 3601 3602<p> 3603This function pops the key from the stack, 3604pushing the resulting value in its place. 3605As in Lua, this function may trigger a metamethod 3606for the "index" event (see <a href="#2.4">§2.4</a>). 3607 3608 3609<p> 3610Returns the type of the pushed value. 3611 3612 3613 3614 3615 3616<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p> 3617<span class="apii">[-0, +0, –]</span> 3618<pre>int lua_gettop (lua_State *L);</pre> 3619 3620<p> 3621Returns the index of the top element in the stack. 3622Because indices start at 1, 3623this result is equal to the number of elements in the stack; 3624in particular, 0 means an empty stack. 3625 3626 3627 3628 3629 3630<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p> 3631<span class="apii">[-0, +1, –]</span> 3632<pre>int lua_getuservalue (lua_State *L, int index);</pre> 3633 3634<p> 3635Pushes onto the stack the Lua value associated with the userdata 3636at the given index. 3637 3638 3639<p> 3640Returns the type of the pushed value. 3641 3642 3643 3644 3645 3646<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p> 3647<span class="apii">[-1, +1, –]</span> 3648<pre>void lua_insert (lua_State *L, int index);</pre> 3649 3650<p> 3651Moves the top element into the given valid index, 3652shifting up the elements above this index to open space. 3653This function cannot be called with a pseudo-index, 3654because a pseudo-index is not an actual stack position. 3655 3656 3657 3658 3659 3660<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3> 3661<pre>typedef ... lua_Integer;</pre> 3662 3663<p> 3664The type of integers in Lua. 3665 3666 3667<p> 3668By default this type is <code>long long</code>, 3669(usually a 64-bit two-complement integer), 3670but that can be changed to <code>long</code> or <code>int</code> 3671(usually a 32-bit two-complement integer). 3672(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.) 3673 3674 3675<p> 3676Lua also defines the constants 3677<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>, 3678with the minimum and the maximum values that fit in this type. 3679 3680 3681 3682 3683 3684<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p> 3685<span class="apii">[-0, +0, –]</span> 3686<pre>int lua_isboolean (lua_State *L, int index);</pre> 3687 3688<p> 3689Returns 1 if the value at the given index is a boolean, 3690and 0 otherwise. 3691 3692 3693 3694 3695 3696<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p> 3697<span class="apii">[-0, +0, –]</span> 3698<pre>int lua_iscfunction (lua_State *L, int index);</pre> 3699 3700<p> 3701Returns 1 if the value at the given index is a C function, 3702and 0 otherwise. 3703 3704 3705 3706 3707 3708<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p> 3709<span class="apii">[-0, +0, –]</span> 3710<pre>int lua_isfunction (lua_State *L, int index);</pre> 3711 3712<p> 3713Returns 1 if the value at the given index is a function 3714(either C or Lua), and 0 otherwise. 3715 3716 3717 3718 3719 3720<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p> 3721<span class="apii">[-0, +0, –]</span> 3722<pre>int lua_isinteger (lua_State *L, int index);</pre> 3723 3724<p> 3725Returns 1 if the value at the given index is an integer 3726(that is, the value is a number and is represented as an integer), 3727and 0 otherwise. 3728 3729 3730 3731 3732 3733<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p> 3734<span class="apii">[-0, +0, –]</span> 3735<pre>int lua_islightuserdata (lua_State *L, int index);</pre> 3736 3737<p> 3738Returns 1 if the value at the given index is a light userdata, 3739and 0 otherwise. 3740 3741 3742 3743 3744 3745<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p> 3746<span class="apii">[-0, +0, –]</span> 3747<pre>int lua_isnil (lua_State *L, int index);</pre> 3748 3749<p> 3750Returns 1 if the value at the given index is <b>nil</b>, 3751and 0 otherwise. 3752 3753 3754 3755 3756 3757<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p> 3758<span class="apii">[-0, +0, –]</span> 3759<pre>int lua_isnone (lua_State *L, int index);</pre> 3760 3761<p> 3762Returns 1 if the given index is not valid, 3763and 0 otherwise. 3764 3765 3766 3767 3768 3769<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p> 3770<span class="apii">[-0, +0, –]</span> 3771<pre>int lua_isnoneornil (lua_State *L, int index);</pre> 3772 3773<p> 3774Returns 1 if the given index is not valid 3775or if the value at this index is <b>nil</b>, 3776and 0 otherwise. 3777 3778 3779 3780 3781 3782<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p> 3783<span class="apii">[-0, +0, –]</span> 3784<pre>int lua_isnumber (lua_State *L, int index);</pre> 3785 3786<p> 3787Returns 1 if the value at the given index is a number 3788or a string convertible to a number, 3789and 0 otherwise. 3790 3791 3792 3793 3794 3795<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p> 3796<span class="apii">[-0, +0, –]</span> 3797<pre>int lua_isstring (lua_State *L, int index);</pre> 3798 3799<p> 3800Returns 1 if the value at the given index is a string 3801or a number (which is always convertible to a string), 3802and 0 otherwise. 3803 3804 3805 3806 3807 3808<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p> 3809<span class="apii">[-0, +0, –]</span> 3810<pre>int lua_istable (lua_State *L, int index);</pre> 3811 3812<p> 3813Returns 1 if the value at the given index is a table, 3814and 0 otherwise. 3815 3816 3817 3818 3819 3820<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p> 3821<span class="apii">[-0, +0, –]</span> 3822<pre>int lua_isthread (lua_State *L, int index);</pre> 3823 3824<p> 3825Returns 1 if the value at the given index is a thread, 3826and 0 otherwise. 3827 3828 3829 3830 3831 3832<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p> 3833<span class="apii">[-0, +0, –]</span> 3834<pre>int lua_isuserdata (lua_State *L, int index);</pre> 3835 3836<p> 3837Returns 1 if the value at the given index is a userdata 3838(either full or light), and 0 otherwise. 3839 3840 3841 3842 3843 3844<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p> 3845<span class="apii">[-0, +0, –]</span> 3846<pre>int lua_isyieldable (lua_State *L);</pre> 3847 3848<p> 3849Returns 1 if the given coroutine can yield, 3850and 0 otherwise. 3851 3852 3853 3854 3855 3856<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3> 3857<pre>typedef ... lua_KContext;</pre> 3858 3859<p> 3860The type for continuation-function contexts. 3861It must be a numeric type. 3862This type is defined as <code>intptr_t</code> 3863when <code>intptr_t</code> is available, 3864so that it can store pointers too. 3865Otherwise, it is defined as <code>ptrdiff_t</code>. 3866 3867 3868 3869 3870 3871<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3> 3872<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre> 3873 3874<p> 3875Type for continuation functions (see <a href="#4.7">§4.7</a>). 3876 3877 3878 3879 3880 3881<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p> 3882<span class="apii">[-0, +1, <em>e</em>]</span> 3883<pre>void lua_len (lua_State *L, int index);</pre> 3884 3885<p> 3886Returns the length of the value at the given index. 3887It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>) and 3888may trigger a metamethod for the "length" event (see <a href="#2.4">§2.4</a>). 3889The result is pushed on the stack. 3890 3891 3892 3893 3894 3895<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p> 3896<span class="apii">[-0, +1, –]</span> 3897<pre>int lua_load (lua_State *L, 3898 lua_Reader reader, 3899 void *data, 3900 const char *chunkname, 3901 const char *mode);</pre> 3902 3903<p> 3904Loads a Lua chunk without running it. 3905If there are no errors, 3906<code>lua_load</code> pushes the compiled chunk as a Lua 3907function on top of the stack. 3908Otherwise, it pushes an error message. 3909 3910 3911<p> 3912The return values of <code>lua_load</code> are: 3913 3914<ul> 3915 3916<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li> 3917 3918<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> 3919syntax error during precompilation;</li> 3920 3921<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> 3922memory allocation error;</li> 3923 3924<li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> 3925error while running a <code>__gc</code> metamethod. 3926(This error has no relation with the chunk being loaded. 3927It is generated by the garbage collector.) 3928</li> 3929 3930</ul> 3931 3932<p> 3933The <code>lua_load</code> function uses a user-supplied <code>reader</code> function 3934to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>). 3935The <code>data</code> argument is an opaque value passed to the reader function. 3936 3937 3938<p> 3939The <code>chunkname</code> argument gives a name to the chunk, 3940which is used for error messages and in debug information (see <a href="#4.9">§4.9</a>). 3941 3942 3943<p> 3944<code>lua_load</code> automatically detects whether the chunk is text or binary 3945and loads it accordingly (see program <code>luac</code>). 3946The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>, 3947with the addition that 3948a <code>NULL</code> value is equivalent to the string "<code>bt</code>". 3949 3950 3951<p> 3952<code>lua_load</code> uses the stack internally, 3953so the reader function must always leave the stack 3954unmodified when returning. 3955 3956 3957<p> 3958If the resulting function has upvalues, 3959its first upvalue is set to the value of the global environment 3960stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">§4.5</a>). 3961When loading main chunks, 3962this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>). 3963Other upvalues are initialized with <b>nil</b>. 3964 3965 3966 3967 3968 3969<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p> 3970<span class="apii">[-0, +0, –]</span> 3971<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre> 3972 3973<p> 3974Creates a new thread running in a new, independent state. 3975Returns <code>NULL</code> if it cannot create the thread or the state 3976(due to lack of memory). 3977The argument <code>f</code> is the allocator function; 3978Lua does all memory allocation for this state through this function. 3979The second argument, <code>ud</code>, is an opaque pointer that Lua 3980passes to the allocator in every call. 3981 3982 3983 3984 3985 3986<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p> 3987<span class="apii">[-0, +1, <em>m</em>]</span> 3988<pre>void lua_newtable (lua_State *L);</pre> 3989 3990<p> 3991Creates a new empty table and pushes it onto the stack. 3992It is equivalent to <code>lua_createtable(L, 0, 0)</code>. 3993 3994 3995 3996 3997 3998<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p> 3999<span class="apii">[-0, +1, <em>m</em>]</span> 4000<pre>lua_State *lua_newthread (lua_State *L);</pre> 4001 4002<p> 4003Creates a new thread, pushes it on the stack, 4004and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread. 4005The new thread returned by this function shares with the original thread 4006its global environment, 4007but has an independent execution stack. 4008 4009 4010<p> 4011There is no explicit function to close or to destroy a thread. 4012Threads are subject to garbage collection, 4013like any Lua object. 4014 4015 4016 4017 4018 4019<hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p> 4020<span class="apii">[-0, +1, <em>m</em>]</span> 4021<pre>void *lua_newuserdata (lua_State *L, size_t size);</pre> 4022 4023<p> 4024This function allocates a new block of memory with the given size, 4025pushes onto the stack a new full userdata with the block address, 4026and returns this address. 4027The host program can freely use this memory. 4028 4029 4030 4031 4032 4033<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p> 4034<span class="apii">[-1, +(2|0), <em>e</em>]</span> 4035<pre>int lua_next (lua_State *L, int index);</pre> 4036 4037<p> 4038Pops a key from the stack, 4039and pushes a key–value pair from the table at the given index 4040(the "next" pair after the given key). 4041If there are no more elements in the table, 4042then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing). 4043 4044 4045<p> 4046A typical traversal looks like this: 4047 4048<pre> 4049 /* table is in the stack at index 't' */ 4050 lua_pushnil(L); /* first key */ 4051 while (lua_next(L, t) != 0) { 4052 /* uses 'key' (at index -2) and 'value' (at index -1) */ 4053 printf("%s - %s\n", 4054 lua_typename(L, lua_type(L, -2)), 4055 lua_typename(L, lua_type(L, -1))); 4056 /* removes 'value'; keeps 'key' for next iteration */ 4057 lua_pop(L, 1); 4058 } 4059</pre> 4060 4061<p> 4062While traversing a table, 4063do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key, 4064unless you know that the key is actually a string. 4065Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change 4066the value at the given index; 4067this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>. 4068 4069 4070<p> 4071See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying 4072the table during its traversal. 4073 4074 4075 4076 4077 4078<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3> 4079<pre>typedef ... lua_Number;</pre> 4080 4081<p> 4082The type of floats in Lua. 4083 4084 4085<p> 4086By default this type is double, 4087but that can be changed to a single float or a long double. 4088(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.) 4089 4090 4091 4092 4093 4094<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3> 4095<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre> 4096 4097<p> 4098Converts a Lua float to a Lua integer. 4099This macro assumes that <code>n</code> has an integral value. 4100If that value is within the range of Lua integers, 4101it is converted to an integer and assigned to <code>*p</code>. 4102The macro results in a boolean indicating whether the 4103conversion was successful. 4104(Note that this range test can be tricky to do 4105correctly without this macro, 4106due to roundings.) 4107 4108 4109<p> 4110This macro may evaluate its arguments more than once. 4111 4112 4113 4114 4115 4116<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p> 4117<span class="apii">[-(nargs + 1), +(nresults|1), –]</span> 4118<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre> 4119 4120<p> 4121Calls a function in protected mode. 4122 4123 4124<p> 4125Both <code>nargs</code> and <code>nresults</code> have the same meaning as 4126in <a href="#lua_call"><code>lua_call</code></a>. 4127If there are no errors during the call, 4128<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>. 4129However, if there is any error, 4130<a href="#lua_pcall"><code>lua_pcall</code></a> catches it, 4131pushes a single value on the stack (the error message), 4132and returns an error code. 4133Like <a href="#lua_call"><code>lua_call</code></a>, 4134<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function 4135and its arguments from the stack. 4136 4137 4138<p> 4139If <code>msgh</code> is 0, 4140then the error message returned on the stack 4141is exactly the original error message. 4142Otherwise, <code>msgh</code> is the stack index of a 4143<em>message handler</em>. 4144(This index cannot be a pseudo-index.) 4145In case of runtime errors, 4146this function will be called with the error message 4147and its return value will be the message 4148returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>. 4149 4150 4151<p> 4152Typically, the message handler is used to add more debug 4153information to the error message, such as a stack traceback. 4154Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>, 4155since by then the stack has unwound. 4156 4157 4158<p> 4159The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants 4160(defined in <code>lua.h</code>): 4161 4162<ul> 4163 4164<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> 4165success.</li> 4166 4167<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> 4168a runtime error. 4169</li> 4170 4171<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> 4172memory allocation error. 4173For such errors, Lua does not call the message handler. 4174</li> 4175 4176<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> 4177error while running the message handler. 4178</li> 4179 4180<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> 4181error while running a <code>__gc</code> metamethod. 4182(This error typically has no relation with the function being called.) 4183</li> 4184 4185</ul> 4186 4187 4188 4189 4190<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p> 4191<span class="apii">[-(nargs + 1), +(nresults|1), –]</span> 4192<pre>int lua_pcallk (lua_State *L, 4193 int nargs, 4194 int nresults, 4195 int msgh, 4196 lua_KContext ctx, 4197 lua_KFunction k);</pre> 4198 4199<p> 4200This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>, 4201but allows the called function to yield (see <a href="#4.7">§4.7</a>). 4202 4203 4204 4205 4206 4207<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p> 4208<span class="apii">[-n, +0, –]</span> 4209<pre>void lua_pop (lua_State *L, int n);</pre> 4210 4211<p> 4212Pops <code>n</code> elements from the stack. 4213 4214 4215 4216 4217 4218<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p> 4219<span class="apii">[-0, +1, –]</span> 4220<pre>void lua_pushboolean (lua_State *L, int b);</pre> 4221 4222<p> 4223Pushes a boolean value with value <code>b</code> onto the stack. 4224 4225 4226 4227 4228 4229<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p> 4230<span class="apii">[-n, +1, <em>m</em>]</span> 4231<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre> 4232 4233<p> 4234Pushes a new C closure onto the stack. 4235 4236 4237<p> 4238When a C function is created, 4239it is possible to associate some values with it, 4240thus creating a C closure (see <a href="#4.4">§4.4</a>); 4241these values are then accessible to the function whenever it is called. 4242To associate values with a C function, 4243first these values must be pushed onto the stack 4244(when there are multiple values, the first value is pushed first). 4245Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> 4246is called to create and push the C function onto the stack, 4247with the argument <code>n</code> telling how many values will be 4248associated with the function. 4249<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack. 4250 4251 4252<p> 4253The maximum value for <code>n</code> is 255. 4254 4255 4256<p> 4257When <code>n</code> is zero, 4258this function creates a <em>light C function</em>, 4259which is just a pointer to the C function. 4260In that case, it never raises a memory error. 4261 4262 4263 4264 4265 4266<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p> 4267<span class="apii">[-0, +1, –]</span> 4268<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre> 4269 4270<p> 4271Pushes a C function onto the stack. 4272This function receives a pointer to a C function 4273and pushes onto the stack a Lua value of type <code>function</code> that, 4274when called, invokes the corresponding C function. 4275 4276 4277<p> 4278Any function to be callable by Lua must 4279follow the correct protocol to receive its parameters 4280and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 4281 4282 4283 4284 4285 4286<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p> 4287<span class="apii">[-0, +1, <em>m</em>]</span> 4288<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre> 4289 4290<p> 4291Pushes onto the stack a formatted string 4292and returns a pointer to this string. 4293It is similar to the ISO C function <code>sprintf</code>, 4294but has some important differences: 4295 4296<ul> 4297 4298<li> 4299You do not have to allocate space for the result: 4300the result is a Lua string and Lua takes care of memory allocation 4301(and deallocation, through garbage collection). 4302</li> 4303 4304<li> 4305The conversion specifiers are quite restricted. 4306There are no flags, widths, or precisions. 4307The conversion specifiers can only be 4308'<code>%%</code>' (inserts the character '<code>%</code>'), 4309'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions), 4310'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>), 4311'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>), 4312'<code>%p</code>' (inserts a pointer as a hexadecimal numeral), 4313'<code>%d</code>' (inserts an <code>int</code>), 4314'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and 4315'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence). 4316</li> 4317 4318</ul> 4319 4320 4321 4322 4323<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p> 4324<span class="apii">[-0, +1, –]</span> 4325<pre>void lua_pushglobaltable (lua_State *L);</pre> 4326 4327<p> 4328Pushes the global environment onto the stack. 4329 4330 4331 4332 4333 4334<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p> 4335<span class="apii">[-0, +1, –]</span> 4336<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre> 4337 4338<p> 4339Pushes an integer with value <code>n</code> onto the stack. 4340 4341 4342 4343 4344 4345<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p> 4346<span class="apii">[-0, +1, –]</span> 4347<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre> 4348 4349<p> 4350Pushes a light userdata onto the stack. 4351 4352 4353<p> 4354Userdata represent C values in Lua. 4355A <em>light userdata</em> represents a pointer, a <code>void*</code>. 4356It is a value (like a number): 4357you do not create it, it has no individual metatable, 4358and it is not collected (as it was never created). 4359A light userdata is equal to "any" 4360light userdata with the same C address. 4361 4362 4363 4364 4365 4366<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p> 4367<span class="apii">[-0, +1, <em>m</em>]</span> 4368<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre> 4369 4370<p> 4371This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>, 4372but should be used only when <code>s</code> is a literal string. 4373 4374 4375 4376 4377 4378<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p> 4379<span class="apii">[-0, +1, <em>m</em>]</span> 4380<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre> 4381 4382<p> 4383Pushes the string pointed to by <code>s</code> with size <code>len</code> 4384onto the stack. 4385Lua makes (or reuses) an internal copy of the given string, 4386so the memory at <code>s</code> can be freed or reused immediately after 4387the function returns. 4388The string can contain any binary data, 4389including embedded zeros. 4390 4391 4392<p> 4393Returns a pointer to the internal copy of the string. 4394 4395 4396 4397 4398 4399<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p> 4400<span class="apii">[-0, +1, –]</span> 4401<pre>void lua_pushnil (lua_State *L);</pre> 4402 4403<p> 4404Pushes a nil value onto the stack. 4405 4406 4407 4408 4409 4410<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p> 4411<span class="apii">[-0, +1, –]</span> 4412<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre> 4413 4414<p> 4415Pushes a float with value <code>n</code> onto the stack. 4416 4417 4418 4419 4420 4421<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p> 4422<span class="apii">[-0, +1, <em>m</em>]</span> 4423<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre> 4424 4425<p> 4426Pushes the zero-terminated string pointed to by <code>s</code> 4427onto the stack. 4428Lua makes (or reuses) an internal copy of the given string, 4429so the memory at <code>s</code> can be freed or reused immediately after 4430the function returns. 4431 4432 4433<p> 4434Returns a pointer to the internal copy of the string. 4435 4436 4437<p> 4438If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>. 4439 4440 4441 4442 4443 4444<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p> 4445<span class="apii">[-0, +1, –]</span> 4446<pre>int lua_pushthread (lua_State *L);</pre> 4447 4448<p> 4449Pushes the thread represented by <code>L</code> onto the stack. 4450Returns 1 if this thread is the main thread of its state. 4451 4452 4453 4454 4455 4456<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p> 4457<span class="apii">[-0, +1, –]</span> 4458<pre>void lua_pushvalue (lua_State *L, int index);</pre> 4459 4460<p> 4461Pushes a copy of the element at the given index 4462onto the stack. 4463 4464 4465 4466 4467 4468<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p> 4469<span class="apii">[-0, +1, <em>m</em>]</span> 4470<pre>const char *lua_pushvfstring (lua_State *L, 4471 const char *fmt, 4472 va_list argp);</pre> 4473 4474<p> 4475Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code> 4476instead of a variable number of arguments. 4477 4478 4479 4480 4481 4482<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p> 4483<span class="apii">[-0, +0, –]</span> 4484<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre> 4485 4486<p> 4487Returns 1 if the two values in indices <code>index1</code> and 4488<code>index2</code> are primitively equal 4489(that is, without calling metamethods). 4490Otherwise returns 0. 4491Also returns 0 if any of the indices are not valid. 4492 4493 4494 4495 4496 4497<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p> 4498<span class="apii">[-1, +1, –]</span> 4499<pre>int lua_rawget (lua_State *L, int index);</pre> 4500 4501<p> 4502Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access 4503(i.e., without metamethods). 4504 4505 4506 4507 4508 4509<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p> 4510<span class="apii">[-0, +1, –]</span> 4511<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre> 4512 4513<p> 4514Pushes onto the stack the value <code>t[n]</code>, 4515where <code>t</code> is the table at the given index. 4516The access is raw; 4517that is, it does not invoke metamethods. 4518 4519 4520<p> 4521Returns the type of the pushed value. 4522 4523 4524 4525 4526 4527<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p> 4528<span class="apii">[-0, +1, –]</span> 4529<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre> 4530 4531<p> 4532Pushes onto the stack the value <code>t[k]</code>, 4533where <code>t</code> is the table at the given index and 4534<code>k</code> is the pointer <code>p</code> represented as a light userdata. 4535The access is raw; 4536that is, it does not invoke metamethods. 4537 4538 4539<p> 4540Returns the type of the pushed value. 4541 4542 4543 4544 4545 4546<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p> 4547<span class="apii">[-0, +0, –]</span> 4548<pre>size_t lua_rawlen (lua_State *L, int index);</pre> 4549 4550<p> 4551Returns the raw "length" of the value at the given index: 4552for strings, this is the string length; 4553for tables, this is the result of the length operator ('<code>#</code>') 4554with no metamethods; 4555for userdata, this is the size of the block of memory allocated 4556for the userdata; 4557for other values, it is 0. 4558 4559 4560 4561 4562 4563<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p> 4564<span class="apii">[-2, +0, <em>m</em>]</span> 4565<pre>void lua_rawset (lua_State *L, int index);</pre> 4566 4567<p> 4568Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment 4569(i.e., without metamethods). 4570 4571 4572 4573 4574 4575<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p> 4576<span class="apii">[-1, +0, <em>m</em>]</span> 4577<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre> 4578 4579<p> 4580Does the equivalent of <code>t[i] = v</code>, 4581where <code>t</code> is the table at the given index 4582and <code>v</code> is the value at the top of the stack. 4583 4584 4585<p> 4586This function pops the value from the stack. 4587The assignment is raw; 4588that is, it does not invoke metamethods. 4589 4590 4591 4592 4593 4594<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p> 4595<span class="apii">[-1, +0, <em>m</em>]</span> 4596<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre> 4597 4598<p> 4599Does the equivalent of <code>t[p] = v</code>, 4600where <code>t</code> is the table at the given index, 4601<code>p</code> is encoded as a light userdata, 4602and <code>v</code> is the value at the top of the stack. 4603 4604 4605<p> 4606This function pops the value from the stack. 4607The assignment is raw; 4608that is, it does not invoke metamethods. 4609 4610 4611 4612 4613 4614<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3> 4615<pre>typedef const char * (*lua_Reader) (lua_State *L, 4616 void *data, 4617 size_t *size);</pre> 4618 4619<p> 4620The reader function used by <a href="#lua_load"><code>lua_load</code></a>. 4621Every time it needs another piece of the chunk, 4622<a href="#lua_load"><code>lua_load</code></a> calls the reader, 4623passing along its <code>data</code> parameter. 4624The reader must return a pointer to a block of memory 4625with a new piece of the chunk 4626and set <code>size</code> to the block size. 4627The block must exist until the reader function is called again. 4628To signal the end of the chunk, 4629the reader must return <code>NULL</code> or set <code>size</code> to zero. 4630The reader function may return pieces of any size greater than zero. 4631 4632 4633 4634 4635 4636<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p> 4637<span class="apii">[-0, +0, <em>e</em>]</span> 4638<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre> 4639 4640<p> 4641Sets the C function <code>f</code> as the new value of global <code>name</code>. 4642It is defined as a macro: 4643 4644<pre> 4645 #define lua_register(L,n,f) \ 4646 (lua_pushcfunction(L, f), lua_setglobal(L, n)) 4647</pre> 4648 4649 4650 4651 4652<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p> 4653<span class="apii">[-1, +0, –]</span> 4654<pre>void lua_remove (lua_State *L, int index);</pre> 4655 4656<p> 4657Removes the element at the given valid index, 4658shifting down the elements above this index to fill the gap. 4659This function cannot be called with a pseudo-index, 4660because a pseudo-index is not an actual stack position. 4661 4662 4663 4664 4665 4666<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p> 4667<span class="apii">[-1, +0, –]</span> 4668<pre>void lua_replace (lua_State *L, int index);</pre> 4669 4670<p> 4671Moves the top element into the given valid index 4672without shifting any element 4673(therefore replacing the value at that given index), 4674and then pops the top element. 4675 4676 4677 4678 4679 4680<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p> 4681<span class="apii">[-?, +?, –]</span> 4682<pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre> 4683 4684<p> 4685Starts and resumes a coroutine in the given thread <code>L</code>. 4686 4687 4688<p> 4689To start a coroutine, 4690you push onto the thread stack the main function plus any arguments; 4691then you call <a href="#lua_resume"><code>lua_resume</code></a>, 4692with <code>nargs</code> being the number of arguments. 4693This call returns when the coroutine suspends or finishes its execution. 4694When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>, 4695or all values returned by the body function. 4696<a href="#lua_resume"><code>lua_resume</code></a> returns 4697<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields, 4698<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution 4699without errors, 4700or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>). 4701 4702 4703<p> 4704In case of errors, 4705the stack is not unwound, 4706so you can use the debug API over it. 4707The error message is on the top of the stack. 4708 4709 4710<p> 4711To resume a coroutine, 4712you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>, 4713put on its stack only the values to 4714be passed as results from <code>yield</code>, 4715and then call <a href="#lua_resume"><code>lua_resume</code></a>. 4716 4717 4718<p> 4719The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>. 4720If there is no such coroutine, 4721this parameter can be <code>NULL</code>. 4722 4723 4724 4725 4726 4727<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p> 4728<span class="apii">[-0, +0, –]</span> 4729<pre>void lua_rotate (lua_State *L, int idx, int n);</pre> 4730 4731<p> 4732Rotates the stack elements between the valid index <code>idx</code> 4733and the top of the stack. 4734The elements are rotated <code>n</code> positions in the direction of the top, 4735for a positive <code>n</code>, 4736or <code>-n</code> positions in the direction of the bottom, 4737for a negative <code>n</code>. 4738The absolute value of <code>n</code> must not be greater than the size 4739of the slice being rotated. 4740This function cannot be called with a pseudo-index, 4741because a pseudo-index is not an actual stack position. 4742 4743 4744 4745 4746 4747<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p> 4748<span class="apii">[-0, +0, –]</span> 4749<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre> 4750 4751<p> 4752Changes the allocator function of a given state to <code>f</code> 4753with user data <code>ud</code>. 4754 4755 4756 4757 4758 4759<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p> 4760<span class="apii">[-1, +0, <em>e</em>]</span> 4761<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre> 4762 4763<p> 4764Does the equivalent to <code>t[k] = v</code>, 4765where <code>t</code> is the value at the given index 4766and <code>v</code> is the value at the top of the stack. 4767 4768 4769<p> 4770This function pops the value from the stack. 4771As in Lua, this function may trigger a metamethod 4772for the "newindex" event (see <a href="#2.4">§2.4</a>). 4773 4774 4775 4776 4777 4778<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p> 4779<span class="apii">[-1, +0, <em>e</em>]</span> 4780<pre>void lua_setglobal (lua_State *L, const char *name);</pre> 4781 4782<p> 4783Pops a value from the stack and 4784sets it as the new value of global <code>name</code>. 4785 4786 4787 4788 4789 4790<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p> 4791<span class="apii">[-1, +0, <em>e</em>]</span> 4792<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre> 4793 4794<p> 4795Does the equivalent to <code>t[n] = v</code>, 4796where <code>t</code> is the value at the given index 4797and <code>v</code> is the value at the top of the stack. 4798 4799 4800<p> 4801This function pops the value from the stack. 4802As in Lua, this function may trigger a metamethod 4803for the "newindex" event (see <a href="#2.4">§2.4</a>). 4804 4805 4806 4807 4808 4809<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p> 4810<span class="apii">[-1, +0, –]</span> 4811<pre>void lua_setmetatable (lua_State *L, int index);</pre> 4812 4813<p> 4814Pops a table from the stack and 4815sets it as the new metatable for the value at the given index. 4816 4817 4818 4819 4820 4821<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p> 4822<span class="apii">[-2, +0, <em>e</em>]</span> 4823<pre>void lua_settable (lua_State *L, int index);</pre> 4824 4825<p> 4826Does the equivalent to <code>t[k] = v</code>, 4827where <code>t</code> is the value at the given index, 4828<code>v</code> is the value at the top of the stack, 4829and <code>k</code> is the value just below the top. 4830 4831 4832<p> 4833This function pops both the key and the value from the stack. 4834As in Lua, this function may trigger a metamethod 4835for the "newindex" event (see <a href="#2.4">§2.4</a>). 4836 4837 4838 4839 4840 4841<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p> 4842<span class="apii">[-?, +?, –]</span> 4843<pre>void lua_settop (lua_State *L, int index);</pre> 4844 4845<p> 4846Accepts any index, or 0, 4847and sets the stack top to this index. 4848If the new top is larger than the old one, 4849then the new elements are filled with <b>nil</b>. 4850If <code>index</code> is 0, then all stack elements are removed. 4851 4852 4853 4854 4855 4856<hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p> 4857<span class="apii">[-1, +0, –]</span> 4858<pre>void lua_setuservalue (lua_State *L, int index);</pre> 4859 4860<p> 4861Pops a value from the stack and sets it as 4862the new value associated to the userdata at the given index. 4863 4864 4865 4866 4867 4868<hr><h3><a name="lua_State"><code>lua_State</code></a></h3> 4869<pre>typedef struct lua_State lua_State;</pre> 4870 4871<p> 4872An opaque structure that points to a thread and indirectly 4873(through the thread) to the whole state of a Lua interpreter. 4874The Lua library is fully reentrant: 4875it has no global variables. 4876All information about a state is accessible through this structure. 4877 4878 4879<p> 4880A pointer to this structure must be passed as the first argument to 4881every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>, 4882which creates a Lua state from scratch. 4883 4884 4885 4886 4887 4888<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p> 4889<span class="apii">[-0, +0, –]</span> 4890<pre>int lua_status (lua_State *L);</pre> 4891 4892<p> 4893Returns the status of the thread <code>L</code>. 4894 4895 4896<p> 4897The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread, 4898an error code if the thread finished the execution 4899of a <a href="#lua_resume"><code>lua_resume</code></a> with an error, 4900or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended. 4901 4902 4903<p> 4904You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>. 4905You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> 4906(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> 4907(to resume a coroutine). 4908 4909 4910 4911 4912 4913<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p> 4914<span class="apii">[-0, +1, –]</span> 4915<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre> 4916 4917<p> 4918Converts the zero-terminated string <code>s</code> to a number, 4919pushes that number into the stack, 4920and returns the total size of the string, 4921that is, its length plus one. 4922The conversion can result in an integer or a float, 4923according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>). 4924The string may have leading and trailing spaces and a sign. 4925If the string is not a valid numeral, 4926returns 0 and pushes nothing. 4927(Note that the result can be used as a boolean, 4928true if the conversion succeeds.) 4929 4930 4931 4932 4933 4934<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p> 4935<span class="apii">[-0, +0, –]</span> 4936<pre>int lua_toboolean (lua_State *L, int index);</pre> 4937 4938<p> 4939Converts the Lua value at the given index to a C boolean 4940value (0 or 1). 4941Like all tests in Lua, 4942<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value 4943different from <b>false</b> and <b>nil</b>; 4944otherwise it returns false. 4945(If you want to accept only actual boolean values, 4946use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.) 4947 4948 4949 4950 4951 4952<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p> 4953<span class="apii">[-0, +0, –]</span> 4954<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre> 4955 4956<p> 4957Converts a value at the given index to a C function. 4958That value must be a C function; 4959otherwise, returns <code>NULL</code>. 4960 4961 4962 4963 4964 4965<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p> 4966<span class="apii">[-0, +0, –]</span> 4967<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre> 4968 4969<p> 4970Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>. 4971 4972 4973 4974 4975 4976<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p> 4977<span class="apii">[-0, +0, –]</span> 4978<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre> 4979 4980<p> 4981Converts the Lua value at the given index 4982to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>. 4983The Lua value must be an integer, 4984or a number or string convertible to an integer (see <a href="#3.4.3">§3.4.3</a>); 4985otherwise, <code>lua_tointegerx</code> returns 0. 4986 4987 4988<p> 4989If <code>isnum</code> is not <code>NULL</code>, 4990its referent is assigned a boolean value that 4991indicates whether the operation succeeded. 4992 4993 4994 4995 4996 4997<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p> 4998<span class="apii">[-0, +0, <em>m</em>]</span> 4999<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre> 5000 5001<p> 5002Converts the Lua value at the given index to a C string. 5003If <code>len</code> is not <code>NULL</code>, 5004it sets <code>*len</code> with the string length. 5005The Lua value must be a string or a number; 5006otherwise, the function returns <code>NULL</code>. 5007If the value is a number, 5008then <code>lua_tolstring</code> also 5009<em>changes the actual value in the stack to a string</em>. 5010(This change confuses <a href="#lua_next"><code>lua_next</code></a> 5011when <code>lua_tolstring</code> is applied to keys during a table traversal.) 5012 5013 5014<p> 5015<code>lua_tolstring</code> returns a pointer 5016to a string inside the Lua state. 5017This string always has a zero ('<code>\0</code>') 5018after its last character (as in C), 5019but can contain other zeros in its body. 5020 5021 5022<p> 5023Because Lua has garbage collection, 5024there is no guarantee that the pointer returned by <code>lua_tolstring</code> 5025will be valid after the corresponding Lua value is removed from the stack. 5026 5027 5028 5029 5030 5031<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p> 5032<span class="apii">[-0, +0, –]</span> 5033<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre> 5034 5035<p> 5036Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>. 5037 5038 5039 5040 5041 5042<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p> 5043<span class="apii">[-0, +0, –]</span> 5044<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre> 5045 5046<p> 5047Converts the Lua value at the given index 5048to the C type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>). 5049The Lua value must be a number or a string convertible to a number 5050(see <a href="#3.4.3">§3.4.3</a>); 5051otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns 0. 5052 5053 5054<p> 5055If <code>isnum</code> is not <code>NULL</code>, 5056its referent is assigned a boolean value that 5057indicates whether the operation succeeded. 5058 5059 5060 5061 5062 5063<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p> 5064<span class="apii">[-0, +0, –]</span> 5065<pre>const void *lua_topointer (lua_State *L, int index);</pre> 5066 5067<p> 5068Converts the value at the given index to a generic 5069C pointer (<code>void*</code>). 5070The value can be a userdata, a table, a thread, or a function; 5071otherwise, <code>lua_topointer</code> returns <code>NULL</code>. 5072Different objects will give different pointers. 5073There is no way to convert the pointer back to its original value. 5074 5075 5076<p> 5077Typically this function is used only for hashing and debug information. 5078 5079 5080 5081 5082 5083<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p> 5084<span class="apii">[-0, +0, <em>m</em>]</span> 5085<pre>const char *lua_tostring (lua_State *L, int index);</pre> 5086 5087<p> 5088Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>. 5089 5090 5091 5092 5093 5094<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p> 5095<span class="apii">[-0, +0, –]</span> 5096<pre>lua_State *lua_tothread (lua_State *L, int index);</pre> 5097 5098<p> 5099Converts the value at the given index to a Lua thread 5100(represented as <code>lua_State*</code>). 5101This value must be a thread; 5102otherwise, the function returns <code>NULL</code>. 5103 5104 5105 5106 5107 5108<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p> 5109<span class="apii">[-0, +0, –]</span> 5110<pre>void *lua_touserdata (lua_State *L, int index);</pre> 5111 5112<p> 5113If the value at the given index is a full userdata, 5114returns its block address. 5115If the value is a light userdata, 5116returns its pointer. 5117Otherwise, returns <code>NULL</code>. 5118 5119 5120 5121 5122 5123<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p> 5124<span class="apii">[-0, +0, –]</span> 5125<pre>int lua_type (lua_State *L, int index);</pre> 5126 5127<p> 5128Returns the type of the value in the given valid index, 5129or <code>LUA_TNONE</code> for a non-valid (but acceptable) index. 5130The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants 5131defined in <code>lua.h</code>: 5132<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a> (0), 5133<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>, 5134<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>, 5135<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, 5136<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, 5137<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>, 5138<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, 5139<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>, 5140and 5141<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>. 5142 5143 5144 5145 5146 5147<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p> 5148<span class="apii">[-0, +0, –]</span> 5149<pre>const char *lua_typename (lua_State *L, int tp);</pre> 5150 5151<p> 5152Returns the name of the type encoded by the value <code>tp</code>, 5153which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>. 5154 5155 5156 5157 5158 5159<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3> 5160<pre>typedef ... lua_Unsigned;</pre> 5161 5162<p> 5163The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>. 5164 5165 5166 5167 5168 5169<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p> 5170<span class="apii">[-0, +0, –]</span> 5171<pre>int lua_upvalueindex (int i);</pre> 5172 5173<p> 5174Returns the pseudo-index that represents the <code>i</code>-th upvalue of 5175the running function (see <a href="#4.4">§4.4</a>). 5176 5177 5178 5179 5180 5181<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p> 5182<span class="apii">[-0, +0, <em>v</em>]</span> 5183<pre>const lua_Number *lua_version (lua_State *L);</pre> 5184 5185<p> 5186Returns the address of the version number stored in the Lua core. 5187When called with a valid <a href="#lua_State"><code>lua_State</code></a>, 5188returns the address of the version used to create that state. 5189When called with <code>NULL</code>, 5190returns the address of the version running the call. 5191 5192 5193 5194 5195 5196<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3> 5197<pre>typedef int (*lua_Writer) (lua_State *L, 5198 const void* p, 5199 size_t sz, 5200 void* ud);</pre> 5201 5202<p> 5203The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>. 5204Every time it produces another piece of chunk, 5205<a href="#lua_dump"><code>lua_dump</code></a> calls the writer, 5206passing along the buffer to be written (<code>p</code>), 5207its size (<code>sz</code>), 5208and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>. 5209 5210 5211<p> 5212The writer returns an error code: 52130 means no errors; 5214any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from 5215calling the writer again. 5216 5217 5218 5219 5220 5221<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p> 5222<span class="apii">[-?, +?, –]</span> 5223<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre> 5224 5225<p> 5226Exchange values between different threads of the same state. 5227 5228 5229<p> 5230This function pops <code>n</code> values from the stack <code>from</code>, 5231and pushes them onto the stack <code>to</code>. 5232 5233 5234 5235 5236 5237<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p> 5238<span class="apii">[-?, +?, <em>e</em>]</span> 5239<pre>int lua_yield (lua_State *L, int nresults);</pre> 5240 5241<p> 5242This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5243but it has no continuation (see <a href="#4.7">§4.7</a>). 5244Therefore, when the thread resumes, 5245it continues the function that called 5246the function calling <code>lua_yield</code>. 5247 5248 5249 5250 5251 5252<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p> 5253<span class="apii">[-?, +?, <em>e</em>]</span> 5254<pre>int lua_yieldk (lua_State *L, 5255 int nresults, 5256 lua_KContext ctx, 5257 lua_KFunction k);</pre> 5258 5259<p> 5260Yields a coroutine (thread). 5261 5262 5263<p> 5264When a C function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5265the running coroutine suspends its execution, 5266and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns. 5267The parameter <code>nresults</code> is the number of values from the stack 5268that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>. 5269 5270 5271<p> 5272When the coroutine is resumed again, 5273Lua calls the given continuation function <code>k</code> to continue 5274the execution of the C function that yielded (see <a href="#4.7">§4.7</a>). 5275This continuation function receives the same stack 5276from the previous function, 5277with the <code>n</code> results removed and 5278replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>. 5279Moreover, 5280the continuation function receives the value <code>ctx</code> 5281that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>. 5282 5283 5284<p> 5285Usually, this function does not return; 5286when the coroutine eventually resumes, 5287it continues executing the continuation function. 5288However, there is one special case, 5289which is when this function is called 5290from inside a line hook (see <a href="#4.9">§4.9</a>). 5291In that case, <code>lua_yieldk</code> should be called with no continuation 5292(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>), 5293and the hook should return immediately after the call. 5294Lua will yield and, 5295when the coroutine resumes again, 5296it will continue the normal execution 5297of the (Lua) function that triggered the hook. 5298 5299 5300<p> 5301This function can raise an error if it is called from a thread 5302with a pending C call with no continuation function, 5303or it is called from a thread that is not running inside a resume 5304(e.g., the main thread). 5305 5306 5307 5308 5309 5310 5311 5312<h2>4.9 – <a name="4.9">The Debug Interface</a></h2> 5313 5314<p> 5315Lua has no built-in debugging facilities. 5316Instead, it offers a special interface 5317by means of functions and <em>hooks</em>. 5318This interface allows the construction of different 5319kinds of debuggers, profilers, and other tools 5320that need "inside information" from the interpreter. 5321 5322 5323 5324<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3> 5325<pre>typedef struct lua_Debug { 5326 int event; 5327 const char *name; /* (n) */ 5328 const char *namewhat; /* (n) */ 5329 const char *what; /* (S) */ 5330 const char *source; /* (S) */ 5331 int currentline; /* (l) */ 5332 int linedefined; /* (S) */ 5333 int lastlinedefined; /* (S) */ 5334 unsigned char nups; /* (u) number of upvalues */ 5335 unsigned char nparams; /* (u) number of parameters */ 5336 char isvararg; /* (u) */ 5337 char istailcall; /* (t) */ 5338 char short_src[LUA_IDSIZE]; /* (S) */ 5339 /* private part */ 5340 <em>other fields</em> 5341} lua_Debug;</pre> 5342 5343<p> 5344A structure used to carry different pieces of 5345information about a function or an activation record. 5346<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part 5347of this structure, for later use. 5348To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information, 5349call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. 5350 5351 5352<p> 5353The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning: 5354 5355<ul> 5356 5357<li><b><code>source</code>: </b> 5358the name of the chunk that created the function. 5359If <code>source</code> starts with a '<code>@</code>', 5360it means that the function was defined in a file where 5361the file name follows the '<code>@</code>'. 5362If <code>source</code> starts with a '<code>=</code>', 5363the remainder of its contents describe the source in a user-dependent manner. 5364Otherwise, 5365the function was defined in a string where 5366<code>source</code> is that string. 5367</li> 5368 5369<li><b><code>short_src</code>: </b> 5370a "printable" version of <code>source</code>, to be used in error messages. 5371</li> 5372 5373<li><b><code>linedefined</code>: </b> 5374the line number where the definition of the function starts. 5375</li> 5376 5377<li><b><code>lastlinedefined</code>: </b> 5378the line number where the definition of the function ends. 5379</li> 5380 5381<li><b><code>what</code>: </b> 5382the string <code>"Lua"</code> if the function is a Lua function, 5383<code>"C"</code> if it is a C function, 5384<code>"main"</code> if it is the main part of a chunk. 5385</li> 5386 5387<li><b><code>currentline</code>: </b> 5388the current line where the given function is executing. 5389When no line information is available, 5390<code>currentline</code> is set to -1. 5391</li> 5392 5393<li><b><code>name</code>: </b> 5394a reasonable name for the given function. 5395Because functions in Lua are first-class values, 5396they do not have a fixed name: 5397some functions can be the value of multiple global variables, 5398while others can be stored only in a table field. 5399The <code>lua_getinfo</code> function checks how the function was 5400called to find a suitable name. 5401If it cannot find a name, 5402then <code>name</code> is set to <code>NULL</code>. 5403</li> 5404 5405<li><b><code>namewhat</code>: </b> 5406explains the <code>name</code> field. 5407The value of <code>namewhat</code> can be 5408<code>"global"</code>, <code>"local"</code>, <code>"method"</code>, 5409<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string), 5410according to how the function was called. 5411(Lua uses the empty string when no other option seems to apply.) 5412</li> 5413 5414<li><b><code>istailcall</code>: </b> 5415true if this function invocation was called by a tail call. 5416In this case, the caller of this level is not in the stack. 5417</li> 5418 5419<li><b><code>nups</code>: </b> 5420the number of upvalues of the function. 5421</li> 5422 5423<li><b><code>nparams</code>: </b> 5424the number of fixed parameters of the function 5425(always 0 for C functions). 5426</li> 5427 5428<li><b><code>isvararg</code>: </b> 5429true if the function is a vararg function 5430(always true for C functions). 5431</li> 5432 5433</ul> 5434 5435 5436 5437 5438<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p> 5439<span class="apii">[-0, +0, –]</span> 5440<pre>lua_Hook lua_gethook (lua_State *L);</pre> 5441 5442<p> 5443Returns the current hook function. 5444 5445 5446 5447 5448 5449<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p> 5450<span class="apii">[-0, +0, –]</span> 5451<pre>int lua_gethookcount (lua_State *L);</pre> 5452 5453<p> 5454Returns the current hook count. 5455 5456 5457 5458 5459 5460<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p> 5461<span class="apii">[-0, +0, –]</span> 5462<pre>int lua_gethookmask (lua_State *L);</pre> 5463 5464<p> 5465Returns the current hook mask. 5466 5467 5468 5469 5470 5471<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p> 5472<span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span> 5473<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre> 5474 5475<p> 5476Gets information about a specific function or function invocation. 5477 5478 5479<p> 5480To get information about a function invocation, 5481the parameter <code>ar</code> must be a valid activation record that was 5482filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or 5483given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). 5484 5485 5486<p> 5487To get information about a function you push it onto the stack 5488and start the <code>what</code> string with the character '<code>></code>'. 5489(In that case, 5490<code>lua_getinfo</code> pops the function from the top of the stack.) 5491For instance, to know in which line a function <code>f</code> was defined, 5492you can write the following code: 5493 5494<pre> 5495 lua_Debug ar; 5496 lua_getglobal(L, "f"); /* get global 'f' */ 5497 lua_getinfo(L, ">S", &ar); 5498 printf("%d\n", ar.linedefined); 5499</pre> 5500 5501<p> 5502Each character in the string <code>what</code> 5503selects some fields of the structure <code>ar</code> to be filled or 5504a value to be pushed on the stack: 5505 5506<ul> 5507 5508<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>; 5509</li> 5510 5511<li><b>'<code>S</code>': </b> 5512fills in the fields <code>source</code>, <code>short_src</code>, 5513<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>; 5514</li> 5515 5516<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>; 5517</li> 5518 5519<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>; 5520</li> 5521 5522<li><b>'<code>u</code>': </b> fills in the fields 5523<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>; 5524</li> 5525 5526<li><b>'<code>f</code>': </b> 5527pushes onto the stack the function that is 5528running at the given level; 5529</li> 5530 5531<li><b>'<code>L</code>': </b> 5532pushes onto the stack a table whose indices are the 5533numbers of the lines that are valid on the function. 5534(A <em>valid line</em> is a line with some associated code, 5535that is, a line where you can put a break point. 5536Non-valid lines include empty lines and comments.) 5537 5538 5539<p> 5540If this option is given together with option '<code>f</code>', 5541its table is pushed after the function. 5542</li> 5543 5544</ul> 5545 5546<p> 5547This function returns 0 on error 5548(for instance, an invalid option in <code>what</code>). 5549 5550 5551 5552 5553 5554<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p> 5555<span class="apii">[-0, +(0|1), –]</span> 5556<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre> 5557 5558<p> 5559Gets information about a local variable of 5560a given activation record or a given function. 5561 5562 5563<p> 5564In the first case, 5565the parameter <code>ar</code> must be a valid activation record that was 5566filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or 5567given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). 5568The index <code>n</code> selects which local variable to inspect; 5569see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices 5570and names. 5571 5572 5573<p> 5574<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack 5575and returns its name. 5576 5577 5578<p> 5579In the second case, <code>ar</code> must be <code>NULL</code> and the function 5580to be inspected must be at the top of the stack. 5581In this case, only parameters of Lua functions are visible 5582(as there is no information about what variables are active) 5583and no values are pushed onto the stack. 5584 5585 5586<p> 5587Returns <code>NULL</code> (and pushes nothing) 5588when the index is greater than 5589the number of active local variables. 5590 5591 5592 5593 5594 5595<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p> 5596<span class="apii">[-0, +0, –]</span> 5597<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre> 5598 5599<p> 5600Gets information about the interpreter runtime stack. 5601 5602 5603<p> 5604This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with 5605an identification of the <em>activation record</em> 5606of the function executing at a given level. 5607Level 0 is the current running function, 5608whereas level <em>n+1</em> is the function that has called level <em>n</em> 5609(except for tail calls, which do not count on the stack). 5610When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1; 5611when called with a level greater than the stack depth, 5612it returns 0. 5613 5614 5615 5616 5617 5618<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p> 5619<span class="apii">[-0, +(0|1), –]</span> 5620<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre> 5621 5622<p> 5623Gets information about the <code>n</code>-th upvalue 5624of the closure at index <code>funcindex</code>. 5625It pushes the upvalue's value onto the stack 5626and returns its name. 5627Returns <code>NULL</code> (and pushes nothing) 5628when the index <code>n</code> is greater than the number of upvalues. 5629 5630 5631<p> 5632For C functions, this function uses the empty string <code>""</code> 5633as a name for all upvalues. 5634(For Lua functions, 5635upvalues are the external local variables that the function uses, 5636and that are consequently included in its closure.) 5637 5638 5639<p> 5640Upvalues have no particular order, 5641as they are active through the whole function. 5642They are numbered in an arbitrary order. 5643 5644 5645 5646 5647 5648<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3> 5649<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre> 5650 5651<p> 5652Type for debugging hook functions. 5653 5654 5655<p> 5656Whenever a hook is called, its <code>ar</code> argument has its field 5657<code>event</code> set to the specific event that triggered the hook. 5658Lua identifies these events with the following constants: 5659<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>, 5660<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>, 5661and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>. 5662Moreover, for line events, the field <code>currentline</code> is also set. 5663To get the value of any other field in <code>ar</code>, 5664the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. 5665 5666 5667<p> 5668For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>, 5669the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call; 5670in this case, there will be no corresponding return event. 5671 5672 5673<p> 5674While Lua is running a hook, it disables other calls to hooks. 5675Therefore, if a hook calls back Lua to execute a function or a chunk, 5676this execution occurs without any calls to hooks. 5677 5678 5679<p> 5680Hook functions cannot have continuations, 5681that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>, 5682<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>. 5683 5684 5685<p> 5686Hook functions can yield under the following conditions: 5687Only count and line events can yield; 5688to yield, a hook function must finish its execution 5689calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero 5690(that is, with no values). 5691 5692 5693 5694 5695 5696<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p> 5697<span class="apii">[-0, +0, –]</span> 5698<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre> 5699 5700<p> 5701Sets the debugging hook function. 5702 5703 5704<p> 5705Argument <code>f</code> is the hook function. 5706<code>mask</code> specifies on which events the hook will be called: 5707it is formed by a bitwise or of the constants 5708<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>, 5709<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>, 5710<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>, 5711and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>. 5712The <code>count</code> argument is only meaningful when the mask 5713includes <code>LUA_MASKCOUNT</code>. 5714For each event, the hook is called as explained below: 5715 5716<ul> 5717 5718<li><b>The call hook: </b> is called when the interpreter calls a function. 5719The hook is called just after Lua enters the new function, 5720before the function gets its arguments. 5721</li> 5722 5723<li><b>The return hook: </b> is called when the interpreter returns from a function. 5724The hook is called just before Lua leaves the function. 5725There is no standard way to access the values 5726to be returned by the function. 5727</li> 5728 5729<li><b>The line hook: </b> is called when the interpreter is about to 5730start the execution of a new line of code, 5731or when it jumps back in the code (even to the same line). 5732(This event only happens while Lua is executing a Lua function.) 5733</li> 5734 5735<li><b>The count hook: </b> is called after the interpreter executes every 5736<code>count</code> instructions. 5737(This event only happens while Lua is executing a Lua function.) 5738</li> 5739 5740</ul> 5741 5742<p> 5743A hook is disabled by setting <code>mask</code> to zero. 5744 5745 5746 5747 5748 5749<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p> 5750<span class="apii">[-(0|1), +0, –]</span> 5751<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre> 5752 5753<p> 5754Sets the value of a local variable of a given activation record. 5755It assigns the value at the top of the stack 5756to the variable and returns its name. 5757It also pops the value from the stack. 5758 5759 5760<p> 5761Returns <code>NULL</code> (and pops nothing) 5762when the index is greater than 5763the number of active local variables. 5764 5765 5766<p> 5767Parameters <code>ar</code> and <code>n</code> are as in function <a href="#lua_getlocal"><code>lua_getlocal</code></a>. 5768 5769 5770 5771 5772 5773<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p> 5774<span class="apii">[-(0|1), +0, –]</span> 5775<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre> 5776 5777<p> 5778Sets the value of a closure's upvalue. 5779It assigns the value at the top of the stack 5780to the upvalue and returns its name. 5781It also pops the value from the stack. 5782 5783 5784<p> 5785Returns <code>NULL</code> (and pops nothing) 5786when the index <code>n</code> is greater than the number of upvalues. 5787 5788 5789<p> 5790Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>. 5791 5792 5793 5794 5795 5796<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p> 5797<span class="apii">[-0, +0, –]</span> 5798<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre> 5799 5800<p> 5801Returns a unique identifier for the upvalue numbered <code>n</code> 5802from the closure at index <code>funcindex</code>. 5803 5804 5805<p> 5806These unique identifiers allow a program to check whether different 5807closures share upvalues. 5808Lua closures that share an upvalue 5809(that is, that access a same external local variable) 5810will return identical ids for those upvalue indices. 5811 5812 5813<p> 5814Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>, 5815but <code>n</code> cannot be greater than the number of upvalues. 5816 5817 5818 5819 5820 5821<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p> 5822<span class="apii">[-0, +0, –]</span> 5823<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1, 5824 int funcindex2, int n2);</pre> 5825 5826<p> 5827Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code> 5828refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>. 5829 5830 5831 5832 5833 5834 5835 5836<h1>5 – <a name="5">The Auxiliary Library</a></h1> 5837 5838<p> 5839 5840The <em>auxiliary library</em> provides several convenient functions 5841to interface C with Lua. 5842While the basic API provides the primitive functions for all 5843interactions between C and Lua, 5844the auxiliary library provides higher-level functions for some 5845common tasks. 5846 5847 5848<p> 5849All functions and types from the auxiliary library 5850are defined in header file <code>lauxlib.h</code> and 5851have a prefix <code>luaL_</code>. 5852 5853 5854<p> 5855All functions in the auxiliary library are built on 5856top of the basic API, 5857and so they provide nothing that cannot be done with that API. 5858Nevertheless, the use of the auxiliary library ensures 5859more consistency to your code. 5860 5861 5862<p> 5863Several functions in the auxiliary library use internally some 5864extra stack slots. 5865When a function in the auxiliary library uses less than five slots, 5866it does not check the stack size; 5867it simply assumes that there are enough slots. 5868 5869 5870<p> 5871Several functions in the auxiliary library are used to 5872check C function arguments. 5873Because the error message is formatted for arguments 5874(e.g., "<code>bad argument #1</code>"), 5875you should not use these functions for other stack values. 5876 5877 5878<p> 5879Functions called <code>luaL_check*</code> 5880always raise an error if the check is not satisfied. 5881 5882 5883 5884<h2>5.1 – <a name="5.1">Functions and Types</a></h2> 5885 5886<p> 5887Here we list all functions and types from the auxiliary library 5888in alphabetical order. 5889 5890 5891 5892<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p> 5893<span class="apii">[-?, +?, <em>m</em>]</span> 5894<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre> 5895 5896<p> 5897Adds the byte <code>c</code> to the buffer <code>B</code> 5898(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5899 5900 5901 5902 5903 5904<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p> 5905<span class="apii">[-?, +?, <em>m</em>]</span> 5906<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre> 5907 5908<p> 5909Adds the string pointed to by <code>s</code> with length <code>l</code> to 5910the buffer <code>B</code> 5911(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5912The string can contain embedded zeros. 5913 5914 5915 5916 5917 5918<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p> 5919<span class="apii">[-?, +?, –]</span> 5920<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre> 5921 5922<p> 5923Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>) 5924a string of length <code>n</code> previously copied to the 5925buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>). 5926 5927 5928 5929 5930 5931<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p> 5932<span class="apii">[-?, +?, <em>m</em>]</span> 5933<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre> 5934 5935<p> 5936Adds the zero-terminated string pointed to by <code>s</code> 5937to the buffer <code>B</code> 5938(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5939 5940 5941 5942 5943 5944<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p> 5945<span class="apii">[-1, +?, <em>m</em>]</span> 5946<pre>void luaL_addvalue (luaL_Buffer *B);</pre> 5947 5948<p> 5949Adds the value at the top of the stack 5950to the buffer <code>B</code> 5951(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 5952Pops the value. 5953 5954 5955<p> 5956This is the only function on string buffers that can (and must) 5957be called with an extra element on the stack, 5958which is the value to be added to the buffer. 5959 5960 5961 5962 5963 5964<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p> 5965<span class="apii">[-0, +0, <em>v</em>]</span> 5966<pre>void luaL_argcheck (lua_State *L, 5967 int cond, 5968 int arg, 5969 const char *extramsg);</pre> 5970 5971<p> 5972Checks whether <code>cond</code> is true. 5973If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>). 5974 5975 5976 5977 5978 5979<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p> 5980<span class="apii">[-0, +0, <em>v</em>]</span> 5981<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre> 5982 5983<p> 5984Raises an error reporting a problem with argument <code>arg</code> 5985of the C function that called it, 5986using a standard message 5987that includes <code>extramsg</code> as a comment: 5988 5989<pre> 5990 bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>) 5991</pre><p> 5992This function never returns. 5993 5994 5995 5996 5997 5998<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3> 5999<pre>typedef struct luaL_Buffer luaL_Buffer;</pre> 6000 6001<p> 6002Type for a <em>string buffer</em>. 6003 6004 6005<p> 6006A string buffer allows C code to build Lua strings piecemeal. 6007Its pattern of use is as follows: 6008 6009<ul> 6010 6011<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> 6012 6013<li>Then initialize it with a call <code>luaL_buffinit(L, &b)</code>.</li> 6014 6015<li> 6016Then add string pieces to the buffer calling any of 6017the <code>luaL_add*</code> functions. 6018</li> 6019 6020<li> 6021Finish by calling <code>luaL_pushresult(&b)</code>. 6022This call leaves the final string on the top of the stack. 6023</li> 6024 6025</ul> 6026 6027<p> 6028If you know beforehand the total size of the resulting string, 6029you can use the buffer like this: 6030 6031<ul> 6032 6033<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> 6034 6035<li>Then initialize it and preallocate a space of 6036size <code>sz</code> with a call <code>luaL_buffinitsize(L, &b, sz)</code>.</li> 6037 6038<li>Then copy the string into that space.</li> 6039 6040<li> 6041Finish by calling <code>luaL_pushresultsize(&b, sz)</code>, 6042where <code>sz</code> is the total size of the resulting string 6043copied into that space. 6044</li> 6045 6046</ul> 6047 6048<p> 6049During its normal operation, 6050a string buffer uses a variable number of stack slots. 6051So, while using a buffer, you cannot assume that you know where 6052the top of the stack is. 6053You can use the stack between successive calls to buffer operations 6054as long as that use is balanced; 6055that is, 6056when you call a buffer operation, 6057the stack is at the same level 6058it was immediately after the previous buffer operation. 6059(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.) 6060After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its 6061level when the buffer was initialized, 6062plus the final string on its top. 6063 6064 6065 6066 6067 6068<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p> 6069<span class="apii">[-0, +0, –]</span> 6070<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre> 6071 6072<p> 6073Initializes a buffer <code>B</code>. 6074This function does not allocate any space; 6075the buffer must be declared as a variable 6076(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 6077 6078 6079 6080 6081 6082<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p> 6083<span class="apii">[-?, +?, <em>m</em>]</span> 6084<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre> 6085 6086<p> 6087Equivalent to the sequence 6088<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>. 6089 6090 6091 6092 6093 6094<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p> 6095<span class="apii">[-0, +(0|1), <em>e</em>]</span> 6096<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre> 6097 6098<p> 6099Calls a metamethod. 6100 6101 6102<p> 6103If the object at index <code>obj</code> has a metatable and this 6104metatable has a field <code>e</code>, 6105this function calls this field passing the object as its only argument. 6106In this case this function returns true and pushes onto the 6107stack the value returned by the call. 6108If there is no metatable or no metamethod, 6109this function returns false (without pushing any value on the stack). 6110 6111 6112 6113 6114 6115<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p> 6116<span class="apii">[-0, +0, <em>v</em>]</span> 6117<pre>void luaL_checkany (lua_State *L, int arg);</pre> 6118 6119<p> 6120Checks whether the function has an argument 6121of any type (including <b>nil</b>) at position <code>arg</code>. 6122 6123 6124 6125 6126 6127<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p> 6128<span class="apii">[-0, +0, <em>v</em>]</span> 6129<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre> 6130 6131<p> 6132Checks whether the function argument <code>arg</code> is an integer 6133(or can be converted to an integer) 6134and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>. 6135 6136 6137 6138 6139 6140<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p> 6141<span class="apii">[-0, +0, <em>v</em>]</span> 6142<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre> 6143 6144<p> 6145Checks whether the function argument <code>arg</code> is a string 6146and returns this string; 6147if <code>l</code> is not <code>NULL</code> fills <code>*l</code> 6148with the string's length. 6149 6150 6151<p> 6152This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, 6153so all conversions and caveats of that function apply here. 6154 6155 6156 6157 6158 6159<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p> 6160<span class="apii">[-0, +0, <em>v</em>]</span> 6161<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre> 6162 6163<p> 6164Checks whether the function argument <code>arg</code> is a number 6165and returns this number. 6166 6167 6168 6169 6170 6171<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p> 6172<span class="apii">[-0, +0, <em>v</em>]</span> 6173<pre>int luaL_checkoption (lua_State *L, 6174 int arg, 6175 const char *def, 6176 const char *const lst[]);</pre> 6177 6178<p> 6179Checks whether the function argument <code>arg</code> is a string and 6180searches for this string in the array <code>lst</code> 6181(which must be NULL-terminated). 6182Returns the index in the array where the string was found. 6183Raises an error if the argument is not a string or 6184if the string cannot be found. 6185 6186 6187<p> 6188If <code>def</code> is not <code>NULL</code>, 6189the function uses <code>def</code> as a default value when 6190there is no argument <code>arg</code> or when this argument is <b>nil</b>. 6191 6192 6193<p> 6194This is a useful function for mapping strings to C enums. 6195(The usual convention in Lua libraries is 6196to use strings instead of numbers to select options.) 6197 6198 6199 6200 6201 6202<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p> 6203<span class="apii">[-0, +0, <em>v</em>]</span> 6204<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre> 6205 6206<p> 6207Grows the stack size to <code>top + sz</code> elements, 6208raising an error if the stack cannot grow to that size. 6209<code>msg</code> is an additional text to go into the error message 6210(or <code>NULL</code> for no additional text). 6211 6212 6213 6214 6215 6216<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p> 6217<span class="apii">[-0, +0, <em>v</em>]</span> 6218<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre> 6219 6220<p> 6221Checks whether the function argument <code>arg</code> is a string 6222and returns this string. 6223 6224 6225<p> 6226This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, 6227so all conversions and caveats of that function apply here. 6228 6229 6230 6231 6232 6233<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p> 6234<span class="apii">[-0, +0, <em>v</em>]</span> 6235<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre> 6236 6237<p> 6238Checks whether the function argument <code>arg</code> has type <code>t</code>. 6239See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>. 6240 6241 6242 6243 6244 6245<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p> 6246<span class="apii">[-0, +0, <em>v</em>]</span> 6247<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre> 6248 6249<p> 6250Checks whether the function argument <code>arg</code> is a userdata 6251of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and 6252returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>). 6253 6254 6255 6256 6257 6258<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p> 6259<span class="apii">[-0, +0, –]</span> 6260<pre>void luaL_checkversion (lua_State *L);</pre> 6261 6262<p> 6263Checks whether the core running the call, 6264the core that created the Lua state, 6265and the code making the call are all using the same version of Lua. 6266Also checks whether the core running the call 6267and the core that created the Lua state 6268are using the same address space. 6269 6270 6271 6272 6273 6274<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p> 6275<span class="apii">[-0, +?, <em>e</em>]</span> 6276<pre>int luaL_dofile (lua_State *L, const char *filename);</pre> 6277 6278<p> 6279Loads and runs the given file. 6280It is defined as the following macro: 6281 6282<pre> 6283 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) 6284</pre><p> 6285It returns false if there are no errors 6286or true in case of errors. 6287 6288 6289 6290 6291 6292<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p> 6293<span class="apii">[-0, +?, –]</span> 6294<pre>int luaL_dostring (lua_State *L, const char *str);</pre> 6295 6296<p> 6297Loads and runs the given string. 6298It is defined as the following macro: 6299 6300<pre> 6301 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) 6302</pre><p> 6303It returns false if there are no errors 6304or true in case of errors. 6305 6306 6307 6308 6309 6310<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p> 6311<span class="apii">[-0, +0, <em>v</em>]</span> 6312<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre> 6313 6314<p> 6315Raises an error. 6316The error message format is given by <code>fmt</code> 6317plus any extra arguments, 6318following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>. 6319It also adds at the beginning of the message the file name and 6320the line number where the error occurred, 6321if this information is available. 6322 6323 6324<p> 6325This function never returns, 6326but it is an idiom to use it in C functions 6327as <code>return luaL_error(<em>args</em>)</code>. 6328 6329 6330 6331 6332 6333<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p> 6334<span class="apii">[-0, +3, <em>m</em>]</span> 6335<pre>int luaL_execresult (lua_State *L, int stat);</pre> 6336 6337<p> 6338This function produces the return values for 6339process-related functions in the standard library 6340(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>). 6341 6342 6343 6344 6345 6346<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p> 6347<span class="apii">[-0, +(1|3), <em>m</em>]</span> 6348<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre> 6349 6350<p> 6351This function produces the return values for 6352file-related functions in the standard library 6353(<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.). 6354 6355 6356 6357 6358 6359<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p> 6360<span class="apii">[-0, +(0|1), <em>m</em>]</span> 6361<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre> 6362 6363<p> 6364Pushes onto the stack the field <code>e</code> from the metatable 6365of the object at index <code>obj</code> and returns the type of pushed value. 6366If the object does not have a metatable, 6367or if the metatable does not have this field, 6368pushes nothing and returns <code>LUA_TNIL</code>. 6369 6370 6371 6372 6373 6374<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p> 6375<span class="apii">[-0, +1, <em>m</em>]</span> 6376<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre> 6377 6378<p> 6379Pushes onto the stack the metatable associated with name <code>tname</code> 6380in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) 6381(<b>nil</b> if there is no metatable associated with that name). 6382Returns the type of the pushed value. 6383 6384 6385 6386 6387 6388<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p> 6389<span class="apii">[-0, +1, <em>e</em>]</span> 6390<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre> 6391 6392<p> 6393Ensures that the value <code>t[fname]</code>, 6394where <code>t</code> is the value at index <code>idx</code>, 6395is a table, 6396and pushes that table onto the stack. 6397Returns true if it finds a previous table there 6398and false if it creates a new table. 6399 6400 6401 6402 6403 6404<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p> 6405<span class="apii">[-0, +1, <em>m</em>]</span> 6406<pre>const char *luaL_gsub (lua_State *L, 6407 const char *s, 6408 const char *p, 6409 const char *r);</pre> 6410 6411<p> 6412Creates a copy of string <code>s</code> by replacing 6413any occurrence of the string <code>p</code> 6414with the string <code>r</code>. 6415Pushes the resulting string on the stack and returns it. 6416 6417 6418 6419 6420 6421<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p> 6422<span class="apii">[-0, +0, <em>e</em>]</span> 6423<pre>lua_Integer luaL_len (lua_State *L, int index);</pre> 6424 6425<p> 6426Returns the "length" of the value at the given index 6427as a number; 6428it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">§3.4.7</a>). 6429Raises an error if the result of the operation is not an integer. 6430(This case only can happen through metamethods.) 6431 6432 6433 6434 6435 6436<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p> 6437<span class="apii">[-0, +1, –]</span> 6438<pre>int luaL_loadbuffer (lua_State *L, 6439 const char *buff, 6440 size_t sz, 6441 const char *name);</pre> 6442 6443<p> 6444Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>. 6445 6446 6447 6448 6449 6450<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p> 6451<span class="apii">[-0, +1, –]</span> 6452<pre>int luaL_loadbufferx (lua_State *L, 6453 const char *buff, 6454 size_t sz, 6455 const char *name, 6456 const char *mode);</pre> 6457 6458<p> 6459Loads a buffer as a Lua chunk. 6460This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the 6461buffer pointed to by <code>buff</code> with size <code>sz</code>. 6462 6463 6464<p> 6465This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. 6466<code>name</code> is the chunk name, 6467used for debug information and error messages. 6468The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. 6469 6470 6471 6472 6473 6474<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p> 6475<span class="apii">[-0, +1, <em>e</em>]</span> 6476<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre> 6477 6478<p> 6479Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>. 6480 6481 6482 6483 6484 6485<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p> 6486<span class="apii">[-0, +1, <em>e</em>]</span> 6487<pre>int luaL_loadfilex (lua_State *L, const char *filename, 6488 const char *mode);</pre> 6489 6490<p> 6491Loads a file as a Lua chunk. 6492This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file 6493named <code>filename</code>. 6494If <code>filename</code> is <code>NULL</code>, 6495then it loads from the standard input. 6496The first line in the file is ignored if it starts with a <code>#</code>. 6497 6498 6499<p> 6500The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. 6501 6502 6503<p> 6504This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>, 6505but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> 6506if it cannot open/read the file or the file has a wrong mode. 6507 6508 6509<p> 6510As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; 6511it does not run it. 6512 6513 6514 6515 6516 6517<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p> 6518<span class="apii">[-0, +1, –]</span> 6519<pre>int luaL_loadstring (lua_State *L, const char *s);</pre> 6520 6521<p> 6522Loads a string as a Lua chunk. 6523This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in 6524the zero-terminated string <code>s</code>. 6525 6526 6527<p> 6528This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. 6529 6530 6531<p> 6532Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; 6533it does not run it. 6534 6535 6536 6537 6538 6539<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p> 6540<span class="apii">[-0, +1, <em>m</em>]</span> 6541<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre> 6542 6543<p> 6544Creates a new table and registers there 6545the functions in list <code>l</code>. 6546 6547 6548<p> 6549It is implemented as the following macro: 6550 6551<pre> 6552 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) 6553</pre><p> 6554The array <code>l</code> must be the actual array, 6555not a pointer to it. 6556 6557 6558 6559 6560 6561<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p> 6562<span class="apii">[-0, +1, <em>m</em>]</span> 6563<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre> 6564 6565<p> 6566Creates a new table with a size optimized 6567to store all entries in the array <code>l</code> 6568(but does not actually store them). 6569It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> 6570(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>). 6571 6572 6573<p> 6574It is implemented as a macro. 6575The array <code>l</code> must be the actual array, 6576not a pointer to it. 6577 6578 6579 6580 6581 6582<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p> 6583<span class="apii">[-0, +1, <em>m</em>]</span> 6584<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre> 6585 6586<p> 6587If the registry already has the key <code>tname</code>, 6588returns 0. 6589Otherwise, 6590creates a new table to be used as a metatable for userdata, 6591adds to this new table the pair <code>__name = tname</code>, 6592adds to the registry the pair <code>[tname] = new table</code>, 6593and returns 1. 6594(The entry <code>__name</code> is used by some error-reporting functions.) 6595 6596 6597<p> 6598In both cases pushes onto the stack the final value associated 6599with <code>tname</code> in the registry. 6600 6601 6602 6603 6604 6605<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p> 6606<span class="apii">[-0, +0, –]</span> 6607<pre>lua_State *luaL_newstate (void);</pre> 6608 6609<p> 6610Creates a new Lua state. 6611It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an 6612allocator based on the standard C <code>realloc</code> function 6613and then sets a panic function (see <a href="#4.6">§4.6</a>) that prints 6614an error message to the standard error output in case of fatal 6615errors. 6616 6617 6618<p> 6619Returns the new state, 6620or <code>NULL</code> if there is a memory allocation error. 6621 6622 6623 6624 6625 6626<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p> 6627<span class="apii">[-0, +0, <em>e</em>]</span> 6628<pre>void luaL_openlibs (lua_State *L);</pre> 6629 6630<p> 6631Opens all standard Lua libraries into the given state. 6632 6633 6634 6635 6636 6637<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p> 6638<span class="apii">[-0, +0, <em>v</em>]</span> 6639<pre>lua_Integer luaL_optinteger (lua_State *L, 6640 int arg, 6641 lua_Integer d);</pre> 6642 6643<p> 6644If the function argument <code>arg</code> is an integer 6645(or convertible to an integer), 6646returns this integer. 6647If this argument is absent or is <b>nil</b>, 6648returns <code>d</code>. 6649Otherwise, raises an error. 6650 6651 6652 6653 6654 6655<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p> 6656<span class="apii">[-0, +0, <em>v</em>]</span> 6657<pre>const char *luaL_optlstring (lua_State *L, 6658 int arg, 6659 const char *d, 6660 size_t *l);</pre> 6661 6662<p> 6663If the function argument <code>arg</code> is a string, 6664returns this string. 6665If this argument is absent or is <b>nil</b>, 6666returns <code>d</code>. 6667Otherwise, raises an error. 6668 6669 6670<p> 6671If <code>l</code> is not <code>NULL</code>, 6672fills the position <code>*l</code> with the result's length. 6673If the result is <code>NULL</code> 6674(only possible when returning <code>d</code> and <code>d == NULL</code>), 6675its length is considered zero. 6676 6677 6678 6679 6680 6681<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p> 6682<span class="apii">[-0, +0, <em>v</em>]</span> 6683<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre> 6684 6685<p> 6686If the function argument <code>arg</code> is a number, 6687returns this number. 6688If this argument is absent or is <b>nil</b>, 6689returns <code>d</code>. 6690Otherwise, raises an error. 6691 6692 6693 6694 6695 6696<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p> 6697<span class="apii">[-0, +0, <em>v</em>]</span> 6698<pre>const char *luaL_optstring (lua_State *L, 6699 int arg, 6700 const char *d);</pre> 6701 6702<p> 6703If the function argument <code>arg</code> is a string, 6704returns this string. 6705If this argument is absent or is <b>nil</b>, 6706returns <code>d</code>. 6707Otherwise, raises an error. 6708 6709 6710 6711 6712 6713<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p> 6714<span class="apii">[-?, +?, <em>m</em>]</span> 6715<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre> 6716 6717<p> 6718Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a> 6719with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>. 6720 6721 6722 6723 6724 6725<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p> 6726<span class="apii">[-?, +?, <em>m</em>]</span> 6727<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre> 6728 6729<p> 6730Returns an address to a space of size <code>sz</code> 6731where you can copy a string to be added to buffer <code>B</code> 6732(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). 6733After copying the string into this space you must call 6734<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add 6735it to the buffer. 6736 6737 6738 6739 6740 6741<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p> 6742<span class="apii">[-?, +1, <em>m</em>]</span> 6743<pre>void luaL_pushresult (luaL_Buffer *B);</pre> 6744 6745<p> 6746Finishes the use of buffer <code>B</code> leaving the final string on 6747the top of the stack. 6748 6749 6750 6751 6752 6753<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p> 6754<span class="apii">[-?, +1, <em>m</em>]</span> 6755<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre> 6756 6757<p> 6758Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>. 6759 6760 6761 6762 6763 6764<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p> 6765<span class="apii">[-1, +0, <em>m</em>]</span> 6766<pre>int luaL_ref (lua_State *L, int t);</pre> 6767 6768<p> 6769Creates and returns a <em>reference</em>, 6770in the table at index <code>t</code>, 6771for the object at the top of the stack (and pops the object). 6772 6773 6774<p> 6775A reference is a unique integer key. 6776As long as you do not manually add integer keys into table <code>t</code>, 6777<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns. 6778You can retrieve an object referred by reference <code>r</code> 6779by calling <code>lua_rawgeti(L, t, r)</code>. 6780Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object. 6781 6782 6783<p> 6784If the object at the top of the stack is <b>nil</b>, 6785<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>. 6786The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different 6787from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>. 6788 6789 6790 6791 6792 6793<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3> 6794<pre>typedef struct luaL_Reg { 6795 const char *name; 6796 lua_CFunction func; 6797} luaL_Reg;</pre> 6798 6799<p> 6800Type for arrays of functions to be registered by 6801<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>. 6802<code>name</code> is the function name and <code>func</code> is a pointer to 6803the function. 6804Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry 6805in which both <code>name</code> and <code>func</code> are <code>NULL</code>. 6806 6807 6808 6809 6810 6811<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p> 6812<span class="apii">[-0, +1, <em>e</em>]</span> 6813<pre>void luaL_requiref (lua_State *L, const char *modname, 6814 lua_CFunction openf, int glb);</pre> 6815 6816<p> 6817If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>, 6818calls function <code>openf</code> with string <code>modname</code> as an argument 6819and sets the call result in <code>package.loaded[modname]</code>, 6820as if that function has been called through <a href="#pdf-require"><code>require</code></a>. 6821 6822 6823<p> 6824If <code>glb</code> is true, 6825also stores the module into global <code>modname</code>. 6826 6827 6828<p> 6829Leaves a copy of the module on the stack. 6830 6831 6832 6833 6834 6835<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p> 6836<span class="apii">[-nup, +0, <em>m</em>]</span> 6837<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre> 6838 6839<p> 6840Registers all functions in the array <code>l</code> 6841(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack 6842(below optional upvalues, see next). 6843 6844 6845<p> 6846When <code>nup</code> is not zero, 6847all functions are created sharing <code>nup</code> upvalues, 6848which must be previously pushed on the stack 6849on top of the library table. 6850These values are popped from the stack after the registration. 6851 6852 6853 6854 6855 6856<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p> 6857<span class="apii">[-0, +0, –]</span> 6858<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre> 6859 6860<p> 6861Sets the metatable of the object at the top of the stack 6862as the metatable associated with name <code>tname</code> 6863in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). 6864 6865 6866 6867 6868 6869<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3> 6870<pre>typedef struct luaL_Stream { 6871 FILE *f; 6872 lua_CFunction closef; 6873} luaL_Stream;</pre> 6874 6875<p> 6876The standard representation for file handles, 6877which is used by the standard I/O library. 6878 6879 6880<p> 6881A file handle is implemented as a full userdata, 6882with a metatable called <code>LUA_FILEHANDLE</code> 6883(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name). 6884The metatable is created by the I/O library 6885(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). 6886 6887 6888<p> 6889This userdata must start with the structure <code>luaL_Stream</code>; 6890it can contain other data after this initial structure. 6891Field <code>f</code> points to the corresponding C stream 6892(or it can be <code>NULL</code> to indicate an incompletely created handle). 6893Field <code>closef</code> points to a Lua function 6894that will be called to close the stream 6895when the handle is closed or collected; 6896this function receives the file handle as its sole argument and 6897must return either <b>true</b> (in case of success) 6898or <b>nil</b> plus an error message (in case of error). 6899Once Lua calls this field, 6900it changes the field value to <code>NULL</code> 6901to signal that the handle is closed. 6902 6903 6904 6905 6906 6907<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p> 6908<span class="apii">[-0, +0, <em>m</em>]</span> 6909<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre> 6910 6911<p> 6912This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>, 6913except that, when the test fails, 6914it returns <code>NULL</code> instead of raising an error. 6915 6916 6917 6918 6919 6920<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p> 6921<span class="apii">[-0, +1, <em>e</em>]</span> 6922<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre> 6923 6924<p> 6925Converts any Lua value at the given index to a C string 6926in a reasonable format. 6927The resulting string is pushed onto the stack and also 6928returned by the function. 6929If <code>len</code> is not <code>NULL</code>, 6930the function also sets <code>*len</code> with the string length. 6931 6932 6933<p> 6934If the value has a metatable with a <code>"__tostring"</code> field, 6935then <code>luaL_tolstring</code> calls the corresponding metamethod 6936with the value as argument, 6937and uses the result of the call as its result. 6938 6939 6940 6941 6942 6943<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p> 6944<span class="apii">[-0, +1, <em>m</em>]</span> 6945<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, 6946 int level);</pre> 6947 6948<p> 6949Creates and pushes a traceback of the stack <code>L1</code>. 6950If <code>msg</code> is not <code>NULL</code> it is appended 6951at the beginning of the traceback. 6952The <code>level</code> parameter tells at which level 6953to start the traceback. 6954 6955 6956 6957 6958 6959<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p> 6960<span class="apii">[-0, +0, –]</span> 6961<pre>const char *luaL_typename (lua_State *L, int index);</pre> 6962 6963<p> 6964Returns the name of the type of the value at the given index. 6965 6966 6967 6968 6969 6970<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p> 6971<span class="apii">[-0, +0, –]</span> 6972<pre>void luaL_unref (lua_State *L, int t, int ref);</pre> 6973 6974<p> 6975Releases reference <code>ref</code> from the table at index <code>t</code> 6976(see <a href="#luaL_ref"><code>luaL_ref</code></a>). 6977The entry is removed from the table, 6978so that the referred object can be collected. 6979The reference <code>ref</code> is also freed to be used again. 6980 6981 6982<p> 6983If <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>, 6984<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing. 6985 6986 6987 6988 6989 6990<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p> 6991<span class="apii">[-0, +1, <em>m</em>]</span> 6992<pre>void luaL_where (lua_State *L, int lvl);</pre> 6993 6994<p> 6995Pushes onto the stack a string identifying the current position 6996of the control at level <code>lvl</code> in the call stack. 6997Typically this string has the following format: 6998 6999<pre> 7000 <em>chunkname</em>:<em>currentline</em>: 7001</pre><p> 7002Level 0 is the running function, 7003level 1 is the function that called the running function, 7004etc. 7005 7006 7007<p> 7008This function is used to build a prefix for error messages. 7009 7010 7011 7012 7013 7014 7015 7016<h1>6 – <a name="6">Standard Libraries</a></h1> 7017 7018<p> 7019The standard Lua libraries provide useful functions 7020that are implemented directly through the C API. 7021Some of these functions provide essential services to the language 7022(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>); 7023others provide access to "outside" services (e.g., I/O); 7024and others could be implemented in Lua itself, 7025but are quite useful or have critical performance requirements that 7026deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>). 7027 7028 7029<p> 7030All libraries are implemented through the official C API 7031and are provided as separate C modules. 7032Currently, Lua has the following standard libraries: 7033 7034<ul> 7035 7036<li>basic library (<a href="#6.1">§6.1</a>);</li> 7037 7038<li>coroutine library (<a href="#6.2">§6.2</a>);</li> 7039 7040<li>package library (<a href="#6.3">§6.3</a>);</li> 7041 7042<li>string manipulation (<a href="#6.4">§6.4</a>);</li> 7043 7044<li>basic UTF-8 support (<a href="#6.5">§6.5</a>);</li> 7045 7046<li>table manipulation (<a href="#6.6">§6.6</a>);</li> 7047 7048<li>mathematical functions (<a href="#6.7">§6.7</a>) (sin, log, etc.);</li> 7049 7050<li>input and output (<a href="#6.8">§6.8</a>);</li> 7051 7052<li>operating system facilities (<a href="#6.9">§6.9</a>);</li> 7053 7054<li>debug facilities (<a href="#6.10">§6.10</a>).</li> 7055 7056</ul><p> 7057Except for the basic and the package libraries, 7058each library provides all its functions as fields of a global table 7059or as methods of its objects. 7060 7061 7062<p> 7063To have access to these libraries, 7064the C host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function, 7065which opens all standard libraries. 7066Alternatively, 7067the host program can open them individually by using 7068<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call 7069<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library), 7070<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library), 7071<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library), 7072<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library), 7073<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library), 7074<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library), 7075<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library), 7076<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library), 7077<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library), 7078and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library). 7079These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>. 7080 7081 7082 7083<h2>6.1 – <a name="6.1">Basic Functions</a></h2> 7084 7085<p> 7086The basic library provides core functions to Lua. 7087If you do not include this library in your application, 7088you should check carefully whether you need to provide 7089implementations for some of its facilities. 7090 7091 7092<p> 7093<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3> 7094 7095 7096<p> 7097Calls <a href="#pdf-error"><code>error</code></a> if 7098the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>); 7099otherwise, returns all its arguments. 7100In case of error, 7101<code>message</code> is the error object; 7102when absent, it defaults to "<code>assertion failed!</code>" 7103 7104 7105 7106 7107<p> 7108<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3> 7109 7110 7111<p> 7112This function is a generic interface to the garbage collector. 7113It performs different functions according to its first argument, <code>opt</code>: 7114 7115<ul> 7116 7117<li><b>"<code>collect</code>": </b> 7118performs a full garbage-collection cycle. 7119This is the default option. 7120</li> 7121 7122<li><b>"<code>stop</code>": </b> 7123stops automatic execution of the garbage collector. 7124The collector will run only when explicitly invoked, 7125until a call to restart it. 7126</li> 7127 7128<li><b>"<code>restart</code>": </b> 7129restarts automatic execution of the garbage collector. 7130</li> 7131 7132<li><b>"<code>count</code>": </b> 7133returns the total memory in use by Lua in Kbytes. 7134The value has a fractional part, 7135so that it multiplied by 1024 7136gives the exact number of bytes in use by Lua 7137(except for overflows). 7138</li> 7139 7140<li><b>"<code>step</code>": </b> 7141performs a garbage-collection step. 7142The step "size" is controlled by <code>arg</code>. 7143With a zero value, 7144the collector will perform one basic (indivisible) step. 7145For non-zero values, 7146the collector will perform as if that amount of memory 7147(in KBytes) had been allocated by Lua. 7148Returns <b>true</b> if the step finished a collection cycle. 7149</li> 7150 7151<li><b>"<code>setpause</code>": </b> 7152sets <code>arg</code> as the new value for the <em>pause</em> of 7153the collector (see <a href="#2.5">§2.5</a>). 7154Returns the previous value for <em>pause</em>. 7155</li> 7156 7157<li><b>"<code>setstepmul</code>": </b> 7158sets <code>arg</code> as the new value for the <em>step multiplier</em> of 7159the collector (see <a href="#2.5">§2.5</a>). 7160Returns the previous value for <em>step</em>. 7161</li> 7162 7163<li><b>"<code>isrunning</code>": </b> 7164returns a boolean that tells whether the collector is running 7165(i.e., not stopped). 7166</li> 7167 7168</ul> 7169 7170 7171 7172<p> 7173<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3> 7174Opens the named file and executes its contents as a Lua chunk. 7175When called without arguments, 7176<code>dofile</code> executes the contents of the standard input (<code>stdin</code>). 7177Returns all values returned by the chunk. 7178In case of errors, <code>dofile</code> propagates the error 7179to its caller (that is, <code>dofile</code> does not run in protected mode). 7180 7181 7182 7183 7184<p> 7185<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3> 7186Terminates the last protected function called 7187and returns <code>message</code> as the error object. 7188Function <code>error</code> never returns. 7189 7190 7191<p> 7192Usually, <code>error</code> adds some information about the error position 7193at the beginning of the message, if the message is a string. 7194The <code>level</code> argument specifies how to get the error position. 7195With level 1 (the default), the error position is where the 7196<code>error</code> function was called. 7197Level 2 points the error to where the function 7198that called <code>error</code> was called; and so on. 7199Passing a level 0 avoids the addition of error position information 7200to the message. 7201 7202 7203 7204 7205<p> 7206<hr><h3><a name="pdf-_G"><code>_G</code></a></h3> 7207A global variable (not a function) that 7208holds the global environment (see <a href="#2.2">§2.2</a>). 7209Lua itself does not use this variable; 7210changing its value does not affect any environment, 7211nor vice versa. 7212 7213 7214 7215 7216<p> 7217<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3> 7218 7219 7220<p> 7221If <code>object</code> does not have a metatable, returns <b>nil</b>. 7222Otherwise, 7223if the object's metatable has a <code>"__metatable"</code> field, 7224returns the associated value. 7225Otherwise, returns the metatable of the given object. 7226 7227 7228 7229 7230<p> 7231<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3> 7232 7233 7234<p> 7235Returns three values (an iterator function, the table <code>t</code>, and 0) 7236so that the construction 7237 7238<pre> 7239 for i,v in ipairs(t) do <em>body</em> end 7240</pre><p> 7241will iterate over the key–value pairs 7242(<code>1,t[1]</code>), (<code>2,t[2]</code>), ..., 7243up to the first nil value. 7244 7245 7246 7247 7248<p> 7249<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3> 7250 7251 7252<p> 7253Loads a chunk. 7254 7255 7256<p> 7257If <code>chunk</code> is a string, the chunk is this string. 7258If <code>chunk</code> is a function, 7259<code>load</code> calls it repeatedly to get the chunk pieces. 7260Each call to <code>chunk</code> must return a string that concatenates 7261with previous results. 7262A return of an empty string, <b>nil</b>, or no value signals the end of the chunk. 7263 7264 7265<p> 7266If there are no syntactic errors, 7267returns the compiled chunk as a function; 7268otherwise, returns <b>nil</b> plus the error message. 7269 7270 7271<p> 7272If the resulting function has upvalues, 7273the first upvalue is set to the value of <code>env</code>, 7274if that parameter is given, 7275or to the value of the global environment. 7276Other upvalues are initialized with <b>nil</b>. 7277(When you load a main chunk, 7278the resulting function will always have exactly one upvalue, 7279the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>). 7280However, 7281when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>), 7282the resulting function can have an arbitrary number of upvalues.) 7283All upvalues are fresh, that is, 7284they are not shared with any other function. 7285 7286 7287<p> 7288<code>chunkname</code> is used as the name of the chunk for error messages 7289and debug information (see <a href="#4.9">§4.9</a>). 7290When absent, 7291it defaults to <code>chunk</code>, if <code>chunk</code> is a string, 7292or to "<code>=(load)</code>" otherwise. 7293 7294 7295<p> 7296The string <code>mode</code> controls whether the chunk can be text or binary 7297(that is, a precompiled chunk). 7298It may be the string "<code>b</code>" (only binary chunks), 7299"<code>t</code>" (only text chunks), 7300or "<code>bt</code>" (both binary and text). 7301The default is "<code>bt</code>". 7302 7303 7304<p> 7305Lua does not check the consistency of binary chunks. 7306Maliciously crafted binary chunks can crash 7307the interpreter. 7308 7309 7310 7311 7312<p> 7313<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3> 7314 7315 7316<p> 7317Similar to <a href="#pdf-load"><code>load</code></a>, 7318but gets the chunk from file <code>filename</code> 7319or from the standard input, 7320if no file name is given. 7321 7322 7323 7324 7325<p> 7326<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3> 7327 7328 7329<p> 7330Allows a program to traverse all fields of a table. 7331Its first argument is a table and its second argument 7332is an index in this table. 7333<code>next</code> returns the next index of the table 7334and its associated value. 7335When called with <b>nil</b> as its second argument, 7336<code>next</code> returns an initial index 7337and its associated value. 7338When called with the last index, 7339or with <b>nil</b> in an empty table, 7340<code>next</code> returns <b>nil</b>. 7341If the second argument is absent, then it is interpreted as <b>nil</b>. 7342In particular, 7343you can use <code>next(t)</code> to check whether a table is empty. 7344 7345 7346<p> 7347The order in which the indices are enumerated is not specified, 7348<em>even for numeric indices</em>. 7349(To traverse a table in numerical order, 7350use a numerical <b>for</b>.) 7351 7352 7353<p> 7354The behavior of <code>next</code> is undefined if, 7355during the traversal, 7356you assign any value to a non-existent field in the table. 7357You may however modify existing fields. 7358In particular, you may clear existing fields. 7359 7360 7361 7362 7363<p> 7364<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3> 7365 7366 7367<p> 7368If <code>t</code> has a metamethod <code>__pairs</code>, 7369calls it with <code>t</code> as argument and returns the first three 7370results from the call. 7371 7372 7373<p> 7374Otherwise, 7375returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>, 7376so that the construction 7377 7378<pre> 7379 for k,v in pairs(t) do <em>body</em> end 7380</pre><p> 7381will iterate over all key–value pairs of table <code>t</code>. 7382 7383 7384<p> 7385See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying 7386the table during its traversal. 7387 7388 7389 7390 7391<p> 7392<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, ···])</code></a></h3> 7393 7394 7395<p> 7396Calls function <code>f</code> with 7397the given arguments in <em>protected mode</em>. 7398This means that any error inside <code>f</code> is not propagated; 7399instead, <code>pcall</code> catches the error 7400and returns a status code. 7401Its first result is the status code (a boolean), 7402which is true if the call succeeds without errors. 7403In such case, <code>pcall</code> also returns all results from the call, 7404after this first result. 7405In case of any error, <code>pcall</code> returns <b>false</b> plus the error message. 7406 7407 7408 7409 7410<p> 7411<hr><h3><a name="pdf-print"><code>print (···)</code></a></h3> 7412Receives any number of arguments 7413and prints their values to <code>stdout</code>, 7414using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string. 7415<code>print</code> is not intended for formatted output, 7416but only as a quick way to show a value, 7417for instance for debugging. 7418For complete control over the output, 7419use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>. 7420 7421 7422 7423 7424<p> 7425<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3> 7426Checks whether <code>v1</code> is equal to <code>v2</code>, 7427without invoking any metamethod. 7428Returns a boolean. 7429 7430 7431 7432 7433<p> 7434<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3> 7435Gets the real value of <code>table[index]</code>, 7436without invoking any metamethod. 7437<code>table</code> must be a table; 7438<code>index</code> may be any value. 7439 7440 7441 7442 7443<p> 7444<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3> 7445Returns the length of the object <code>v</code>, 7446which must be a table or a string, 7447without invoking any metamethod. 7448Returns an integer. 7449 7450 7451 7452 7453<p> 7454<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3> 7455Sets the real value of <code>table[index]</code> to <code>value</code>, 7456without invoking any metamethod. 7457<code>table</code> must be a table, 7458<code>index</code> any value different from <b>nil</b> and NaN, 7459and <code>value</code> any Lua value. 7460 7461 7462<p> 7463This function returns <code>table</code>. 7464 7465 7466 7467 7468<p> 7469<hr><h3><a name="pdf-select"><code>select (index, ···)</code></a></h3> 7470 7471 7472<p> 7473If <code>index</code> is a number, 7474returns all arguments after argument number <code>index</code>; 7475a negative number indexes from the end (-1 is the last argument). 7476Otherwise, <code>index</code> must be the string <code>"#"</code>, 7477and <code>select</code> returns the total number of extra arguments it received. 7478 7479 7480 7481 7482<p> 7483<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3> 7484 7485 7486<p> 7487Sets the metatable for the given table. 7488(To change the metatable of other types from Lua code, 7489you must use the debug library (<a href="#6.10">§6.10</a>).) 7490If <code>metatable</code> is <b>nil</b>, 7491removes the metatable of the given table. 7492If the original metatable has a <code>"__metatable"</code> field, 7493raises an error. 7494 7495 7496<p> 7497This function returns <code>table</code>. 7498 7499 7500 7501 7502<p> 7503<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3> 7504 7505 7506<p> 7507When called with no <code>base</code>, 7508<code>tonumber</code> tries to convert its argument to a number. 7509If the argument is already a number or 7510a string convertible to a number, 7511then <code>tonumber</code> returns this number; 7512otherwise, it returns <b>nil</b>. 7513 7514 7515<p> 7516The conversion of strings can result in integers or floats, 7517according to the lexical conventions of Lua (see <a href="#3.1">§3.1</a>). 7518(The string may have leading and trailing spaces and a sign.) 7519 7520 7521<p> 7522When called with <code>base</code>, 7523then <code>e</code> must be a string to be interpreted as 7524an integer numeral in that base. 7525The base may be any integer between 2 and 36, inclusive. 7526In bases above 10, the letter '<code>A</code>' (in either upper or lower case) 7527represents 10, '<code>B</code>' represents 11, and so forth, 7528with '<code>Z</code>' representing 35. 7529If the string <code>e</code> is not a valid numeral in the given base, 7530the function returns <b>nil</b>. 7531 7532 7533 7534 7535<p> 7536<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3> 7537Receives a value of any type and 7538converts it to a string in a human-readable format. 7539(For complete control of how numbers are converted, 7540use <a href="#pdf-string.format"><code>string.format</code></a>.) 7541 7542 7543<p> 7544If the metatable of <code>v</code> has a <code>"__tostring"</code> field, 7545then <code>tostring</code> calls the corresponding value 7546with <code>v</code> as argument, 7547and uses the result of the call as its result. 7548 7549 7550 7551 7552<p> 7553<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3> 7554Returns the type of its only argument, coded as a string. 7555The possible results of this function are 7556"<code>nil</code>" (a string, not the value <b>nil</b>), 7557"<code>number</code>", 7558"<code>string</code>", 7559"<code>boolean</code>", 7560"<code>table</code>", 7561"<code>function</code>", 7562"<code>thread</code>", 7563and "<code>userdata</code>". 7564 7565 7566 7567 7568<p> 7569<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3> 7570 7571 7572<p> 7573A global variable (not a function) that 7574holds a string containing the running Lua version. 7575The current value of this variable is "<code>Lua 5.3</code>". 7576 7577 7578 7579 7580<p> 7581<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, ···])</code></a></h3> 7582 7583 7584<p> 7585This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>, 7586except that it sets a new message handler <code>msgh</code>. 7587 7588 7589 7590 7591 7592 7593 7594<h2>6.2 – <a name="6.2">Coroutine Manipulation</a></h2> 7595 7596<p> 7597This library comprises the operations to manipulate coroutines, 7598which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>. 7599See <a href="#2.6">§2.6</a> for a general description of coroutines. 7600 7601 7602<p> 7603<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3> 7604 7605 7606<p> 7607Creates a new coroutine, with body <code>f</code>. 7608<code>f</code> must be a function. 7609Returns this new coroutine, 7610an object with type <code>"thread"</code>. 7611 7612 7613 7614 7615<p> 7616<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3> 7617 7618 7619<p> 7620Returns true when the running coroutine can yield. 7621 7622 7623<p> 7624A running coroutine is yieldable if it is not the main thread and 7625it is not inside a non-yieldable C function. 7626 7627 7628 7629 7630<p> 7631<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, ···])</code></a></h3> 7632 7633 7634<p> 7635Starts or continues the execution of coroutine <code>co</code>. 7636The first time you resume a coroutine, 7637it starts running its body. 7638The values <code>val1</code>, ... are passed 7639as the arguments to the body function. 7640If the coroutine has yielded, 7641<code>resume</code> restarts it; 7642the values <code>val1</code>, ... are passed 7643as the results from the yield. 7644 7645 7646<p> 7647If the coroutine runs without any errors, 7648<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code> 7649(when the coroutine yields) or any values returned by the body function 7650(when the coroutine terminates). 7651If there is any error, 7652<code>resume</code> returns <b>false</b> plus the error message. 7653 7654 7655 7656 7657<p> 7658<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3> 7659 7660 7661<p> 7662Returns the running coroutine plus a boolean, 7663true when the running coroutine is the main one. 7664 7665 7666 7667 7668<p> 7669<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3> 7670 7671 7672<p> 7673Returns the status of coroutine <code>co</code>, as a string: 7674<code>"running"</code>, 7675if the coroutine is running (that is, it called <code>status</code>); 7676<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>, 7677or if it has not started running yet; 7678<code>"normal"</code> if the coroutine is active but not running 7679(that is, it has resumed another coroutine); 7680and <code>"dead"</code> if the coroutine has finished its body function, 7681or if it has stopped with an error. 7682 7683 7684 7685 7686<p> 7687<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3> 7688 7689 7690<p> 7691Creates a new coroutine, with body <code>f</code>. 7692<code>f</code> must be a function. 7693Returns a function that resumes the coroutine each time it is called. 7694Any arguments passed to the function behave as the 7695extra arguments to <code>resume</code>. 7696Returns the same values returned by <code>resume</code>, 7697except the first boolean. 7698In case of error, propagates the error. 7699 7700 7701 7702 7703<p> 7704<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (···)</code></a></h3> 7705 7706 7707<p> 7708Suspends the execution of the calling coroutine. 7709Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>. 7710 7711 7712 7713 7714 7715 7716 7717<h2>6.3 – <a name="6.3">Modules</a></h2> 7718 7719<p> 7720The package library provides basic 7721facilities for loading modules in Lua. 7722It exports one function directly in the global environment: 7723<a href="#pdf-require"><code>require</code></a>. 7724Everything else is exported in a table <a name="pdf-package"><code>package</code></a>. 7725 7726 7727<p> 7728<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3> 7729 7730 7731<p> 7732Loads the given module. 7733The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table 7734to determine whether <code>modname</code> is already loaded. 7735If it is, then <code>require</code> returns the value stored 7736at <code>package.loaded[modname]</code>. 7737Otherwise, it tries to find a <em>loader</em> for the module. 7738 7739 7740<p> 7741To find a loader, 7742<code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence. 7743By changing this sequence, 7744we can change how <code>require</code> looks for a module. 7745The following explanation is based on the default configuration 7746for <a href="#pdf-package.searchers"><code>package.searchers</code></a>. 7747 7748 7749<p> 7750First <code>require</code> queries <code>package.preload[modname]</code>. 7751If it has a value, 7752this value (which must be a function) is the loader. 7753Otherwise <code>require</code> searches for a Lua loader using the 7754path stored in <a href="#pdf-package.path"><code>package.path</code></a>. 7755If that also fails, it searches for a C loader using the 7756path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>. 7757If that also fails, 7758it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>). 7759 7760 7761<p> 7762Once a loader is found, 7763<code>require</code> calls the loader with two arguments: 7764<code>modname</code> and an extra value dependent on how it got the loader. 7765(If the loader came from a file, 7766this extra value is the file name.) 7767If the loader returns any non-nil value, 7768<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>. 7769If the loader does not return a non-nil value and 7770has not assigned any value to <code>package.loaded[modname]</code>, 7771then <code>require</code> assigns <b>true</b> to this entry. 7772In any case, <code>require</code> returns the 7773final value of <code>package.loaded[modname]</code>. 7774 7775 7776<p> 7777If there is any error loading or running the module, 7778or if it cannot find any loader for the module, 7779then <code>require</code> raises an error. 7780 7781 7782 7783 7784<p> 7785<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3> 7786 7787 7788<p> 7789A string describing some compile-time configurations for packages. 7790This string is a sequence of lines: 7791 7792<ul> 7793 7794<li>The first line is the directory separator string. 7795Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li> 7796 7797<li>The second line is the character that separates templates in a path. 7798Default is '<code>;</code>'.</li> 7799 7800<li>The third line is the string that marks the 7801substitution points in a template. 7802Default is '<code>?</code>'.</li> 7803 7804<li>The fourth line is a string that, in a path in Windows, 7805is replaced by the executable's directory. 7806Default is '<code>!</code>'.</li> 7807 7808<li>The fifth line is a mark to ignore all text after it 7809when building the <code>luaopen_</code> function name. 7810Default is '<code>-</code>'.</li> 7811 7812</ul> 7813 7814 7815 7816<p> 7817<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3> 7818 7819 7820<p> 7821The path used by <a href="#pdf-require"><code>require</code></a> to search for a C loader. 7822 7823 7824<p> 7825Lua initializes the C path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way 7826it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>, 7827using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a> 7828or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a> 7829or a default path defined in <code>luaconf.h</code>. 7830 7831 7832 7833 7834<p> 7835<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3> 7836 7837 7838<p> 7839A table used by <a href="#pdf-require"><code>require</code></a> to control which 7840modules are already loaded. 7841When you require a module <code>modname</code> and 7842<code>package.loaded[modname]</code> is not false, 7843<a href="#pdf-require"><code>require</code></a> simply returns the value stored there. 7844 7845 7846<p> 7847This variable is only a reference to the real table; 7848assignments to this variable do not change the 7849table used by <a href="#pdf-require"><code>require</code></a>. 7850 7851 7852 7853 7854<p> 7855<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3> 7856 7857 7858<p> 7859Dynamically links the host program with the C library <code>libname</code>. 7860 7861 7862<p> 7863If <code>funcname</code> is "<code>*</code>", 7864then it only links with the library, 7865making the symbols exported by the library 7866available to other dynamically linked libraries. 7867Otherwise, 7868it looks for a function <code>funcname</code> inside the library 7869and returns this function as a C function. 7870So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype 7871(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). 7872 7873 7874<p> 7875This is a low-level function. 7876It completely bypasses the package and module system. 7877Unlike <a href="#pdf-require"><code>require</code></a>, 7878it does not perform any path searching and 7879does not automatically adds extensions. 7880<code>libname</code> must be the complete file name of the C library, 7881including if necessary a path and an extension. 7882<code>funcname</code> must be the exact name exported by the C library 7883(which may depend on the C compiler and linker used). 7884 7885 7886<p> 7887This function is not supported by Standard C. 7888As such, it is only available on some platforms 7889(Windows, Linux, Mac OS X, Solaris, BSD, 7890plus other Unix systems that support the <code>dlfcn</code> standard). 7891 7892 7893 7894 7895<p> 7896<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3> 7897 7898 7899<p> 7900The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader. 7901 7902 7903<p> 7904At start-up, Lua initializes this variable with 7905the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or 7906the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or 7907with a default path defined in <code>luaconf.h</code>, 7908if those environment variables are not defined. 7909Any "<code>;;</code>" in the value of the environment variable 7910is replaced by the default path. 7911 7912 7913 7914 7915<p> 7916<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3> 7917 7918 7919<p> 7920A table to store loaders for specific modules 7921(see <a href="#pdf-require"><code>require</code></a>). 7922 7923 7924<p> 7925This variable is only a reference to the real table; 7926assignments to this variable do not change the 7927table used by <a href="#pdf-require"><code>require</code></a>. 7928 7929 7930 7931 7932<p> 7933<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3> 7934 7935 7936<p> 7937A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules. 7938 7939 7940<p> 7941Each entry in this table is a <em>searcher function</em>. 7942When looking for a module, 7943<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order, 7944with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its 7945sole parameter. 7946The function can return another function (the module <em>loader</em>) 7947plus an extra value that will be passed to that loader, 7948or a string explaining why it did not find that module 7949(or <b>nil</b> if it has nothing to say). 7950 7951 7952<p> 7953Lua initializes this table with four searcher functions. 7954 7955 7956<p> 7957The first searcher simply looks for a loader in the 7958<a href="#pdf-package.preload"><code>package.preload</code></a> table. 7959 7960 7961<p> 7962The second searcher looks for a loader as a Lua library, 7963using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>. 7964The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 7965 7966 7967<p> 7968The third searcher looks for a loader as a C library, 7969using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>. 7970Again, 7971the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 7972For instance, 7973if the C path is the string 7974 7975<pre> 7976 "./?.so;./?.dll;/usr/local/?/init.so" 7977</pre><p> 7978the searcher for module <code>foo</code> 7979will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>, 7980and <code>/usr/local/foo/init.so</code>, in that order. 7981Once it finds a C library, 7982this searcher first uses a dynamic link facility to link the 7983application with the library. 7984Then it tries to find a C function inside the library to 7985be used as the loader. 7986The name of this C function is the string "<code>luaopen_</code>" 7987concatenated with a copy of the module name where each dot 7988is replaced by an underscore. 7989Moreover, if the module name has a hyphen, 7990its suffix after (and including) the first hyphen is removed. 7991For instance, if the module name is <code>a.b.c-v2.1</code>, 7992the function name will be <code>luaopen_a_b_c</code>. 7993 7994 7995<p> 7996The fourth searcher tries an <em>all-in-one loader</em>. 7997It searches the C path for a library for 7998the root name of the given module. 7999For instance, when requiring <code>a.b.c</code>, 8000it will search for a C library for <code>a</code>. 8001If found, it looks into it for an open function for 8002the submodule; 8003in our example, that would be <code>luaopen_a_b_c</code>. 8004With this facility, a package can pack several C submodules 8005into one single library, 8006with each submodule keeping its original open function. 8007 8008 8009<p> 8010All searchers except the first one (preload) return as the extra value 8011the file name where the module was found, 8012as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. 8013The first searcher returns no extra value. 8014 8015 8016 8017 8018<p> 8019<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3> 8020 8021 8022<p> 8023Searches for the given <code>name</code> in the given <code>path</code>. 8024 8025 8026<p> 8027A path is a string containing a sequence of 8028<em>templates</em> separated by semicolons. 8029For each template, 8030the function replaces each interrogation mark (if any) 8031in the template with a copy of <code>name</code> 8032wherein all occurrences of <code>sep</code> 8033(a dot, by default) 8034were replaced by <code>rep</code> 8035(the system's directory separator, by default), 8036and then tries to open the resulting file name. 8037 8038 8039<p> 8040For instance, if the path is the string 8041 8042<pre> 8043 "./?.lua;./?.lc;/usr/local/?/init.lua" 8044</pre><p> 8045the search for the name <code>foo.a</code> 8046will try to open the files 8047<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and 8048<code>/usr/local/foo/a/init.lua</code>, in that order. 8049 8050 8051<p> 8052Returns the resulting name of the first file that it can 8053open in read mode (after closing the file), 8054or <b>nil</b> plus an error message if none succeeds. 8055(This error message lists all file names it tried to open.) 8056 8057 8058 8059 8060 8061 8062 8063<h2>6.4 – <a name="6.4">String Manipulation</a></h2> 8064 8065<p> 8066This library provides generic functions for string manipulation, 8067such as finding and extracting substrings, and pattern matching. 8068When indexing a string in Lua, the first character is at position 1 8069(not at 0, as in C). 8070Indices are allowed to be negative and are interpreted as indexing backwards, 8071from the end of the string. 8072Thus, the last character is at position -1, and so on. 8073 8074 8075<p> 8076The string library provides all its functions inside the table 8077<a name="pdf-string"><code>string</code></a>. 8078It also sets a metatable for strings 8079where the <code>__index</code> field points to the <code>string</code> table. 8080Therefore, you can use the string functions in object-oriented style. 8081For instance, <code>string.byte(s,i)</code> 8082can be written as <code>s:byte(i)</code>. 8083 8084 8085<p> 8086The string library assumes one-byte character encodings. 8087 8088 8089<p> 8090<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3> 8091Returns the internal numeric codes of the characters <code>s[i]</code>, 8092<code>s[i+1]</code>, ..., <code>s[j]</code>. 8093The default value for <code>i</code> is 1; 8094the default value for <code>j</code> is <code>i</code>. 8095These indices are corrected 8096following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>. 8097 8098 8099<p> 8100Numeric codes are not necessarily portable across platforms. 8101 8102 8103 8104 8105<p> 8106<hr><h3><a name="pdf-string.char"><code>string.char (···)</code></a></h3> 8107Receives zero or more integers. 8108Returns a string with length equal to the number of arguments, 8109in which each character has the internal numeric code equal 8110to its corresponding argument. 8111 8112 8113<p> 8114Numeric codes are not necessarily portable across platforms. 8115 8116 8117 8118 8119<p> 8120<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3> 8121 8122 8123<p> 8124Returns a string containing a binary representation 8125(a <em>binary chunk</em>) 8126of the given function, 8127so that a later <a href="#pdf-load"><code>load</code></a> on this string returns 8128a copy of the function (but with new upvalues). 8129If <code>strip</code> is a true value, 8130the binary representation may not include all debug information 8131about the function, 8132to save space. 8133 8134 8135<p> 8136Functions with upvalues have only their number of upvalues saved. 8137When (re)loaded, 8138those upvalues receive fresh instances containing <b>nil</b>. 8139(You can use the debug library to serialize 8140and reload the upvalues of a function 8141in a way adequate to your needs.) 8142 8143 8144 8145 8146<p> 8147<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3> 8148 8149 8150<p> 8151Looks for the first match of 8152<code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>. 8153If it finds a match, then <code>find</code> returns the indices of <code>s</code> 8154where this occurrence starts and ends; 8155otherwise, it returns <b>nil</b>. 8156A third, optional numeric argument <code>init</code> specifies 8157where to start the search; 8158its default value is 1 and can be negative. 8159A value of <b>true</b> as a fourth, optional argument <code>plain</code> 8160turns off the pattern matching facilities, 8161so the function does a plain "find substring" operation, 8162with no characters in <code>pattern</code> being considered magic. 8163Note that if <code>plain</code> is given, then <code>init</code> must be given as well. 8164 8165 8166<p> 8167If the pattern has captures, 8168then in a successful match 8169the captured values are also returned, 8170after the two indices. 8171 8172 8173 8174 8175<p> 8176<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, ···)</code></a></h3> 8177 8178 8179<p> 8180Returns a formatted version of its variable number of arguments 8181following the description given in its first argument (which must be a string). 8182The format string follows the same rules as the ISO C function <code>sprintf</code>. 8183The only differences are that the options/modifiers 8184<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>, 8185and <code>p</code> are not supported 8186and that there is an extra option, <code>q</code>. 8187The <code>q</code> option formats a string between double quotes, 8188using escape sequences when necessary to ensure that 8189it can safely be read back by the Lua interpreter. 8190For instance, the call 8191 8192<pre> 8193 string.format('%q', 'a string with "quotes" and \n new line') 8194</pre><p> 8195may produce the string: 8196 8197<pre> 8198 "a string with \"quotes\" and \ 8199 new line" 8200</pre> 8201 8202<p> 8203Options 8204<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>, 8205<code>G</code>, and <code>g</code> all expect a number as argument. 8206Options <code>c</code>, <code>d</code>, 8207<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> 8208expect an integer. 8209Option <code>q</code> expects a string. 8210Option <code>s</code> expects a string; 8211if its argument is not a string, 8212it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>. 8213If the option has any modifier (flags, width, length), 8214the string argument should not contain embedded zeros. 8215 8216 8217<p> 8218When Lua is compiled with a non-C99 compiler, 8219options <code>A</code> and <code>a</code> (hexadecimal floats) 8220do not support any modifier (flags, width, length). 8221 8222 8223 8224 8225<p> 8226<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3> 8227Returns an iterator function that, 8228each time it is called, 8229returns the next captures from <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) 8230over the string <code>s</code>. 8231If <code>pattern</code> specifies no captures, 8232then the whole match is produced in each call. 8233 8234 8235<p> 8236As an example, the following loop 8237will iterate over all the words from string <code>s</code>, 8238printing one per line: 8239 8240<pre> 8241 s = "hello world from Lua" 8242 for w in string.gmatch(s, "%a+") do 8243 print(w) 8244 end 8245</pre><p> 8246The next example collects all pairs <code>key=value</code> from the 8247given string into a table: 8248 8249<pre> 8250 t = {} 8251 s = "from=world, to=Lua" 8252 for k, v in string.gmatch(s, "(%w+)=(%w+)") do 8253 t[k] = v 8254 end 8255</pre> 8256 8257<p> 8258For this function, a caret '<code>^</code>' at the start of a pattern does not 8259work as an anchor, as this would prevent the iteration. 8260 8261 8262 8263 8264<p> 8265<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3> 8266Returns a copy of <code>s</code> 8267in which all (or the first <code>n</code>, if given) 8268occurrences of the <code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) have been 8269replaced by a replacement string specified by <code>repl</code>, 8270which can be a string, a table, or a function. 8271<code>gsub</code> also returns, as its second value, 8272the total number of matches that occurred. 8273The name <code>gsub</code> comes from <em>Global SUBstitution</em>. 8274 8275 8276<p> 8277If <code>repl</code> is a string, then its value is used for replacement. 8278The character <code>%</code> works as an escape character: 8279any sequence in <code>repl</code> of the form <code>%<em>d</em></code>, 8280with <em>d</em> between 1 and 9, 8281stands for the value of the <em>d</em>-th captured substring. 8282The sequence <code>%0</code> stands for the whole match. 8283The sequence <code>%%</code> stands for a single <code>%</code>. 8284 8285 8286<p> 8287If <code>repl</code> is a table, then the table is queried for every match, 8288using the first capture as the key. 8289 8290 8291<p> 8292If <code>repl</code> is a function, then this function is called every time a 8293match occurs, with all captured substrings passed as arguments, 8294in order. 8295 8296 8297<p> 8298In any case, 8299if the pattern specifies no captures, 8300then it behaves as if the whole pattern was inside a capture. 8301 8302 8303<p> 8304If the value returned by the table query or by the function call 8305is a string or a number, 8306then it is used as the replacement string; 8307otherwise, if it is <b>false</b> or <b>nil</b>, 8308then there is no replacement 8309(that is, the original match is kept in the string). 8310 8311 8312<p> 8313Here are some examples: 8314 8315<pre> 8316 x = string.gsub("hello world", "(%w+)", "%1 %1") 8317 --> x="hello hello world world" 8318 8319 x = string.gsub("hello world", "%w+", "%0 %0", 1) 8320 --> x="hello hello world" 8321 8322 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") 8323 --> x="world hello Lua from" 8324 8325 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) 8326 --> x="home = /home/roberto, user = roberto" 8327 8328 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) 8329 return load(s)() 8330 end) 8331 --> x="4+5 = 9" 8332 8333 local t = {name="lua", version="5.3"} 8334 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) 8335 --> x="lua-5.3.tar.gz" 8336</pre> 8337 8338 8339 8340<p> 8341<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3> 8342Receives a string and returns its length. 8343The empty string <code>""</code> has length 0. 8344Embedded zeros are counted, 8345so <code>"a\000bc\000"</code> has length 5. 8346 8347 8348 8349 8350<p> 8351<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3> 8352Receives a string and returns a copy of this string with all 8353uppercase letters changed to lowercase. 8354All other characters are left unchanged. 8355The definition of what an uppercase letter is depends on the current locale. 8356 8357 8358 8359 8360<p> 8361<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3> 8362Looks for the first <em>match</em> of 8363<code>pattern</code> (see <a href="#6.4.1">§6.4.1</a>) in the string <code>s</code>. 8364If it finds one, then <code>match</code> returns 8365the captures from the pattern; 8366otherwise it returns <b>nil</b>. 8367If <code>pattern</code> specifies no captures, 8368then the whole match is returned. 8369A third, optional numeric argument <code>init</code> specifies 8370where to start the search; 8371its default value is 1 and can be negative. 8372 8373 8374 8375 8376<p> 8377<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, ···)</code></a></h3> 8378 8379 8380<p> 8381Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc. 8382packed (that is, serialized in binary form) 8383according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>). 8384 8385 8386 8387 8388<p> 8389<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3> 8390 8391 8392<p> 8393Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a> 8394with the given format. 8395The format string cannot have the variable-length options 8396'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">§6.4.2</a>). 8397 8398 8399 8400 8401<p> 8402<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3> 8403Returns a string that is the concatenation of <code>n</code> copies of 8404the string <code>s</code> separated by the string <code>sep</code>. 8405The default value for <code>sep</code> is the empty string 8406(that is, no separator). 8407Returns the empty string if <code>n</code> is not positive. 8408 8409 8410<p> 8411(Note that it is very easy to exhaust the memory of your machine 8412with a single call to this function.) 8413 8414 8415 8416 8417<p> 8418<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3> 8419Returns a string that is the string <code>s</code> reversed. 8420 8421 8422 8423 8424<p> 8425<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3> 8426Returns the substring of <code>s</code> that 8427starts at <code>i</code> and continues until <code>j</code>; 8428<code>i</code> and <code>j</code> can be negative. 8429If <code>j</code> is absent, then it is assumed to be equal to -1 8430(which is the same as the string length). 8431In particular, 8432the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code> 8433with length <code>j</code>, 8434and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code> 8435with length <code>i</code>. 8436 8437 8438<p> 8439If, after the translation of negative indices, 8440<code>i</code> is less than 1, 8441it is corrected to 1. 8442If <code>j</code> is greater than the string length, 8443it is corrected to that length. 8444If, after these corrections, 8445<code>i</code> is greater than <code>j</code>, 8446the function returns the empty string. 8447 8448 8449 8450 8451<p> 8452<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3> 8453 8454 8455<p> 8456Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>) 8457according to the format string <code>fmt</code> (see <a href="#6.4.2">§6.4.2</a>). 8458An optional <code>pos</code> marks where 8459to start reading in <code>s</code> (default is 1). 8460After the read values, 8461this function also returns the index of the first unread byte in <code>s</code>. 8462 8463 8464 8465 8466<p> 8467<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3> 8468Receives a string and returns a copy of this string with all 8469lowercase letters changed to uppercase. 8470All other characters are left unchanged. 8471The definition of what a lowercase letter is depends on the current locale. 8472 8473 8474 8475 8476 8477<h3>6.4.1 – <a name="6.4.1">Patterns</a></h3> 8478 8479<p> 8480Patterns in Lua are described by regular strings, 8481which are interpreted as patterns by the pattern-matching functions 8482<a href="#pdf-string.find"><code>string.find</code></a>, 8483<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>, 8484<a href="#pdf-string.gsub"><code>string.gsub</code></a>, 8485and <a href="#pdf-string.match"><code>string.match</code></a>. 8486This section describes the syntax and the meaning 8487(that is, what they match) of these strings. 8488 8489 8490 8491<h4>Character Class:</h4><p> 8492A <em>character class</em> is used to represent a set of characters. 8493The following combinations are allowed in describing a character class: 8494 8495<ul> 8496 8497<li><b><em>x</em>: </b> 8498(where <em>x</em> is not one of the <em>magic characters</em> 8499<code>^$()%.[]*+-?</code>) 8500represents the character <em>x</em> itself. 8501</li> 8502 8503<li><b><code>.</code>: </b> (a dot) represents all characters.</li> 8504 8505<li><b><code>%a</code>: </b> represents all letters.</li> 8506 8507<li><b><code>%c</code>: </b> represents all control characters.</li> 8508 8509<li><b><code>%d</code>: </b> represents all digits.</li> 8510 8511<li><b><code>%g</code>: </b> represents all printable characters except space.</li> 8512 8513<li><b><code>%l</code>: </b> represents all lowercase letters.</li> 8514 8515<li><b><code>%p</code>: </b> represents all punctuation characters.</li> 8516 8517<li><b><code>%s</code>: </b> represents all space characters.</li> 8518 8519<li><b><code>%u</code>: </b> represents all uppercase letters.</li> 8520 8521<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li> 8522 8523<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li> 8524 8525<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character) 8526represents the character <em>x</em>. 8527This is the standard way to escape the magic characters. 8528Any non-alphanumeric character 8529(including all punctuation characters, even the non-magical) 8530can be preceded by a '<code>%</code>' 8531when used to represent itself in a pattern. 8532</li> 8533 8534<li><b><code>[<em>set</em>]</code>: </b> 8535represents the class which is the union of all 8536characters in <em>set</em>. 8537A range of characters can be specified by 8538separating the end characters of the range, 8539in ascending order, with a '<code>-</code>'. 8540All classes <code>%</code><em>x</em> described above can also be used as 8541components in <em>set</em>. 8542All other characters in <em>set</em> represent themselves. 8543For example, <code>[%w_]</code> (or <code>[_%w]</code>) 8544represents all alphanumeric characters plus the underscore, 8545<code>[0-7]</code> represents the octal digits, 8546and <code>[0-7%l%-]</code> represents the octal digits plus 8547the lowercase letters plus the '<code>-</code>' character. 8548 8549 8550<p> 8551The interaction between ranges and classes is not defined. 8552Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code> 8553have no meaning. 8554</li> 8555 8556<li><b><code>[^<em>set</em>]</code>: </b> 8557represents the complement of <em>set</em>, 8558where <em>set</em> is interpreted as above. 8559</li> 8560 8561</ul><p> 8562For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.), 8563the corresponding uppercase letter represents the complement of the class. 8564For instance, <code>%S</code> represents all non-space characters. 8565 8566 8567<p> 8568The definitions of letter, space, and other character groups 8569depend on the current locale. 8570In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>. 8571 8572 8573 8574 8575 8576<h4>Pattern Item:</h4><p> 8577A <em>pattern item</em> can be 8578 8579<ul> 8580 8581<li> 8582a single character class, 8583which matches any single character in the class; 8584</li> 8585 8586<li> 8587a single character class followed by '<code>*</code>', 8588which matches zero or more repetitions of characters in the class. 8589These repetition items will always match the longest possible sequence; 8590</li> 8591 8592<li> 8593a single character class followed by '<code>+</code>', 8594which matches one or more repetitions of characters in the class. 8595These repetition items will always match the longest possible sequence; 8596</li> 8597 8598<li> 8599a single character class followed by '<code>-</code>', 8600which also matches zero or more repetitions of characters in the class. 8601Unlike '<code>*</code>', 8602these repetition items will always match the shortest possible sequence; 8603</li> 8604 8605<li> 8606a single character class followed by '<code>?</code>', 8607which matches zero or one occurrence of a character in the class. 8608It always matches one occurrence if possible; 8609</li> 8610 8611<li> 8612<code>%<em>n</em></code>, for <em>n</em> between 1 and 9; 8613such item matches a substring equal to the <em>n</em>-th captured string 8614(see below); 8615</li> 8616 8617<li> 8618<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters; 8619such item matches strings that start with <em>x</em>, end with <em>y</em>, 8620and where the <em>x</em> and <em>y</em> are <em>balanced</em>. 8621This means that, if one reads the string from left to right, 8622counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>, 8623the ending <em>y</em> is the first <em>y</em> where the count reaches 0. 8624For instance, the item <code>%b()</code> matches expressions with 8625balanced parentheses. 8626</li> 8627 8628<li> 8629<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>; 8630such item matches an empty string at any position such that 8631the next character belongs to <em>set</em> 8632and the previous character does not belong to <em>set</em>. 8633The set <em>set</em> is interpreted as previously described. 8634The beginning and the end of the subject are handled as if 8635they were the character '<code>\0</code>'. 8636</li> 8637 8638</ul> 8639 8640 8641 8642 8643<h4>Pattern:</h4><p> 8644A <em>pattern</em> is a sequence of pattern items. 8645A caret '<code>^</code>' at the beginning of a pattern anchors the match at the 8646beginning of the subject string. 8647A '<code>$</code>' at the end of a pattern anchors the match at the 8648end of the subject string. 8649At other positions, 8650'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves. 8651 8652 8653 8654 8655 8656<h4>Captures:</h4><p> 8657A pattern can contain sub-patterns enclosed in parentheses; 8658they describe <em>captures</em>. 8659When a match succeeds, the substrings of the subject string 8660that match captures are stored (<em>captured</em>) for future use. 8661Captures are numbered according to their left parentheses. 8662For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>, 8663the part of the string matching <code>"a*(.)%w(%s*)"</code> is 8664stored as the first capture (and therefore has number 1); 8665the character matching "<code>.</code>" is captured with number 2, 8666and the part matching "<code>%s*</code>" has number 3. 8667 8668 8669<p> 8670As a special case, the empty capture <code>()</code> captures 8671the current string position (a number). 8672For instance, if we apply the pattern <code>"()aa()"</code> on the 8673string <code>"flaaap"</code>, there will be two captures: 3 and 5. 8674 8675 8676 8677 8678 8679 8680 8681<h3>6.4.2 – <a name="6.4.2">Format Strings for Pack and Unpack</a></h3> 8682 8683<p> 8684The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>, 8685<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a> 8686is a format string, 8687which describes the layout of the structure being created or read. 8688 8689 8690<p> 8691A format string is a sequence of conversion options. 8692The conversion options are as follows: 8693 8694<ul> 8695<li><b><code><</code>: </b>sets little endian</li> 8696<li><b><code>></code>: </b>sets big endian</li> 8697<li><b><code>=</code>: </b>sets native endian</li> 8698<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code> 8699(default is native alignment)</li> 8700<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li> 8701<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li> 8702<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li> 8703<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li> 8704<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li> 8705<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li> 8706<li><b><code>j</code>: </b>a <code>lua_Integer</code></li> 8707<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li> 8708<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li> 8709<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes 8710(default is native size)</li> 8711<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes 8712(default is native size)</li> 8713<li><b><code>f</code>: </b>a <code>float</code> (native size)</li> 8714<li><b><code>d</code>: </b>a <code>double</code> (native size)</li> 8715<li><b><code>n</code>: </b>a <code>lua_Number</code></li> 8716<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li> 8717<li><b><code>z</code>: </b>a zero-terminated string</li> 8718<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length 8719coded as an unsigned integer with <code>n</code> bytes 8720(default is a <code>size_t</code>)</li> 8721<li><b><code>x</code>: </b>one byte of padding</li> 8722<li><b><code>X<em>op</em></code>: </b>an empty item that aligns 8723according to option <code>op</code> 8724(which is otherwise ignored)</li> 8725<li><b>'<code> </code>': </b>(empty space) ignored</li> 8726</ul><p> 8727(A "<code>[<em>n</em>]</code>" means an optional integral numeral.) 8728Except for padding, spaces, and configurations 8729(options "<code>xX <=>!</code>"), 8730each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>) 8731or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>). 8732 8733 8734<p> 8735For 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>", 8736<code>n</code> can be any integer between 1 and 16. 8737All integral options check overflows; 8738<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size; 8739<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer. 8740 8741 8742<p> 8743Any format string starts as if prefixed by "<code>!1=</code>", 8744that is, 8745with maximum alignment of 1 (no alignment) 8746and native endianness. 8747 8748 8749<p> 8750Alignment works as follows: 8751For each option, 8752the format gets extra padding until the data starts 8753at an offset that is a multiple of the minimum between the 8754option size and the maximum alignment; 8755this minimum must be a power of 2. 8756Options "<code>c</code>" and "<code>z</code>" are not aligned; 8757option "<code>s</code>" follows the alignment of its starting integer. 8758 8759 8760<p> 8761All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a> 8762(and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>). 8763 8764 8765 8766 8767 8768 8769 8770<h2>6.5 – <a name="6.5">UTF-8 Support</a></h2> 8771 8772<p> 8773This library provides basic support for UTF-8 encoding. 8774It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>. 8775This library does not provide any support for Unicode other 8776than the handling of the encoding. 8777Any operation that needs the meaning of a character, 8778such as character classification, is outside its scope. 8779 8780 8781<p> 8782Unless stated otherwise, 8783all functions that expect a byte position as a parameter 8784assume that the given position is either the start of a byte sequence 8785or one plus the length of the subject string. 8786As in the string library, 8787negative indices count from the end of the string. 8788 8789 8790<p> 8791<hr><h3><a name="pdf-utf8.char"><code>utf8.char (···)</code></a></h3> 8792Receives zero or more integers, 8793converts each one to its corresponding UTF-8 byte sequence 8794and returns a string with the concatenation of all these sequences. 8795 8796 8797 8798 8799<p> 8800<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3> 8801The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>" 8802(see <a href="#6.4.1">§6.4.1</a>), 8803which matches exactly one UTF-8 byte sequence, 8804assuming that the subject is a valid UTF-8 string. 8805 8806 8807 8808 8809<p> 8810<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3> 8811 8812 8813<p> 8814Returns values so that the construction 8815 8816<pre> 8817 for p, c in utf8.codes(s) do <em>body</em> end 8818</pre><p> 8819will iterate over all characters in string <code>s</code>, 8820with <code>p</code> being the position (in bytes) and <code>c</code> the code point 8821of each character. 8822It raises an error if it meets any invalid byte sequence. 8823 8824 8825 8826 8827<p> 8828<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3> 8829Returns the codepoints (as integers) from all characters in <code>s</code> 8830that start between byte position <code>i</code> and <code>j</code> (both included). 8831The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>. 8832It raises an error if it meets any invalid byte sequence. 8833 8834 8835 8836 8837<p> 8838<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3> 8839Returns the number of UTF-8 characters in string <code>s</code> 8840that start between positions <code>i</code> and <code>j</code> (both inclusive). 8841The default for <code>i</code> is 1 and for <code>j</code> is -1. 8842If it finds any invalid byte sequence, 8843returns a false value plus the position of the first invalid byte. 8844 8845 8846 8847 8848<p> 8849<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3> 8850Returns the position (in bytes) where the encoding of the 8851<code>n</code>-th character of <code>s</code> 8852(counting from position <code>i</code>) starts. 8853A negative <code>n</code> gets characters before position <code>i</code>. 8854The default for <code>i</code> is 1 when <code>n</code> is non-negative 8855and <code>#s + 1</code> otherwise, 8856so that <code>utf8.offset(s, -n)</code> gets the offset of the 8857<code>n</code>-th character from the end of the string. 8858If the specified character is neither in the subject 8859nor right after its end, 8860the function returns <b>nil</b>. 8861 8862 8863<p> 8864As a special case, 8865when <code>n</code> is 0 the function returns the start of the encoding 8866of the character that contains the <code>i</code>-th byte of <code>s</code>. 8867 8868 8869<p> 8870This function assumes that <code>s</code> is a valid UTF-8 string. 8871 8872 8873 8874 8875 8876 8877 8878<h2>6.6 – <a name="6.6">Table Manipulation</a></h2> 8879 8880<p> 8881This library provides generic functions for table manipulation. 8882It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>. 8883 8884 8885<p> 8886Remember that, whenever an operation needs the length of a table, 8887the table must be a proper sequence 8888or have a <code>__len</code> metamethod (see <a href="#3.4.7">§3.4.7</a>). 8889All functions ignore non-numeric keys 8890in the tables given as arguments. 8891 8892 8893<p> 8894<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3> 8895 8896 8897<p> 8898Given a list where all elements are strings or numbers, 8899returns the string <code>list[i]..sep..list[i+1] ··· sep..list[j]</code>. 8900The default value for <code>sep</code> is the empty string, 8901the default for <code>i</code> is 1, 8902and the default for <code>j</code> is <code>#list</code>. 8903If <code>i</code> is greater than <code>j</code>, returns the empty string. 8904 8905 8906 8907 8908<p> 8909<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3> 8910 8911 8912<p> 8913Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>, 8914shifting up the elements 8915<code>list[pos], list[pos+1], ···, list[#list]</code>. 8916The default value for <code>pos</code> is <code>#list+1</code>, 8917so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end 8918of list <code>t</code>. 8919 8920 8921 8922 8923<p> 8924<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3> 8925 8926 8927<p> 8928Moves elements from table <code>a1</code> to table <code>a2</code>. 8929This function performs the equivalent to the following 8930multiple assignment: 8931<code>a2[t],··· = a1[f],···,a1[e]</code>. 8932The default for <code>a2</code> is <code>a1</code>. 8933The destination range can overlap with the source range. 8934The number of elements to be moved must fit in a Lua integer. 8935 8936 8937 8938 8939<p> 8940<hr><h3><a name="pdf-table.pack"><code>table.pack (···)</code></a></h3> 8941 8942 8943<p> 8944Returns a new table with all parameters stored into keys 1, 2, etc. 8945and with a field "<code>n</code>" with the total number of parameters. 8946Note that the resulting table may not be a sequence. 8947 8948 8949 8950 8951<p> 8952<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3> 8953 8954 8955<p> 8956Removes from <code>list</code> the element at position <code>pos</code>, 8957returning the value of the removed element. 8958When <code>pos</code> is an integer between 1 and <code>#list</code>, 8959it shifts down the elements 8960<code>list[pos+1], list[pos+2], ···, list[#list]</code> 8961and erases element <code>list[#list]</code>; 8962The index <code>pos</code> can also be 0 when <code>#list</code> is 0, 8963or <code>#list + 1</code>; 8964in those cases, the function erases the element <code>list[pos]</code>. 8965 8966 8967<p> 8968The default value for <code>pos</code> is <code>#list</code>, 8969so that a call <code>table.remove(l)</code> removes the last element 8970of list <code>l</code>. 8971 8972 8973 8974 8975<p> 8976<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3> 8977 8978 8979<p> 8980Sorts list elements in a given order, <em>in-place</em>, 8981from <code>list[1]</code> to <code>list[#list]</code>. 8982If <code>comp</code> is given, 8983then it must be a function that receives two list elements 8984and returns true when the first element must come 8985before the second in the final order 8986(so that, after the sort, 8987<code>i < j</code> implies <code>not comp(list[j],list[i])</code>). 8988If <code>comp</code> is not given, 8989then the standard Lua operator <code><</code> is used instead. 8990 8991 8992<p> 8993Note that the <code>comp</code> function must define 8994a strict partial order over the elements in the list; 8995that is, it must be asymmetric and transitive. 8996Otherwise, no valid sort may be possible. 8997 8998 8999<p> 9000The sort algorithm is not stable; 9001that is, elements not comparable by the given order 9002(e.g., equal elements) 9003may have their relative positions changed by the sort. 9004 9005 9006 9007 9008<p> 9009<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3> 9010 9011 9012<p> 9013Returns the elements from the given list. 9014This function is equivalent to 9015 9016<pre> 9017 return list[i], list[i+1], ···, list[j] 9018</pre><p> 9019By default, <code>i</code> is 1 and <code>j</code> is <code>#list</code>. 9020 9021 9022 9023 9024 9025 9026 9027<h2>6.7 – <a name="6.7">Mathematical Functions</a></h2> 9028 9029<p> 9030This library provides basic mathematical functions. 9031It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>. 9032Functions with the annotation "<code>integer/float</code>" give 9033integer results for integer arguments 9034and float results for float (or mixed) arguments. 9035Rounding functions 9036(<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>) 9037return an integer when the result fits in the range of an integer, 9038or a float otherwise. 9039 9040 9041<p> 9042<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3> 9043 9044 9045<p> 9046Returns the absolute value of <code>x</code>. (integer/float) 9047 9048 9049 9050 9051<p> 9052<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3> 9053 9054 9055<p> 9056Returns the arc cosine of <code>x</code> (in radians). 9057 9058 9059 9060 9061<p> 9062<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3> 9063 9064 9065<p> 9066Returns the arc sine of <code>x</code> (in radians). 9067 9068 9069 9070 9071<p> 9072<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3> 9073 9074 9075<p> 9076 9077Returns the arc tangent of <code>y/x</code> (in radians), 9078but uses the signs of both parameters to find the 9079quadrant of the result. 9080(It also handles correctly the case of <code>x</code> being zero.) 9081 9082 9083<p> 9084The default value for <code>x</code> is 1, 9085so that the call <code>math.atan(y)</code> 9086returns the arc tangent of <code>y</code>. 9087 9088 9089 9090 9091<p> 9092<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3> 9093 9094 9095<p> 9096Returns the smallest integral value larger than or equal to <code>x</code>. 9097 9098 9099 9100 9101<p> 9102<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3> 9103 9104 9105<p> 9106Returns the cosine of <code>x</code> (assumed to be in radians). 9107 9108 9109 9110 9111<p> 9112<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3> 9113 9114 9115<p> 9116Converts the angle <code>x</code> from radians to degrees. 9117 9118 9119 9120 9121<p> 9122<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3> 9123 9124 9125<p> 9126Returns the value <em>e<sup>x</sup></em> 9127(where <code>e</code> is the base of natural logarithms). 9128 9129 9130 9131 9132<p> 9133<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3> 9134 9135 9136<p> 9137Returns the largest integral value smaller than or equal to <code>x</code>. 9138 9139 9140 9141 9142<p> 9143<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3> 9144 9145 9146<p> 9147Returns the remainder of the division of <code>x</code> by <code>y</code> 9148that rounds the quotient towards zero. (integer/float) 9149 9150 9151 9152 9153<p> 9154<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3> 9155 9156 9157<p> 9158The float value <code>HUGE_VAL</code>, 9159a value larger than any other numeric value. 9160 9161 9162 9163 9164<p> 9165<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3> 9166 9167 9168<p> 9169Returns the logarithm of <code>x</code> in the given base. 9170The default for <code>base</code> is <em>e</em> 9171(so that the function returns the natural logarithm of <code>x</code>). 9172 9173 9174 9175 9176<p> 9177<hr><h3><a name="pdf-math.max"><code>math.max (x, ···)</code></a></h3> 9178 9179 9180<p> 9181Returns the argument with the maximum value, 9182according to the Lua operator <code><</code>. (integer/float) 9183 9184 9185 9186 9187<p> 9188<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3> 9189An integer with the maximum value for an integer. 9190 9191 9192 9193 9194<p> 9195<hr><h3><a name="pdf-math.min"><code>math.min (x, ···)</code></a></h3> 9196 9197 9198<p> 9199Returns the argument with the minimum value, 9200according to the Lua operator <code><</code>. (integer/float) 9201 9202 9203 9204 9205<p> 9206<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3> 9207An integer with the minimum value for an integer. 9208 9209 9210 9211 9212<p> 9213<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3> 9214 9215 9216<p> 9217Returns the integral part of <code>x</code> and the fractional part of <code>x</code>. 9218Its second result is always a float. 9219 9220 9221 9222 9223<p> 9224<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3> 9225 9226 9227<p> 9228The value of <em>π</em>. 9229 9230 9231 9232 9233<p> 9234<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3> 9235 9236 9237<p> 9238Converts the angle <code>x</code> from degrees to radians. 9239 9240 9241 9242 9243<p> 9244<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3> 9245 9246 9247<p> 9248When called without arguments, 9249returns a pseudo-random float with uniform distribution 9250in the range <em>[0,1)</em>. 9251When called with two integers <code>m</code> and <code>n</code>, 9252<code>math.random</code> returns a pseudo-random integer 9253with uniform distribution in the range <em>[m, n]</em>. 9254(The value <em>n-m</em> cannot be negative and must fit in a Lua integer.) 9255The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>. 9256 9257 9258<p> 9259This function is an interface to the underling 9260pseudo-random generator function provided by C. 9261 9262 9263 9264 9265<p> 9266<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3> 9267 9268 9269<p> 9270Sets <code>x</code> as the "seed" 9271for the pseudo-random generator: 9272equal seeds produce equal sequences of numbers. 9273 9274 9275 9276 9277<p> 9278<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3> 9279 9280 9281<p> 9282Returns the sine of <code>x</code> (assumed to be in radians). 9283 9284 9285 9286 9287<p> 9288<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3> 9289 9290 9291<p> 9292Returns the square root of <code>x</code>. 9293(You can also use the expression <code>x^0.5</code> to compute this value.) 9294 9295 9296 9297 9298<p> 9299<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3> 9300 9301 9302<p> 9303Returns the tangent of <code>x</code> (assumed to be in radians). 9304 9305 9306 9307 9308<p> 9309<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3> 9310 9311 9312<p> 9313If the value <code>x</code> is convertible to an integer, 9314returns that integer. 9315Otherwise, returns <b>nil</b>. 9316 9317 9318 9319 9320<p> 9321<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3> 9322 9323 9324<p> 9325Returns "<code>integer</code>" if <code>x</code> is an integer, 9326"<code>float</code>" if it is a float, 9327or <b>nil</b> if <code>x</code> is not a number. 9328 9329 9330 9331 9332<p> 9333<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3> 9334 9335 9336<p> 9337Returns a boolean, 9338true if integer <code>m</code> is below integer <code>n</code> when 9339they are compared as unsigned integers. 9340 9341 9342 9343 9344 9345 9346 9347<h2>6.8 – <a name="6.8">Input and Output Facilities</a></h2> 9348 9349<p> 9350The I/O library provides two different styles for file manipulation. 9351The first one uses implicit file handles; 9352that is, there are operations to set a default input file and a 9353default output file, 9354and all input/output operations are over these default files. 9355The second style uses explicit file handles. 9356 9357 9358<p> 9359When using implicit file handles, 9360all operations are supplied by table <a name="pdf-io"><code>io</code></a>. 9361When using explicit file handles, 9362the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle 9363and then all operations are supplied as methods of the file handle. 9364 9365 9366<p> 9367The table <code>io</code> also provides 9368three predefined file handles with their usual meanings from C: 9369<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>. 9370The I/O library never closes these files. 9371 9372 9373<p> 9374Unless otherwise stated, 9375all I/O functions return <b>nil</b> on failure 9376(plus an error message as a second result and 9377a system-dependent error code as a third result) 9378and some value different from <b>nil</b> on success. 9379On non-POSIX systems, 9380the computation of the error message and error code 9381in case of errors 9382may be not thread safe, 9383because they rely on the global C variable <code>errno</code>. 9384 9385 9386<p> 9387<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3> 9388 9389 9390<p> 9391Equivalent to <code>file:close()</code>. 9392Without a <code>file</code>, closes the default output file. 9393 9394 9395 9396 9397<p> 9398<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3> 9399 9400 9401<p> 9402Equivalent to <code>io.output():flush()</code>. 9403 9404 9405 9406 9407<p> 9408<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3> 9409 9410 9411<p> 9412When called with a file name, it opens the named file (in text mode), 9413and sets its handle as the default input file. 9414When called with a file handle, 9415it simply sets this file handle as the default input file. 9416When called without parameters, 9417it returns the current default input file. 9418 9419 9420<p> 9421In case of errors this function raises the error, 9422instead of returning an error code. 9423 9424 9425 9426 9427<p> 9428<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, ···])</code></a></h3> 9429 9430 9431<p> 9432Opens the given file name in read mode 9433and returns an iterator function that 9434works like <code>file:lines(···)</code> over the opened file. 9435When the iterator function detects the end of file, 9436it returns no values (to finish the loop) and automatically closes the file. 9437 9438 9439<p> 9440The call <code>io.lines()</code> (with no file name) is equivalent 9441to <code>io.input():lines("*l")</code>; 9442that is, it iterates over the lines of the default input file. 9443In this case it does not close the file when the loop ends. 9444 9445 9446<p> 9447In case of errors this function raises the error, 9448instead of returning an error code. 9449 9450 9451 9452 9453<p> 9454<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3> 9455 9456 9457<p> 9458This function opens a file, 9459in the mode specified in the string <code>mode</code>. 9460It returns a new file handle, 9461or, in case of errors, <b>nil</b> plus an error message. 9462 9463 9464<p> 9465The <code>mode</code> string can be any of the following: 9466 9467<ul> 9468<li><b>"<code>r</code>": </b> read mode (the default);</li> 9469<li><b>"<code>w</code>": </b> write mode;</li> 9470<li><b>"<code>a</code>": </b> append mode;</li> 9471<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li> 9472<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li> 9473<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved, 9474 writing is only allowed at the end of file.</li> 9475</ul><p> 9476The <code>mode</code> string can also have a '<code>b</code>' at the end, 9477which is needed in some systems to open the file in binary mode. 9478 9479 9480 9481 9482<p> 9483<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3> 9484 9485 9486<p> 9487Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file. 9488 9489 9490 9491 9492<p> 9493<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3> 9494 9495 9496<p> 9497This function is system dependent and is not available 9498on all platforms. 9499 9500 9501<p> 9502Starts program <code>prog</code> in a separated process and returns 9503a file handle that you can use to read data from this program 9504(if <code>mode</code> is <code>"r"</code>, the default) 9505or to write data to this program 9506(if <code>mode</code> is <code>"w"</code>). 9507 9508 9509 9510 9511<p> 9512<hr><h3><a name="pdf-io.read"><code>io.read (···)</code></a></h3> 9513 9514 9515<p> 9516Equivalent to <code>io.input():read(···)</code>. 9517 9518 9519 9520 9521<p> 9522<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3> 9523 9524 9525<p> 9526Returns a handle for a temporary file. 9527This file is opened in update mode 9528and it is automatically removed when the program ends. 9529 9530 9531 9532 9533<p> 9534<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3> 9535 9536 9537<p> 9538Checks whether <code>obj</code> is a valid file handle. 9539Returns the string <code>"file"</code> if <code>obj</code> is an open file handle, 9540<code>"closed file"</code> if <code>obj</code> is a closed file handle, 9541or <b>nil</b> if <code>obj</code> is not a file handle. 9542 9543 9544 9545 9546<p> 9547<hr><h3><a name="pdf-io.write"><code>io.write (···)</code></a></h3> 9548 9549 9550<p> 9551Equivalent to <code>io.output():write(···)</code>. 9552 9553 9554 9555 9556<p> 9557<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3> 9558 9559 9560<p> 9561Closes <code>file</code>. 9562Note that files are automatically closed when 9563their handles are garbage collected, 9564but that takes an unpredictable amount of time to happen. 9565 9566 9567<p> 9568When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>, 9569<a href="#pdf-file:close"><code>file:close</code></a> returns the same values 9570returned by <a href="#pdf-os.execute"><code>os.execute</code></a>. 9571 9572 9573 9574 9575<p> 9576<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3> 9577 9578 9579<p> 9580Saves any written data to <code>file</code>. 9581 9582 9583 9584 9585<p> 9586<hr><h3><a name="pdf-file:lines"><code>file:lines (···)</code></a></h3> 9587 9588 9589<p> 9590Returns an iterator function that, 9591each time it is called, 9592reads the file according to the given formats. 9593When no format is given, 9594uses "<code>l</code>" as a default. 9595As an example, the construction 9596 9597<pre> 9598 for c in file:lines(1) do <em>body</em> end 9599</pre><p> 9600will iterate over all characters of the file, 9601starting at the current position. 9602Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file 9603when the loop ends. 9604 9605 9606<p> 9607In case of errors this function raises the error, 9608instead of returning an error code. 9609 9610 9611 9612 9613<p> 9614<hr><h3><a name="pdf-file:read"><code>file:read (···)</code></a></h3> 9615 9616 9617<p> 9618Reads the file <code>file</code>, 9619according to the given formats, which specify what to read. 9620For each format, 9621the function returns a string or a number with the characters read, 9622or <b>nil</b> if it cannot read data with the specified format. 9623(In this latter case, 9624the function does not read subsequent formats.) 9625When called without formats, 9626it uses a default format that reads the next line 9627(see below). 9628 9629 9630<p> 9631The available formats are 9632 9633<ul> 9634 9635<li><b>"<code>n</code>": </b> 9636reads a numeral and returns it as a float or an integer, 9637following the lexical conventions of Lua. 9638(The numeral may have leading spaces and a sign.) 9639This format always reads the longest input sequence that 9640is a valid prefix for a numeral; 9641if that prefix does not form a valid numeral 9642(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"), 9643it is discarded and the function returns <b>nil</b>. 9644</li> 9645 9646<li><b>"<code>a</code>": </b> 9647reads the whole file, starting at the current position. 9648On end of file, it returns the empty string. 9649</li> 9650 9651<li><b>"<code>l</code>": </b> 9652reads the next line skipping the end of line, 9653returning <b>nil</b> on end of file. 9654This is the default format. 9655</li> 9656 9657<li><b>"<code>L</code>": </b> 9658reads the next line keeping the end-of-line character (if present), 9659returning <b>nil</b> on end of file. 9660</li> 9661 9662<li><b><em>number</em>: </b> 9663reads a string with up to this number of bytes, 9664returning <b>nil</b> on end of file. 9665If <code>number</code> is zero, 9666it reads nothing and returns an empty string, 9667or <b>nil</b> on end of file. 9668</li> 9669 9670</ul><p> 9671The formats "<code>l</code>" and "<code>L</code>" should be used only for text files. 9672 9673 9674 9675 9676<p> 9677<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3> 9678 9679 9680<p> 9681Sets and gets the file position, 9682measured from the beginning of the file, 9683to the position given by <code>offset</code> plus a base 9684specified by the string <code>whence</code>, as follows: 9685 9686<ul> 9687<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li> 9688<li><b>"<code>cur</code>": </b> base is current position;</li> 9689<li><b>"<code>end</code>": </b> base is end of file;</li> 9690</ul><p> 9691In case of success, <code>seek</code> returns the final file position, 9692measured in bytes from the beginning of the file. 9693If <code>seek</code> fails, it returns <b>nil</b>, 9694plus a string describing the error. 9695 9696 9697<p> 9698The default value for <code>whence</code> is <code>"cur"</code>, 9699and for <code>offset</code> is 0. 9700Therefore, the call <code>file:seek()</code> returns the current 9701file position, without changing it; 9702the call <code>file:seek("set")</code> sets the position to the 9703beginning of the file (and returns 0); 9704and the call <code>file:seek("end")</code> sets the position to the 9705end of the file, and returns its size. 9706 9707 9708 9709 9710<p> 9711<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3> 9712 9713 9714<p> 9715Sets the buffering mode for an output file. 9716There are three available modes: 9717 9718<ul> 9719 9720<li><b>"<code>no</code>": </b> 9721no buffering; the result of any output operation appears immediately. 9722</li> 9723 9724<li><b>"<code>full</code>": </b> 9725full buffering; output operation is performed only 9726when the buffer is full or when 9727you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>). 9728</li> 9729 9730<li><b>"<code>line</code>": </b> 9731line buffering; output is buffered until a newline is output 9732or there is any input from some special files 9733(such as a terminal device). 9734</li> 9735 9736</ul><p> 9737For the last two cases, <code>size</code> 9738specifies the size of the buffer, in bytes. 9739The default is an appropriate size. 9740 9741 9742 9743 9744<p> 9745<hr><h3><a name="pdf-file:write"><code>file:write (···)</code></a></h3> 9746 9747 9748<p> 9749Writes the value of each of its arguments to <code>file</code>. 9750The arguments must be strings or numbers. 9751 9752 9753<p> 9754In case of success, this function returns <code>file</code>. 9755Otherwise it returns <b>nil</b> plus a string describing the error. 9756 9757 9758 9759 9760 9761 9762 9763<h2>6.9 – <a name="6.9">Operating System Facilities</a></h2> 9764 9765<p> 9766This library is implemented through table <a name="pdf-os"><code>os</code></a>. 9767 9768 9769<p> 9770<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3> 9771 9772 9773<p> 9774Returns an approximation of the amount in seconds of CPU time 9775used by the program. 9776 9777 9778 9779 9780<p> 9781<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3> 9782 9783 9784<p> 9785Returns a string or a table containing date and time, 9786formatted according to the given string <code>format</code>. 9787 9788 9789<p> 9790If the <code>time</code> argument is present, 9791this is the time to be formatted 9792(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value). 9793Otherwise, <code>date</code> formats the current time. 9794 9795 9796<p> 9797If <code>format</code> starts with '<code>!</code>', 9798then the date is formatted in Coordinated Universal Time. 9799After this optional character, 9800if <code>format</code> is the string "<code>*t</code>", 9801then <code>date</code> returns a table with the following fields: 9802<code>year</code>, <code>month</code> (1–12), <code>day</code> (1–31), 9803<code>hour</code> (0–23), <code>min</code> (0–59), <code>sec</code> (0–61), 9804<code>wday</code> (weekday, Sunday is 1), 9805<code>yday</code> (day of the year), 9806and <code>isdst</code> (daylight saving flag, a boolean). 9807This last field may be absent 9808if the information is not available. 9809 9810 9811<p> 9812If <code>format</code> is not "<code>*t</code>", 9813then <code>date</code> returns the date as a string, 9814formatted according to the same rules as the ISO C function <code>strftime</code>. 9815 9816 9817<p> 9818When called without arguments, 9819<code>date</code> returns a reasonable date and time representation that depends on 9820the host system and on the current locale. 9821(More specifically, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>.) 9822 9823 9824<p> 9825On non-POSIX systems, 9826this function may be not thread safe 9827because of its reliance on C function <code>gmtime</code> and C function <code>localtime</code>. 9828 9829 9830 9831 9832<p> 9833<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3> 9834 9835 9836<p> 9837Returns the difference, in seconds, 9838from time <code>t1</code> to time <code>t2</code> 9839(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>). 9840In POSIX, Windows, and some other systems, 9841this value is exactly <code>t2</code><em>-</em><code>t1</code>. 9842 9843 9844 9845 9846<p> 9847<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3> 9848 9849 9850<p> 9851This function is equivalent to the ISO C function <code>system</code>. 9852It passes <code>command</code> to be executed by an operating system shell. 9853Its first result is <b>true</b> 9854if the command terminated successfully, 9855or <b>nil</b> otherwise. 9856After this first result 9857the function returns a string plus a number, 9858as follows: 9859 9860<ul> 9861 9862<li><b>"<code>exit</code>": </b> 9863the command terminated normally; 9864the following number is the exit status of the command. 9865</li> 9866 9867<li><b>"<code>signal</code>": </b> 9868the command was terminated by a signal; 9869the following number is the signal that terminated the command. 9870</li> 9871 9872</ul> 9873 9874<p> 9875When called without a <code>command</code>, 9876<code>os.execute</code> returns a boolean that is true if a shell is available. 9877 9878 9879 9880 9881<p> 9882<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3> 9883 9884 9885<p> 9886Calls the ISO C function <code>exit</code> to terminate the host program. 9887If <code>code</code> is <b>true</b>, 9888the returned status is <code>EXIT_SUCCESS</code>; 9889if <code>code</code> is <b>false</b>, 9890the returned status is <code>EXIT_FAILURE</code>; 9891if <code>code</code> is a number, 9892the returned status is this number. 9893The default value for <code>code</code> is <b>true</b>. 9894 9895 9896<p> 9897If the optional second argument <code>close</code> is true, 9898closes the Lua state before exiting. 9899 9900 9901 9902 9903<p> 9904<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3> 9905 9906 9907<p> 9908Returns the value of the process environment variable <code>varname</code>, 9909or <b>nil</b> if the variable is not defined. 9910 9911 9912 9913 9914<p> 9915<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3> 9916 9917 9918<p> 9919Deletes the file (or empty directory, on POSIX systems) 9920with the given name. 9921If this function fails, it returns <b>nil</b>, 9922plus a string describing the error and the error code. 9923 9924 9925 9926 9927<p> 9928<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3> 9929 9930 9931<p> 9932Renames file or directory named <code>oldname</code> to <code>newname</code>. 9933If this function fails, it returns <b>nil</b>, 9934plus a string describing the error and the error code. 9935 9936 9937 9938 9939<p> 9940<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3> 9941 9942 9943<p> 9944Sets the current locale of the program. 9945<code>locale</code> is a system-dependent string specifying a locale; 9946<code>category</code> is an optional string describing which category to change: 9947<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>, 9948<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>; 9949the default category is <code>"all"</code>. 9950The function returns the name of the new locale, 9951or <b>nil</b> if the request cannot be honored. 9952 9953 9954<p> 9955If <code>locale</code> is the empty string, 9956the current locale is set to an implementation-defined native locale. 9957If <code>locale</code> is the string "<code>C</code>", 9958the current locale is set to the standard C locale. 9959 9960 9961<p> 9962When called with <b>nil</b> as the first argument, 9963this function only returns the name of the current locale 9964for the given category. 9965 9966 9967<p> 9968This function may be not thread safe 9969because of its reliance on C function <code>setlocale</code>. 9970 9971 9972 9973 9974<p> 9975<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3> 9976 9977 9978<p> 9979Returns the current time when called without arguments, 9980or a time representing the local date and time specified by the given table. 9981This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>, 9982and may have fields 9983<code>hour</code> (default is 12), 9984<code>min</code> (default is 0), 9985<code>sec</code> (default is 0), 9986and <code>isdst</code> (default is <b>nil</b>). 9987Other fields are ignored. 9988For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function. 9989 9990 9991<p> 9992The values in these fields do not need to be inside their valid ranges. 9993For instance, if <code>sec</code> is -10, 9994it means -10 seconds from the time specified by the other fields; 9995if <code>hour</code> is 1000, 9996it means +1000 hours from the time specified by the other fields. 9997 9998 9999<p> 10000The returned value is a number, whose meaning depends on your system. 10001In POSIX, Windows, and some other systems, 10002this number counts the number 10003of seconds since some given start time (the "epoch"). 10004In other systems, the meaning is not specified, 10005and the number returned by <code>time</code> can be used only as an argument to 10006<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>. 10007 10008 10009 10010 10011<p> 10012<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3> 10013 10014 10015<p> 10016Returns a string with a file name that can 10017be used for a temporary file. 10018The file must be explicitly opened before its use 10019and explicitly removed when no longer needed. 10020 10021 10022<p> 10023On POSIX systems, 10024this function also creates a file with that name, 10025to avoid security risks. 10026(Someone else might create the file with wrong permissions 10027in the time between getting the name and creating the file.) 10028You still have to open the file to use it 10029and to remove it (even if you do not use it). 10030 10031 10032<p> 10033When possible, 10034you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>, 10035which automatically removes the file when the program ends. 10036 10037 10038 10039 10040 10041 10042 10043<h2>6.10 – <a name="6.10">The Debug Library</a></h2> 10044 10045<p> 10046This library provides 10047the functionality of the debug interface (<a href="#4.9">§4.9</a>) to Lua programs. 10048You should exert care when using this library. 10049Several of its functions 10050violate basic assumptions about Lua code 10051(e.g., that variables local to a function 10052cannot be accessed from outside; 10053that userdata metatables cannot be changed by Lua code; 10054that Lua programs do not crash) 10055and therefore can compromise otherwise secure code. 10056Moreover, some functions in this library may be slow. 10057 10058 10059<p> 10060All functions in this library are provided 10061inside the <a name="pdf-debug"><code>debug</code></a> table. 10062All functions that operate over a thread 10063have an optional first argument which is the 10064thread to operate over. 10065The default is always the current thread. 10066 10067 10068<p> 10069<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3> 10070 10071 10072<p> 10073Enters an interactive mode with the user, 10074running each string that the user enters. 10075Using simple commands and other debug facilities, 10076the user can inspect global and local variables, 10077change their values, evaluate expressions, and so on. 10078A line containing only the word <code>cont</code> finishes this function, 10079so that the caller continues its execution. 10080 10081 10082<p> 10083Note that commands for <code>debug.debug</code> are not lexically nested 10084within any function and so have no direct access to local variables. 10085 10086 10087 10088 10089<p> 10090<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3> 10091 10092 10093<p> 10094Returns the current hook settings of the thread, as three values: 10095the current hook function, the current hook mask, 10096and the current hook count 10097(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function). 10098 10099 10100 10101 10102<p> 10103<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3> 10104 10105 10106<p> 10107Returns a table with information about a function. 10108You can give the function directly 10109or you can give a number as the value of <code>f</code>, 10110which means the function running at level <code>f</code> of the call stack 10111of the given thread: 10112level 0 is the current function (<code>getinfo</code> itself); 10113level 1 is the function that called <code>getinfo</code> 10114(except for tail calls, which do not count on the stack); 10115and so on. 10116If <code>f</code> is a number larger than the number of active functions, 10117then <code>getinfo</code> returns <b>nil</b>. 10118 10119 10120<p> 10121The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>, 10122with the string <code>what</code> describing which fields to fill in. 10123The default for <code>what</code> is to get all information available, 10124except the table of valid lines. 10125If present, 10126the option '<code>f</code>' 10127adds a field named <code>func</code> with the function itself. 10128If present, 10129the option '<code>L</code>' 10130adds a field named <code>activelines</code> with the table of 10131valid lines. 10132 10133 10134<p> 10135For instance, the expression <code>debug.getinfo(1,"n").name</code> returns 10136a name for the current function, 10137if a reasonable name can be found, 10138and the expression <code>debug.getinfo(print)</code> 10139returns a table with all available information 10140about the <a href="#pdf-print"><code>print</code></a> function. 10141 10142 10143 10144 10145<p> 10146<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3> 10147 10148 10149<p> 10150This function returns the name and the value of the local variable 10151with index <code>local</code> of the function at level <code>f</code> of the stack. 10152This function accesses not only explicit local variables, 10153but also parameters, temporaries, etc. 10154 10155 10156<p> 10157The first parameter or local variable has index 1, and so on, 10158following the order that they are declared in the code, 10159counting only the variables that are active 10160in the current scope of the function. 10161Negative indices refer to vararg parameters; 10162-1 is the first vararg parameter. 10163The function returns <b>nil</b> if there is no variable with the given index, 10164and raises an error when called with a level out of range. 10165(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.) 10166 10167 10168<p> 10169Variable names starting with '<code>(</code>' (open parenthesis) 10170represent variables with no known names 10171(internal variables such as loop control variables, 10172and variables from chunks saved without debug information). 10173 10174 10175<p> 10176The parameter <code>f</code> may also be a function. 10177In that case, <code>getlocal</code> returns only the name of function parameters. 10178 10179 10180 10181 10182<p> 10183<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3> 10184 10185 10186<p> 10187Returns the metatable of the given <code>value</code> 10188or <b>nil</b> if it does not have a metatable. 10189 10190 10191 10192 10193<p> 10194<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3> 10195 10196 10197<p> 10198Returns the registry table (see <a href="#4.5">§4.5</a>). 10199 10200 10201 10202 10203<p> 10204<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3> 10205 10206 10207<p> 10208This function returns the name and the value of the upvalue 10209with index <code>up</code> of the function <code>f</code>. 10210The function returns <b>nil</b> if there is no upvalue with the given index. 10211 10212 10213<p> 10214Variable names starting with '<code>(</code>' (open parenthesis) 10215represent variables with no known names 10216(variables from chunks saved without debug information). 10217 10218 10219 10220 10221<p> 10222<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3> 10223 10224 10225<p> 10226Returns the Lua value associated to <code>u</code>. 10227If <code>u</code> is not a userdata, 10228returns <b>nil</b>. 10229 10230 10231 10232 10233<p> 10234<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3> 10235 10236 10237<p> 10238Sets the given function as a hook. 10239The string <code>mask</code> and the number <code>count</code> describe 10240when the hook will be called. 10241The string mask may have any combination of the following characters, 10242with the given meaning: 10243 10244<ul> 10245<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li> 10246<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li> 10247<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li> 10248</ul><p> 10249Moreover, 10250with a <code>count</code> different from zero, 10251the hook is called also after every <code>count</code> instructions. 10252 10253 10254<p> 10255When called without arguments, 10256<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook. 10257 10258 10259<p> 10260When the hook is called, its first parameter is a string 10261describing the event that has triggered its call: 10262<code>"call"</code> (or <code>"tail call"</code>), 10263<code>"return"</code>, 10264<code>"line"</code>, and <code>"count"</code>. 10265For line events, 10266the hook also gets the new line number as its second parameter. 10267Inside a hook, 10268you can call <code>getinfo</code> with level 2 to get more information about 10269the running function 10270(level 0 is the <code>getinfo</code> function, 10271and level 1 is the hook function). 10272 10273 10274 10275 10276<p> 10277<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3> 10278 10279 10280<p> 10281This function assigns the value <code>value</code> to the local variable 10282with index <code>local</code> of the function at level <code>level</code> of the stack. 10283The function returns <b>nil</b> if there is no local 10284variable with the given index, 10285and raises an error when called with a <code>level</code> out of range. 10286(You can call <code>getinfo</code> to check whether the level is valid.) 10287Otherwise, it returns the name of the local variable. 10288 10289 10290<p> 10291See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about 10292variable indices and names. 10293 10294 10295 10296 10297<p> 10298<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3> 10299 10300 10301<p> 10302Sets the metatable for the given <code>value</code> to the given <code>table</code> 10303(which can be <b>nil</b>). 10304Returns <code>value</code>. 10305 10306 10307 10308 10309<p> 10310<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3> 10311 10312 10313<p> 10314This function assigns the value <code>value</code> to the upvalue 10315with index <code>up</code> of the function <code>f</code>. 10316The function returns <b>nil</b> if there is no upvalue 10317with the given index. 10318Otherwise, it returns the name of the upvalue. 10319 10320 10321 10322 10323<p> 10324<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3> 10325 10326 10327<p> 10328Sets the given <code>value</code> as 10329the Lua value associated to the given <code>udata</code>. 10330<code>udata</code> must be a full userdata. 10331 10332 10333<p> 10334Returns <code>udata</code>. 10335 10336 10337 10338 10339<p> 10340<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3> 10341 10342 10343<p> 10344If <code>message</code> is present but is neither a string nor <b>nil</b>, 10345this function returns <code>message</code> without further processing. 10346Otherwise, 10347it returns a string with a traceback of the call stack. 10348The optional <code>message</code> string is appended 10349at the beginning of the traceback. 10350An optional <code>level</code> number tells at which level 10351to start the traceback 10352(default is 1, the function calling <code>traceback</code>). 10353 10354 10355 10356 10357<p> 10358<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3> 10359 10360 10361<p> 10362Returns a unique identifier (as a light userdata) 10363for the upvalue numbered <code>n</code> 10364from the given function. 10365 10366 10367<p> 10368These unique identifiers allow a program to check whether different 10369closures share upvalues. 10370Lua closures that share an upvalue 10371(that is, that access a same external local variable) 10372will return identical ids for those upvalue indices. 10373 10374 10375 10376 10377<p> 10378<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3> 10379 10380 10381<p> 10382Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code> 10383refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>. 10384 10385 10386 10387 10388 10389 10390 10391<h1>7 – <a name="7">Lua Standalone</a></h1> 10392 10393<p> 10394Although Lua has been designed as an extension language, 10395to be embedded in a host C program, 10396it is also frequently used as a standalone language. 10397An interpreter for Lua as a standalone language, 10398called simply <code>lua</code>, 10399is provided with the standard distribution. 10400The standalone interpreter includes 10401all standard libraries, including the debug library. 10402Its usage is: 10403 10404<pre> 10405 lua [options] [script [args]] 10406</pre><p> 10407The options are: 10408 10409<ul> 10410<li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li> 10411<li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em>;</li> 10412<li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li> 10413<li><b><code>-v</code>: </b> prints version information;</li> 10414<li><b><code>-E</code>: </b> ignores environment variables;</li> 10415<li><b><code>--</code>: </b> stops handling options;</li> 10416<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li> 10417</ul><p> 10418After handling its options, <code>lua</code> runs the given <em>script</em>. 10419When called without arguments, 10420<code>lua</code> behaves as <code>lua -v -i</code> 10421when the standard input (<code>stdin</code>) is a terminal, 10422and as <code>lua -</code> otherwise. 10423 10424 10425<p> 10426When called without option <code>-E</code>, 10427the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a> 10428(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined) 10429before running any argument. 10430If the variable content has the format <code>@<em>filename</em></code>, 10431then <code>lua</code> executes the file. 10432Otherwise, <code>lua</code> executes the string itself. 10433 10434 10435<p> 10436When called with option <code>-E</code>, 10437besides ignoring <code>LUA_INIT</code>, 10438Lua also ignores 10439the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>, 10440setting the values of 10441<a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a> 10442with the default paths defined in <code>luaconf.h</code>. 10443 10444 10445<p> 10446All options are handled in order, except <code>-i</code> and <code>-E</code>. 10447For instance, an invocation like 10448 10449<pre> 10450 $ lua -e'a=1' -e 'print(a)' script.lua 10451</pre><p> 10452will first set <code>a</code> to 1, then print the value of <code>a</code>, 10453and finally run the file <code>script.lua</code> with no arguments. 10454(Here <code>$</code> is the shell prompt. Your prompt may be different.) 10455 10456 10457<p> 10458Before running any code, 10459<code>lua</code> collects all command-line arguments 10460in a global table called <code>arg</code>. 10461The script name goes to index 0, 10462the first argument after the script name goes to index 1, 10463and so on. 10464Any arguments before the script name 10465(that is, the interpreter name plus its options) 10466go to negative indices. 10467For instance, in the call 10468 10469<pre> 10470 $ lua -la b.lua t1 t2 10471</pre><p> 10472the table is like this: 10473 10474<pre> 10475 arg = { [-2] = "lua", [-1] = "-la", 10476 [0] = "b.lua", 10477 [1] = "t1", [2] = "t2" } 10478</pre><p> 10479If there is no script in the call, 10480the interpreter name goes to index 0, 10481followed by the other arguments. 10482For instance, the call 10483 10484<pre> 10485 $ lua -e "print(arg[1])" 10486</pre><p> 10487will print "<code>-e</code>". 10488If there is a script, 10489the script is called with parameters 10490<code>arg[1]</code>, ···, <code>arg[#arg]</code>. 10491(Like all chunks in Lua, 10492the script is compiled as a vararg function.) 10493 10494 10495<p> 10496In interactive mode, 10497Lua repeatedly prompts and waits for a line. 10498After reading a line, 10499Lua first try to interpret the line as an expression. 10500If it succeeds, it prints its value. 10501Otherwise, it interprets the line as a statement. 10502If you write an incomplete statement, 10503the interpreter waits for its completion 10504by issuing a different prompt. 10505 10506 10507<p> 10508In case of unprotected errors in the script, 10509the interpreter reports the error to the standard error stream. 10510If the error object is not a string but 10511has a metamethod <code>__tostring</code>, 10512the interpreter calls this metamethod to produce the final message. 10513Otherwise, the interpreter converts the error object to a string 10514and adds a stack traceback to it. 10515 10516 10517<p> 10518When finishing normally, 10519the interpreter closes its main Lua state 10520(see <a href="#lua_close"><code>lua_close</code></a>). 10521The script can avoid this step by 10522calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate. 10523 10524 10525<p> 10526To allow the use of Lua as a 10527script interpreter in Unix systems, 10528the standalone interpreter skips 10529the first line of a chunk if it starts with <code>#</code>. 10530Therefore, Lua scripts can be made into executable programs 10531by using <code>chmod +x</code> and the <code>#!</code> form, 10532as in 10533 10534<pre> 10535 #!/usr/local/bin/lua 10536</pre><p> 10537(Of course, 10538the location of the Lua interpreter may be different in your machine. 10539If <code>lua</code> is in your <code>PATH</code>, 10540then 10541 10542<pre> 10543 #!/usr/bin/env lua 10544</pre><p> 10545is a more portable solution.) 10546 10547 10548 10549<h1>8 – <a name="8">Incompatibilities with the Previous Version</a></h1> 10550 10551<p> 10552Here we list the incompatibilities that you may find when moving a program 10553from Lua 5.2 to Lua 5.3. 10554You can avoid some incompatibilities by compiling Lua with 10555appropriate options (see file <code>luaconf.h</code>). 10556However, 10557all these compatibility options will be removed in the future. 10558 10559 10560<p> 10561Lua versions can always change the C API in ways that 10562do not imply source-code changes in a program, 10563such as the numeric values for constants 10564or the implementation of functions as macros. 10565Therefore, 10566you should not assume that binaries are compatible between 10567different Lua versions. 10568Always recompile clients of the Lua API when 10569using a new version. 10570 10571 10572<p> 10573Similarly, Lua versions can always change the internal representation 10574of precompiled chunks; 10575precompiled chunks are not compatible between different Lua versions. 10576 10577 10578<p> 10579The standard paths in the official distribution may 10580change between versions. 10581 10582 10583 10584<h2>8.1 – <a name="8.1">Changes in the Language</a></h2> 10585<ul> 10586 10587<li> 10588The main difference between Lua 5.2 and Lua 5.3 is the 10589introduction of an integer subtype for numbers. 10590Although this change should not affect "normal" computations, 10591some computations 10592(mainly those that involve some kind of overflow) 10593can give different results. 10594 10595 10596<p> 10597You can fix these differences by forcing a number to be a float 10598(in Lua 5.2 all numbers were float), 10599in particular writing constants with an ending <code>.0</code> 10600or using <code>x = x + 0.0</code> to convert a variable. 10601(This recommendation is only for a quick fix 10602for an occasional incompatibility; 10603it is not a general guideline for good programming. 10604For good programming, 10605use floats where you need floats 10606and integers where you need integers.) 10607</li> 10608 10609<li> 10610The conversion of a float to a string now adds a <code>.0</code> suffix 10611to the result if it looks like an integer. 10612(For instance, the float 2.0 will be printed as <code>2.0</code>, 10613not as <code>2</code>.) 10614You should always use an explicit format 10615when you need a specific format for numbers. 10616 10617 10618<p> 10619(Formally this is not an incompatibility, 10620because Lua does not specify how numbers are formatted as strings, 10621but some programs assumed a specific format.) 10622</li> 10623 10624<li> 10625The generational mode for the garbage collector was removed. 10626(It was an experimental feature in Lua 5.2.) 10627</li> 10628 10629</ul> 10630 10631 10632 10633 10634<h2>8.2 – <a name="8.2">Changes in the Libraries</a></h2> 10635<ul> 10636 10637<li> 10638The <code>bit32</code> library has been deprecated. 10639It is easy to require a compatible external library or, 10640better yet, to replace its functions with appropriate bitwise operations. 10641(Keep in mind that <code>bit32</code> operates on 32-bit integers, 10642while the bitwise operators in Lua 5.3 operate on Lua integers, 10643which by default have 64 bits.) 10644</li> 10645 10646<li> 10647The Table library now respects metamethods 10648for setting and getting elements. 10649</li> 10650 10651<li> 10652The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and 10653its <code>__ipairs</code> metamethod has been deprecated. 10654</li> 10655 10656<li> 10657Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore. 10658For compatibility, Lua will continue to accept (and ignore) this character. 10659</li> 10660 10661<li> 10662The following functions were deprecated in the mathematical library: 10663<code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>, 10664<code>frexp</code>, and <code>ldexp</code>. 10665You can replace <code>math.pow(x,y)</code> with <code>x^y</code>; 10666you can replace <code>math.atan2</code> with <code>math.atan</code>, 10667which now accepts one or two parameters; 10668you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>. 10669For the other operations, 10670you can either use an external library or 10671implement them in Lua. 10672</li> 10673 10674<li> 10675The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a> 10676changed the way it handles versioned names. 10677Now, the version should come after the module name 10678(as is usual in most other tools). 10679For compatibility, that searcher still tries the old format 10680if it cannot find an open function according to the new style. 10681(Lua 5.2 already worked that way, 10682but it did not document the change.) 10683</li> 10684 10685<li> 10686The call <code>collectgarbage("count")</code> now returns only one result. 10687(You can compute that second result from the fractional part 10688of the first result.) 10689</li> 10690 10691</ul> 10692 10693 10694 10695 10696<h2>8.3 – <a name="8.3">Changes in the API</a></h2> 10697 10698 10699<ul> 10700 10701<li> 10702Continuation functions now receive as parameters what they needed 10703to get through <code>lua_getctx</code>, 10704so <code>lua_getctx</code> has been removed. 10705Adapt your code accordingly. 10706</li> 10707 10708<li> 10709Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>. 10710Use 0 as the value of this parameter to get the old behavior. 10711</li> 10712 10713<li> 10714Functions to inject/project unsigned integers 10715(<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>, 10716<code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>) 10717were deprecated. 10718Use their signed equivalents with a type cast. 10719</li> 10720 10721<li> 10722Macros to project non-default integer types 10723(<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>) 10724were deprecated. 10725Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast 10726(or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code). 10727</li> 10728 10729</ul> 10730 10731 10732 10733 10734<h1>9 – <a name="9">The Complete Syntax of Lua</a></h1> 10735 10736<p> 10737Here is the complete syntax of Lua in extended BNF. 10738As usual in extended BNF, 10739{A} means 0 or more As, 10740and [A] means an optional A. 10741(For operator precedences, see <a href="#3.4.8">§3.4.8</a>; 10742for a description of the terminals 10743Name, Numeral, 10744and LiteralString, see <a href="#3.1">§3.1</a>.) 10745 10746 10747 10748 10749<pre> 10750 10751 chunk ::= block 10752 10753 block ::= {stat} [retstat] 10754 10755 stat ::= ‘<b>;</b>’ | 10756 varlist ‘<b>=</b>’ explist | 10757 functioncall | 10758 label | 10759 <b>break</b> | 10760 <b>goto</b> Name | 10761 <b>do</b> block <b>end</b> | 10762 <b>while</b> exp <b>do</b> block <b>end</b> | 10763 <b>repeat</b> block <b>until</b> exp | 10764 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 10765 <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b> | 10766 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> | 10767 <b>function</b> funcname funcbody | 10768 <b>local</b> <b>function</b> Name funcbody | 10769 <b>local</b> namelist [‘<b>=</b>’ explist] 10770 10771 retstat ::= <b>return</b> [explist] [‘<b>;</b>’] 10772 10773 label ::= ‘<b>::</b>’ Name ‘<b>::</b>’ 10774 10775 funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name] 10776 10777 varlist ::= var {‘<b>,</b>’ var} 10778 10779 var ::= Name | prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ | prefixexp ‘<b>.</b>’ Name 10780 10781 namelist ::= Name {‘<b>,</b>’ Name} 10782 10783 explist ::= exp {‘<b>,</b>’ exp} 10784 10785 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | ‘<b>...</b>’ | functiondef | 10786 prefixexp | tableconstructor | exp binop exp | unop exp 10787 10788 prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’ 10789 10790 functioncall ::= prefixexp args | prefixexp ‘<b>:</b>’ Name args 10791 10792 args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ | tableconstructor | LiteralString 10793 10794 functiondef ::= <b>function</b> funcbody 10795 10796 funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b> 10797 10798 parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’ 10799 10800 tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’ 10801 10802 fieldlist ::= field {fieldsep field} [fieldsep] 10803 10804 field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp 10805 10806 fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’ 10807 10808 binop ::= ‘<b>+</b>’ | ‘<b>-</b>’ | ‘<b>*</b>’ | ‘<b>/</b>’ | ‘<b>//</b>’ | ‘<b>^</b>’ | ‘<b>%</b>’ | 10809 ‘<b>&</b>’ | ‘<b>~</b>’ | ‘<b>|</b>’ | ‘<b>>></b>’ | ‘<b><<</b>’ | ‘<b>..</b>’ | 10810 ‘<b><</b>’ | ‘<b><=</b>’ | ‘<b>></b>’ | ‘<b>>=</b>’ | ‘<b>==</b>’ | ‘<b>~=</b>’ | 10811 <b>and</b> | <b>or</b> 10812 10813 unop ::= ‘<b>-</b>’ | <b>not</b> | ‘<b>#</b>’ | ‘<b>~</b>’ 10814 10815</pre> 10816 10817<p> 10818 10819 10820 10821 10822 10823 10824 10825 10826<P CLASS="footer"> 10827Last update: 10828Wed Nov 25 15:19:10 BRST 2015 10829</P> 10830<!-- 10831Last change: revised for Lua 5.3.2 10832--> 10833 10834</body></html> 10835 10836