From 0632a96667929da7328af60957bd07cfedf713e0 Mon Sep 17 00:00:00 2001 From: DongHun Kwak Date: Tue, 1 Nov 2016 14:27:09 +0900 Subject: [PATCH] Imported Upstream version 5.3.3 Change-Id: I59dadecaff3d1e7c294e9dff914881dc75da9d60 Signed-off-by: DongHun Kwak --- Makefile | 6 +- README | 2 +- doc/contents.html | 160 +-- doc/index.css | 21 + doc/lua.1 | 13 +- doc/lua.css | 134 +- doc/manual.css | 14 +- doc/manual.html | 3758 +++++++++++++++++++++++++++++------------------------ doc/readme.html | 146 +-- src/Makefile | 146 ++- src/lapi.c | 582 +++++---- src/lapi.h | 2 +- src/lauxlib.c | 370 +++--- src/lauxlib.h | 96 +- src/lbaselib.c | 226 ++-- src/lbitlib.c | 111 +- src/lcode.c | 828 ++++++++---- src/lcode.h | 15 +- src/lcorolib.c | 33 +- src/lctype.c | 5 +- src/lctype.h | 2 +- src/ldblib.c | 220 ++-- src/ldebug.c | 223 ++-- src/ldebug.h | 19 +- src/ldo.c | 387 ++++-- src/ldo.h | 28 +- src/ldump.c | 300 +++-- src/lfunc.c | 118 +- src/lfunc.h | 38 +- src/lgc.c | 936 +++++++------ src/lgc.h | 112 +- src/linit.c | 41 +- src/liolib.c | 298 +++-- src/llex.c | 295 +++-- src/llex.h | 17 +- src/llimits.h | 280 ++-- src/lmathlib.c | 336 +++-- src/lmem.c | 23 +- src/lmem.h | 30 +- src/loadlib.c | 258 ++-- src/lobject.c | 382 ++++-- src/lobject.h | 422 +++--- src/lopcodes.c | 25 +- src/lopcodes.h | 37 +- src/loslib.c | 260 ++-- src/lparser.c | 224 ++-- src/lparser.h | 68 +- src/lprefix.h | 45 + src/lstate.c | 120 +- src/lstate.h | 168 +-- src/lstring.c | 217 ++-- src/lstring.h | 21 +- src/lstrlib.c | 921 ++++++++++--- src/ltable.c | 427 +++--- src/ltable.h | 25 +- src/ltablib.c | 401 ++++-- src/ltm.c | 112 +- src/ltm.h | 29 +- src/lua.c | 518 +++++--- src/lua.h | 180 ++- src/luac.c | 49 +- src/luaconf.h | 700 ++++++---- src/lualib.h | 5 +- src/lundump.c | 427 +++--- src/lundump.h | 26 +- src/lutf8lib.c | 256 ++++ src/lvm.c | 1271 ++++++++++++------ src/lvm.h | 99 +- src/lzio.c | 20 +- src/lzio.h | 11 +- 70 files changed, 11127 insertions(+), 6968 deletions(-) create mode 100644 doc/index.css create mode 100644 src/lprefix.h create mode 100644 src/lutf8lib.c diff --git a/Makefile b/Makefile index b2a62cf..c795dd7 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,7 @@ RM= rm -f # == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE ======= # Convenience platforms targets. -PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris +PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris # What to install. TO_BIN= lua luac @@ -45,8 +45,8 @@ TO_LIB= liblua.a TO_MAN= lua.1 luac.1 # Lua version and release. -V= 5.2 -R= $V.4 +V= 5.3 +R= $V.3 # Targets start here. all: $(PLAT) diff --git a/README b/README index 710e3ee..e84d9ac 100644 --- a/README +++ b/README @@ -1,5 +1,5 @@ -This is Lua 5.2.4, released on 25 Feb 2015. +This is Lua 5.3.3, released on 30 May 2016. For installation instructions, license details, and further information about Lua, see doc/readme.html. diff --git a/doc/contents.html b/doc/contents.html index 9d5202f..ca0f568 100644 --- a/doc/contents.html +++ b/doc/contents.html @@ -1,44 +1,44 @@ -Lua 5.2 Reference Manual - contents +Lua 5.3 Reference Manual - contents + - -

- -Lua 5.2 Reference Manual +Lua +Lua 5.3 Reference Manual

The reference manual is the official definition of the Lua language. +
For a complete introduction to Lua programming, see the book Programming in Lua. -

+

+ +

-Copyright © 2011–2015 Lua.org, PUC-Rio. +Copyright © 2015–2016 Lua.org, PUC-Rio. Freely available under the terms of the Lua license.

Contents

-

Index

- - +
+ -
- + diff --git a/doc/index.css b/doc/index.css new file mode 100644 index 0000000..c961835 --- /dev/null +++ b/doc/index.css @@ -0,0 +1,21 @@ +ul { + list-style-type: none ; +} + +ul.contents { + padding: 0 ; +} + +table { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +td { + vertical-align: top ; + padding: 0 ; + text-align: left ; + line-height: 1.25 ; + width: 15% ; +} diff --git a/doc/lua.1 b/doc/lua.1 index 1dbf043..411531b 100644 --- a/doc/lua.1 +++ b/doc/lua.1 @@ -1,5 +1,4 @@ -.\" $Id: lua.man,v 1.13 2011/11/16 17:16:53 lhf Exp $ -.TH LUA 1 "$Date: 2011/11/16 17:16:53 $" +.TH LUA 1 "$Date: 2014/12/10 15:55:45 $" .SH NAME lua \- Lua interpreter .SH SYNOPSIS @@ -50,22 +49,18 @@ In interactive mode, prompts the user, reads lines from the standard input, and executes them as they are read. +If the line contains an expression or list of expressions, +then the line is evaluated and the results are printed. If a line does not contain a complete statement, then a secondary prompt is displayed and lines are read until a complete statement is formed or a syntax error is found. -If a line starts with -.BR '=' , -then -.B lua -evaluates and displays -the values of the expressions in the remainder of the line. .LP At the very start, before even handling the command line, .B lua checks the contents of the environment variables -.B LUA_INIT_5_2 +.B LUA_INIT_5_3 or .BR LUA_INIT , in that order. diff --git a/doc/lua.css b/doc/lua.css index 5dc9a8b..5bedf7e 100644 --- a/doc/lua.css +++ b/doc/lua.css @@ -3,57 +3,51 @@ html { } body { - border: solid #a0a0a0 1px ; - border-radius: 20px ; - padding: 26px ; - margin: 16px ; - color: #000000 ; background-color: #FFFFFF ; + color: #000000 ; font-family: Helvetica, Arial, sans-serif ; text-align: justify ; line-height: 1.25 ; + margin: 16px auto ; + padding: 32px ; + border: solid #a0a0a0 1px ; + border-radius: 20px ; + max-width: 70em ; + width: 90% ; } h1, h2, h3, h4 { + color: #000080 ; font-family: Verdana, Geneva, sans-serif ; font-weight: normal ; font-style: normal ; + text-align: left ; } -h2 { - padding-top: 0.4em ; - padding-bottom: 0.4em ; - padding-left: 0.8em ; - padding-right: 0.8em ; - background-color: #D0D0FF ; - border-radius: 8px ; - border: solid #a0a0a0 1px ; +h1 { + font-size: 28pt ; } -h3 { - padding-left: 0.5em ; - border-left: solid #D0D0FF 1em ; +h1 img { + vertical-align: text-bottom ; } -table h3 { - padding-left: 0px ; - border-left: none ; +h2:before { + content: "\2756" ; + padding-right: 0.5em ; } -a:link { - color: #000080 ; - background-color: inherit ; +a { text-decoration: none ; } -a:visited { - background-color: inherit ; - text-decoration: none ; +a:link { + color: #000080 ; } a:link:hover, a:visited:hover { - color: #000080 ; background-color: #D0D0FF ; + color: #000080 ; border-radius: 4px ; } @@ -61,32 +55,44 @@ a:link:active, a:visited:active { color: #FF0000 ; } -h1 a img { - vertical-align: text-bottom ; +div.menubar { + padding-bottom: 0.5em ; } -hr { - border: 0 ; - height: 1px ; - color: #a0a0a0 ; - background-color: #a0a0a0 ; - display: none ; +p.menubar { + margin-left: 2.5em ; } -table hr { - display: block ; +.menubar a:hover { + margin: -3px -3px -3px -3px ; + padding: 3px 3px 3px 3px ; + border-radius: 4px ; } :target { - background-color: #F8F8F8 ; + background-color: #F0F0F0 ; + margin: -8px ; padding: 8px ; - border: solid #a0a0a0 2px ; border-radius: 8px ; + outline: none ; +} + +hr { + display: none ; +} + +table hr { + background-color: #a0a0a0 ; + color: #a0a0a0 ; + border: 0 ; + height: 1px ; + display: block ; } .footer { color: gray ; font-size: x-small ; + text-transform: lowercase ; } input[type=text] { @@ -104,3 +110,55 @@ pre.session { padding: 1em ; border-radius: 8px ; } + +td.gutter { + width: 4% ; +} + +table.columns { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +table.columns td { + vertical-align: top ; + padding: 0 ; + padding-bottom: 1em ; + text-align: justify ; + line-height: 1.25 ; +} + +p.logos a:link:hover, p.logos a:visited:hover { + background-color: inherit ; +} + +table.book { + border: none ; + border-spacing: 0 ; + border-collapse: collapse ; +} + +table.book td { + padding: 0 ; + vertical-align: top ; +} + +table.book td.cover { + padding-right: 1em ; +} + +table.book img { + border: solid #000080 1px ; +} + +table.book span { + font-size: small ; + text-align: left ; + display: block ; + margin-top: 0.25em ; +} + +img { + background-color: white ; +} diff --git a/doc/manual.css b/doc/manual.css index ca613cd..aa0e677 100644 --- a/doc/manual.css +++ b/doc/manual.css @@ -8,20 +8,14 @@ pre, code { } span.apii { + color: gray ; float: right ; font-family: inherit ; font-style: normal ; font-size: small ; - color: gray ; } -p+h1, ul+h1 { - font-style: normal ; - padding-top: 0.4em ; - padding-bottom: 0.4em ; - padding-left: 16px ; - margin-left: -16px ; - background-color: #D0D0FF ; - border-radius: 8px ; - border: solid #000080 1px ; +h2:before { + content: "" ; + padding-right: 0em ; } diff --git a/doc/manual.html b/doc/manual.html index 0a95e9e..5fb26b2 100644 --- a/doc/manual.html +++ b/doc/manual.html @@ -1,39 +1,41 @@ - - - -Lua 5.2 Reference Manual - - + + +Lua 5.3 Reference Manual + + - + - + -
-

- -Lua 5.2 Reference Manual -

+

+Lua +Lua 5.3 Reference Manual +

+

by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes -

- -Copyright © 2011–2015 Lua.org, PUC-Rio. + +

+ +Copyright © 2015–2016 Lua.org, PUC-Rio. Freely available under the terms of the Lua license. - -


-

+ -contents +

- + @@ -41,30 +43,47 @@ Freely available under the terms of the

1 – Introduction

-Lua is an extension programming language designed to support -general procedural programming with data description -facilities. -It also offers good support for object-oriented programming, -functional programming, and data-driven programming. -Lua is intended to be used as a powerful, lightweight, -embeddable scripting language for any program that needs one. +Lua is a powerful, efficient, lightweight, embeddable scripting language. +It supports procedural programming, +object-oriented programming, functional programming, +data-driven programming, and data description. + + +

+Lua combines simple procedural syntax with powerful data description +constructs based on associative arrays and extensible semantics. +Lua is dynamically typed, +runs by interpreting bytecode with a register-based +virtual machine, +and has automatic memory management with +incremental garbage collection, +making it ideal for configuration, scripting, +and rapid prototyping. + + +

Lua is implemented as a library, written in clean C, the common subset of Standard C and C++. +The Lua distribution includes a host program called lua, +which uses the Lua library to offer a complete, +standalone Lua interpreter, +for interactive or batch use. +Lua is intended to be used both as a powerful, lightweight, +embeddable scripting language for any program that needs one, +and as a powerful but lightweight and efficient stand-alone language.

-Being an extension language, Lua has no notion of a "main" program: -it only works embedded in a host client, +As an extension language, Lua has no notion of a "main" program: +it works embedded in a host client, called the embedding program or simply the host. +(Frequently, this host is the stand-alone lua program.) The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. -The Lua distribution includes a sample host program called lua, -which uses the Lua library to offer a complete, standalone Lua interpreter, -for interactive or batch use.

@@ -113,40 +132,57 @@ There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table. -Nil is the type of the value nil, +The type nil has one single value, nil, whose main property is to be different from any other value; it usually represents the absence of a useful value. -Boolean is the type of the values false and true. +The type boolean has two values, false and true. Both nil and false make a condition false; any other value makes it true. -Number represents real (double-precision floating-point) numbers. -Operations on numbers follow the same rules of -the underlying C implementation, -which, in turn, usually follows the IEEE 754 standard. -(It is easy to build Lua interpreters that use other -internal representations for numbers, -such as single-precision floats or long integers; -see file luaconf.h.) -String represents immutable sequences of bytes. +The type number represents both +integer numbers and real (floating-point) numbers. +The type string represents immutable sequences of bytes. Lua is 8-bit clean: strings can contain any 8-bit value, including embedded zeros ('\0'). +Lua is also encoding-agnostic; +it makes no assumptions about the contents of a string. + + +

+The type number uses two internal representations, +or two subtypes, +one called integer and the other called float. +Lua has explicit rules about when each representation is used, +but it also converts between them automatically as needed (see §3.4.3). +Therefore, +the programmer may choose to mostly ignore the difference +between integers and floats +or to assume complete control over the representation of each number. +Standard Lua uses 64-bit integers and double-precision (64-bit) floats, +but you can also compile Lua so that it +uses 32-bit integers and/or single-precision (32-bit) floats. +The option with 32 bits for both integers and floats +is particularly attractive +for small machines and embedded systems. +(See macro LUA_32BITS in file luaconf.h.)

Lua can call (and manipulate) functions written in Lua and -functions written in C -(see §3.4.9). +functions written in C (see §3.4.10). +Both are represented by the type function.

The type userdata is provided to allow arbitrary C data to be stored in Lua variables. -A userdata value is a pointer to a block of raw memory. +A userdata value represents a block of raw memory. There are two kinds of userdata: -full userdata, where the block of memory is managed by Lua, -and light userdata, where the block of memory is managed by the host. +full userdata, +which is an object with a block of memory managed by Lua, +and light userdata, +which is simply a C pointer value. Userdata has no predefined operations in Lua, except assignment and identity test. By using metatables, @@ -160,17 +196,17 @@ This guarantees the integrity of data owned by the host program.

The type thread represents independent threads of execution and it is used to implement coroutines (see §2.6). -Do not confuse Lua threads with operating-system threads. +Lua threads are not related to operating-system threads. Lua supports coroutines on all systems, -even those that do not support threads. +even those that do not support threads natively.

The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, -but with any Lua value except nil and NaN -(Not a Number, a special numeric value used to represent -undefined or unrepresentable results, such as 0/0). +but with any Lua value except nil and NaN. +(Not a Number is a special value used to represent +undefined or unrepresentable numerical results, such as 0/0.) Tables can be heterogeneous; that is, they can contain values of all types (except nil). Any key with value nil is not considered part of the table. @@ -179,21 +215,21 @@ an associated value nil.

-Tables are the sole data structuring mechanism in Lua; +Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, sequences, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. There are several convenient ways to create tables in Lua -(see §3.4.8). +(see §3.4.9).

We use the term sequence to denote a table where -the set of all positive numeric keys is equal to {1..n} -for some integer n, -which is called the length of the sequence (see §3.4.6). +the set of all positive numeric keys is equal to {1..n} +for some non-negative integer n, +which is called the length of the sequence (see §3.4.7).

@@ -202,7 +238,7 @@ the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. -Thus tables can also carry methods (see §3.4.10). +Thus tables can also carry methods (see §3.4.11).

@@ -212,6 +248,18 @@ The expressions a[i] and a[j] denote the same table element if and only if i and j are raw equal (that is, equal without metamethods). +In particular, floats with integral values +are equal to their respective integers +(e.g., 1.0 == 1). +To avoid ambiguities, +any float with integral value used as a key +is converted to its respective integer. +For instance, if you write a[2.0] = true, +the actual key inserted into the table will be the +integer 2. +(On the other hand, +2 and "2" are different Lua values and therefore +denote different table entries.)

@@ -235,20 +283,21 @@ of a given value (see §6.1).

As will be discussed in §3.2 and §3.3.3, -any reference to a global name var is syntactically translated -to _ENV.var. +any reference to a free name +(that is, a name not bound to any declaration) var +is syntactically translated to _ENV.var. Moreover, every chunk is compiled in the scope of -an external local variable called _ENV (see §3.3.2), -so _ENV itself is never a global name in a chunk. +an external local variable named _ENV (see §3.3.2), +so _ENV itself is never a free name in a chunk.

Despite the existence of this external _ENV variable and -the translation of global names, +the translation of free names, _ENV is a completely regular name. In particular, you can define new variables and parameters with that name. -Each reference to a global name uses the _ENV that is +Each reference to a free name uses the _ENV that is visible at that point in the program, following the usual visibility rules of Lua (see §3.5). @@ -260,34 +309,25 @@ Any table used as the value of _ENV is called an environment Lua keeps a distinguished environment called the global environment. This value is kept at a special index in the C registry (see §4.5). -In Lua, the variable _G is initialized with this same value. +In Lua, the global variable _G is initialized with this same value. +(_G is never used internally.)

-When Lua compiles a chunk, -it initializes the value of its _ENV upvalue -with the global environment (see load). +When Lua loads a chunk, +the default value for its _ENV upvalue +is the global environment (see load). Therefore, by default, -global variables in Lua code refer to entries in the global environment. +free names in Lua code refer to entries in the global environment +(and, therefore, they are also called global variables). Moreover, all standard libraries are loaded in the global environment -and several functions there operate on that environment. +and some functions there operate on that environment. You can use load (or loadfile) to load a chunk with a different environment. (In C, you have to load the chunk and then change the value of its first upvalue.) -

-If you change the global environment in the registry -(through C code or the debug library), -all chunks loaded after the change will get the new environment. -Previously loaded chunks are not affected, however, -as each has its own reference to the environment in its _ENV variable. -Moreover, the variable _G -(which is stored in the original global environment) -is never updated by Lua. - - @@ -296,7 +336,9 @@ is never updated by Lua.

Because Lua is an embedded extension language, all Lua actions start from C code in the host program -calling a function from the Lua library (see lua_pcall). +calling a function from the Lua library. +(When you use Lua standalone, +the lua application is the host program.) Whenever an error occurs during the compilation or execution of a Lua chunk, control returns to the host, @@ -316,24 +358,26 @@ to call a given function in protected mode. Whenever there is an error, an error object (also called an error message) is propagated with information about the error. -Lua itself only generates errors where the error object is a string, +Lua itself only generates errors whose error object is a string, but programs may generate errors with -any value for the error object. +any value as the error object. +It is up to the Lua program or its host to handle such error objects.

When you use xpcall or lua_pcall, you may give a message handler to be called in case of errors. -This function is called with the original error message -and returns a new error message. +This function is called with the original error object +and returns a new error object. It is called before the error unwinds the stack, so that it can gather more information about the error, for instance by inspecting the stack and creating a stack traceback. This message handler is still protected by the protected call; so, an error inside the message handler will call the message handler again. -If this loop goes on, Lua breaks it and returns an appropriate message. +If this loop goes on for too long, +Lua breaks it and returns an appropriate message. @@ -355,23 +399,30 @@ Lua calls this function to perform the addition.

-The keys in a metatable are derived from the event names; +The key for each event in a metatable is a string +with the event name prefixed by two underscores; the corresponding values are called metamethods. -In the previous example, the event is "add" +In the previous example, the key is "__add" and the metamethod is the function that performs the addition.

You can query the metatable of any value using the getmetatable function. +Lua queries metamethods in metatables using a raw access (see rawget). +So, to retrieve the metamethod for event ev in object o, +Lua does the equivalent to the following code: +

+     rawget(getmetatable(o) or {}, "__ev")
+

You can replace the metatable of tables using the setmetatable function. -You cannot change the metatable of other types from Lua -(except by using the debug library); -you must use the C API for that. +You cannot change the metatable of other types from Lua code +(except by using the debug library (§6.10)); +you should use the C API for that.

@@ -385,382 +436,249 @@ but the string library sets a metatable for the string type (see

-A metatable controls how an object behaves in arithmetic operations, -order comparisons, concatenation, length operation, and indexing. +A metatable controls how an object behaves in +arithmetic operations, bitwise operations, +order comparisons, concatenation, length operation, calls, and indexing. A metatable also can define a function to be called -when a userdata or a table is garbage collected. -When Lua performs one of these operations over a value, -it checks whether this value has a metatable with the corresponding event. -If so, the value associated with that key (the metamethod) -controls how Lua will perform the operation. +when a userdata or a table is garbage collected (§2.5).

-Metatables control the operations listed next. -Each operation is identified by its corresponding name. -The key for each operation is a string with its name prefixed by -two underscores, '__'; -for instance, the key for operation "add" is the -string "__add". - - -

-The semantics of these operations is better explained by a Lua function -describing how the interpreter executes the operation. -The code shown here in Lua is only illustrative; -the real behavior is hard coded in the interpreter -and it is much more efficient than this simulation. -All functions used in these descriptions -(rawget, tonumber, etc.) -are described in §6.1. -In particular, to retrieve the metamethod of a given object, -we use the expression - -

-     metatable(obj)[event]
-

-This should be read as - -

-     rawget(getmetatable(obj) or {}, event)
-

-This means that the access to a metamethod does not invoke other metamethods, -and access to objects with no metatables does not fail -(it simply results in nil). +For the unary operators (negation, length, and bitwise NOT), +the metamethod is computed and called with a dummy second operand, +equal to the first one. +This extra operand is only to simplify Lua's internals +(by making these operators behave like a binary operation) +and may be removed in future versions. +(For most uses this extra operand is irrelevant.)

-For the unary - and # operators, -the metamethod is called with a dummy second argument. -This extra argument is only to simplify Lua's internals; -it may be removed in future versions and therefore it is not present -in the following code. -(For most uses this extra argument is irrelevant.) +A detailed list of events controlled by metatables is given next. +Each operation is identified by its corresponding key.

    -
  • "add": -the + operation. - - - -

    -The function getbinhandler below defines how Lua chooses a handler -for a binary operation. -First, Lua tries the first operand. -If its type does not define a handler for the operation, -then Lua tries the second operand. - -

    -     function getbinhandler (op1, op2, event)
    -       return metatable(op1)[event] or metatable(op2)[event]
    -     end
    -

    -By using this function, -the behavior of the op1 + op2 is - -

    -     function add_event (op1, op2)
    -       local o1, o2 = tonumber(op1), tonumber(op2)
    -       if o1 and o2 then  -- both operands are numeric?
    -         return o1 + o2   -- '+' here is the primitive 'add'
    -       else  -- at least one of the operands is not numeric
    -         local h = getbinhandler(op1, op2, "__add")
    -         if h then
    -           -- call the handler with both operands
    -           return (h(op1, op2))
    -         else  -- no handler available: default behavior
    -           error(···)
    -         end
    -       end
    -     end
    -

    +

  • __add: +the addition (+) operation. +If any operand for an addition is not a number +(nor a string coercible to a number), +Lua will try to call a metamethod. +First, Lua will check the first operand (even if it is valid). +If that operand does not define a metamethod for __add, +then Lua will check the second operand. +If Lua can find a metamethod, +it calls the metamethod with the two operands as arguments, +and the result of the call +(adjusted to one value) +is the result of the operation. +Otherwise, +it raises an error.
  • -
  • "sub": -the - operation. - -Behavior similar to the "add" operation. +
  • __sub: +the subtraction (-) operation. +Behavior similar to the addition operation.
  • -
  • "mul": -the * operation. - -Behavior similar to the "add" operation. +
  • __mul: +the multiplication (*) operation. +Behavior similar to the addition operation.
  • -
  • "div": -the / operation. - -Behavior similar to the "add" operation. +
  • __div: +the division (/) operation. +Behavior similar to the addition operation.
  • -
  • "mod": -the % operation. - -Behavior similar to the "add" operation, -with the operation -o1 - floor(o1/o2)*o2 as the primitive operation. +
  • __mod: +the modulo (%) operation. +Behavior similar to the addition operation.
  • -
  • "pow": -the ^ (exponentiation) operation. - -Behavior similar to the "add" operation, -with the function pow (from the C math library) -as the primitive operation. +
  • __pow: +the exponentiation (^) operation. +Behavior similar to the addition operation.
  • -
  • "unm": -the unary - operation. - - -
    -     function unm_event (op)
    -       local o = tonumber(op)
    -       if o then  -- operand is numeric?
    -         return -o  -- '-' here is the primitive 'unm'
    -       else  -- the operand is not numeric.
    -         -- Try to get a handler from the operand
    -         local h = metatable(op).__unm
    -         if h then
    -           -- call the handler with the operand
    -           return (h(op))
    -         else  -- no handler available: default behavior
    -           error(···)
    -         end
    -       end
    -     end
    -

    +

  • __unm: +the negation (unary -) operation. +Behavior similar to the addition operation.
  • -
  • "concat": -the .. (concatenation) operation. - - -
    -     function concat_event (op1, op2)
    -       if (type(op1) == "string" or type(op1) == "number") and
    -          (type(op2) == "string" or type(op2) == "number") then
    -         return op1 .. op2  -- primitive string concatenation
    -       else
    -         local h = getbinhandler(op1, op2, "__concat")
    -         if h then
    -           return (h(op1, op2))
    -         else
    -           error(···)
    -         end
    -       end
    -     end
    -

    +

  • __idiv: +the floor division (//) operation. +Behavior similar to the addition operation.
  • -
  • "len": -the # operation. - - -
    -     function len_event (op)
    -       if type(op) == "string" then
    -         return strlen(op)      -- primitive string length
    -       else
    -         local h = metatable(op).__len
    -         if h then
    -           return (h(op))       -- call handler with the operand
    -         elseif type(op) == "table" then
    -           return #op              -- primitive table length
    -         else  -- no handler available: error
    -           error(···)
    -         end
    -       end
    -     end
    -

    -See §3.4.6 for a description of the length of a table. +

  • __band: +the bitwise AND (&) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod +if any operand is neither an integer +nor a value coercible to an integer (see §3.4.3).
  • -
  • "eq": -the == operation. - -The function getequalhandler defines how Lua chooses a metamethod -for equality. -A metamethod is selected only when both values -being compared have the same type -and the same metamethod for the selected operation, -and the values are either tables or full userdata. - -
    -     function getequalhandler (op1, op2)
    -       if type(op1) ~= type(op2) or
    -          (type(op1) ~= "table" and type(op1) ~= "userdata") then
    -         return nil     -- different values
    -       end
    -       local mm1 = metatable(op1).__eq
    -       local mm2 = metatable(op2).__eq
    -       if mm1 == mm2 then return mm1 else return nil end
    -     end
    -

    -The "eq" event is defined as follows: +

  • __bor: +the bitwise OR (|) operation. +Behavior similar to the bitwise AND operation. +
  • -
    -     function eq_event (op1, op2)
    -       if op1 == op2 then   -- primitive equal?
    -         return true   -- values are equal
    -       end
    -       -- try metamethod
    -       local h = getequalhandler(op1, op2)
    -       if h then
    -         return not not h(op1, op2)
    -       else
    -         return false
    -       end
    -     end
    -

    -Note that the result is always a boolean. +

  • __bxor: +the bitwise exclusive OR (binary ~) operation. +Behavior similar to the bitwise AND operation.
  • -
  • "lt": -the < operation. +
  • __bnot: +the bitwise NOT (unary ~) operation. +Behavior similar to the bitwise AND operation. +
  • +
  • __shl: +the bitwise left shift (<<) operation. +Behavior similar to the bitwise AND operation. +
  • -
    -     function lt_event (op1, op2)
    -       if type(op1) == "number" and type(op2) == "number" then
    -         return op1 < op2   -- numeric comparison
    -       elseif type(op1) == "string" and type(op2) == "string" then
    -         return op1 < op2   -- lexicographic comparison
    -       else
    -         local h = getbinhandler(op1, op2, "__lt")
    -         if h then
    -           return not not h(op1, op2)
    -         else
    -           error(···)
    -         end
    -       end
    -     end
    -

    -Note that the result is always a boolean. +

  • __shr: +the bitwise right shift (>>) operation. +Behavior similar to the bitwise AND operation.
  • -
  • "le": -the <= operation. +
  • __concat: +the concatenation (..) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod +if any operand is neither a string nor a number +(which is always coercible to a string). +
  • +
  • __len: +the length (#) operation. +If the object is not a string, +Lua will try its metamethod. +If there is a metamethod, +Lua calls it with the object as argument, +and the result of the call +(always adjusted to one value) +is the result of the operation. +If there is no metamethod but the object is a table, +then Lua uses the table length operation (see §3.4.7). +Otherwise, Lua raises an error. +
  • -
    -     function le_event (op1, op2)
    -       if type(op1) == "number" and type(op2) == "number" then
    -         return op1 <= op2   -- numeric comparison
    -       elseif type(op1) == "string" and type(op2) == "string" then
    -         return op1 <= op2   -- lexicographic comparison
    -       else
    -         local h = getbinhandler(op1, op2, "__le")
    -         if h then
    -           return not not h(op1, op2)
    -         else
    -           h = getbinhandler(op1, op2, "__lt")
    -           if h then
    -             return not h(op2, op1)
    -           else
    -             error(···)
    -           end
    -         end
    -       end
    -     end
    -

    -Note that, in the absence of a "le" metamethod, -Lua tries the "lt", assuming that a <= b is -equivalent to not (b < a). +

  • __eq: +the equal (==) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod only when the values +being compared are either both tables or both full userdata +and they are not primitively equal. +The result of the call is always converted to a boolean. +
  • +
  • __lt: +the less than (<) operation. +Behavior similar to the addition operation, +except that Lua will try a metamethod only when the values +being compared are neither both numbers nor both strings. +The result of the call is always converted to a boolean. +
  • -

    +

  • __le: +the less equal (<=) operation. +Unlike other operations, +the less-equal operation can use two different events. +First, Lua looks for the __le metamethod in both operands, +like in the less than operation. +If it cannot find such a metamethod, +then it will try the __lt metamethod, +assuming that a <= b is equivalent to not (b < a). As with the other comparison operators, the result is always a boolean. +(This use of the __lt event can be removed in future versions; +it is also slower than a real __le metamethod.)
  • -
  • "index": +
  • __index: The indexing access table[key]. -Note that the metamethod is tried only +This event happens when table is not a table or when key is not present in table. -(When table is not a table, -no key is ever present, -so the metamethod is always tried.) +The metamethod is looked up in table. -
    -     function gettable_event (table, key)
    -       local h
    -       if type(table) == "table" then
    -         local v = rawget(table, key)
    -         -- if key is present, return raw value
    -         if v ~= nil then return v end
    -         h = metatable(table).__index
    -         if h == nil then return nil end
    -       else
    -         h = metatable(table).__index
    -         if h == nil then
    -           error(···)
    -         end
    -       end
    -       if type(h) == "function" then
    -         return (h(table, key))     -- call the handler
    -       else return h[key]           -- or repeat operation on it
    -       end
    -     end
    -

    +

    +Despite the name, +the metamethod for this event can be either a function or a table. +If it is a function, +it is called with table and key as arguments, +and the result of the call +(adjusted to one value) +is the result of the operation. +If it is a table, +the final result is the result of indexing this table with key. +(This indexing is regular, not raw, +and therefore can trigger another metamethod.)

  • -
  • "newindex": +
  • __newindex: The indexing assignment table[key] = value. -Note that the metamethod is tried only +Like the index event, +this event happens when table is not a table or when key is not present in table. +The metamethod is looked up in table. -
    -     function settable_event (table, key, value)
    -       local h
    -       if type(table) == "table" then
    -         local v = rawget(table, key)
    -         -- if key is present, do raw assignment
    -         if v ~= nil then rawset(table, key, value); return end
    -         h = metatable(table).__newindex
    -         if h == nil then rawset(table, key, value); return end
    -       else
    -         h = metatable(table).__newindex
    -         if h == nil then
    -           error(···)
    -         end
    -       end
    -       if type(h) == "function" then
    -         h(table, key,value)           -- call the handler
    -       else h[key] = value             -- or repeat operation on it
    -       end
    -     end
    -

    -

  • +

    +Like with indexing, +the metamethod for this event can be either a function or a table. +If it is a function, +it is called with table, key, and value as arguments. +If it is a table, +Lua does an indexing assignment to this table with the same key and value. +(This assignment is regular, not raw, +and therefore can trigger another metamethod.) -

  • "call": -called when Lua calls a value. +

    +Whenever there is a __newindex metamethod, +Lua does not perform the primitive assignment. +(If necessary, +the metamethod itself can call rawset +to do the assignment.) +

  • -
    -     function function_event (func, ...)
    -       if type(func) == "function" then
    -         return func(...)   -- primitive call
    -       else
    -         local h = metatable(func).__call
    -         if h then
    -           return h(func, ...)
    -         else
    -           error(···)
    -         end
    -       end
    -     end
    -

    +

  • __call: +The call operation func(args). +This event happens when Lua tries to call a non-function value +(that is, func is not a function). +The metamethod is looked up in func. +If present, +the metamethod is called with func as its first argument, +followed by the arguments of the original call (args). +All results of the call +are the result of the operation. +(This is the only metamethod that allows multiple results.)
+

+It is a good practice to add all needed metamethods to a table +before setting it as a metatable of some object. +In particular, the __gc metamethod works only when this order +is followed (see §2.5.1). + + +

+Because metatables are regular tables, +they can contain arbitrary fields, +not only the event names defined above. +Some functions in the standard library +(e.g., tostring) +use other fields in metatables for their own purposes. + + @@ -769,8 +687,8 @@ called when Lua calls a value.

Lua performs automatic memory management. This means that -you have to worry neither about allocating memory for new objects -nor about freeing it when the objects are no longer needed. +you do not have to worry about allocating memory for new objects +or freeing it when the objects are no longer needed. Lua manages memory automatically by running a garbage collector to collect all dead objects (that is, objects that are no longer accessible from Lua). @@ -803,7 +721,8 @@ controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. -Values smaller than 100 make the collector too slow and +You should not use values smaller than 100, +because they make the collector too slow and can result in the collector never finishing a cycle. The default is 200, which means that the collector runs at "twice" @@ -828,21 +747,6 @@ You can also use these functions to control the collector directly (e.g., stop and restart it). -

-As an experimental feature in Lua 5.2, -you can change the collector's operation mode -from incremental to generational. -A generational collector assumes that most objects die young, -and therefore it traverses only young (recently created) objects. -This behavior can reduce the time used by the collector, -but also increases memory usage (as old dead objects may accumulate). -To mitigate this second problem, -from time to time the generational collector performs a full collection. -Remember that this is an experimental feature; -you are welcome to try it, -but check your gains. - -

2.5.1 – Garbage-Collection Metamethods

@@ -866,8 +770,6 @@ and the metatable has a field indexed by the string "__gc". Note that if you set a metatable without a __gc field and later create that field in the metatable, the object will not be marked for finalization. -However, after an object is marked, -you can freely change the __gc field of its metatable.

@@ -875,22 +777,19 @@ When a marked object becomes garbage, it is not collected immediately by the garbage collector. Instead, Lua puts it in a list. After the collection, -Lua does the equivalent of the following function -for each object in that list: +Lua goes through that list. +For each object in the list, +it checks the object's __gc metamethod: +If it is a function, +Lua calls it with the object as its single argument; +if the metamethod is not a function, +Lua simply ignores it. -

-     function gc_event (obj)
-       local h = metatable(obj).__gc
-       if type(h) == "function" then
-         h(obj)
-       end
-     end
-

At the end of each garbage-collection cycle, the finalizers for objects are called in -the reverse order that they were marked for collection, +the reverse order that the objects were marked for finalization, among those collected in that cycle; that is, the first finalizer to be called is the one associated with the object marked last in the program. @@ -900,24 +799,27 @@ the execution of the regular code.

Because the object being collected must still be used by the finalizer, -it (and other objects accessible only through it) +that object (and other objects accessible only through it) must be resurrected by Lua. Usually, this resurrection is transient, and the object memory is freed in the next garbage-collection cycle. However, if the finalizer stores the object in some global place (e.g., a global variable), -then there is a permanent resurrection. +then the resurrection is permanent. +Moreover, if the finalizer marks a finalizing object for finalization again, +its finalizer will be called again in the next cycle where the +object is unreachable. In any case, -the object memory is freed only when it becomes completely inaccessible; -its finalizer will never be called twice. +the object memory is freed only in a GC cycle where +the object is unreachable and not marked for finalization.

When you close a state (see lua_close), Lua calls the finalizers of all objects marked for finalization, following the reverse order that they were marked. -If any finalizer marks new objects for collection during that phase, -these new objects will not be finalized. +If any finalizer marks objects for collection during that phase, +these marks have no effect. @@ -936,8 +838,8 @@ then the garbage collector will collect that object.

A weak table can have weak keys, weak values, or both. -A table with weak keys allows the collection of its keys, -but prevents the collection of its values. +A table with weak values allows the collection of its values, +but prevents the collection of its keys. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, @@ -974,7 +876,7 @@ are removed from weak tables. Values, such as numbers and light C functions, are not subject to garbage collection, and therefore are not removed from weak tables -(unless its associated value is collected). +(unless their associated values are collected). Although strings are subject to garbage collection, they do not have an explicit construction, and therefore are not removed from weak tables. @@ -1027,10 +929,10 @@ You execute a coroutine by calling corouti When you first call coroutine.resume, passing as its first argument a thread returned by coroutine.create, -the coroutine starts its execution, -at the first line of its main function. -Extra arguments passed to coroutine.resume are passed on -to the coroutine main function. +the coroutine starts its execution by +calling its main function. +Extra arguments passed to coroutine.resume are passed +as arguments to that function. After the coroutine starts running, it runs until it terminates or yields. @@ -1040,10 +942,11 @@ A coroutine can terminate its execution in two ways: normally, when its main function returns (explicitly or implicitly, after the last instruction); and abnormally, if there is an unprotected error. -In the first case, coroutine.resume returns true, +In case of normal termination, +coroutine.resume returns true, plus any values returned by the coroutine main function. In case of errors, coroutine.resume returns false -plus an error message. +plus an error object.

@@ -1159,7 +1062,8 @@ except as delimiters between names and keywords. (also called identifiers) in Lua can be any string of letters, digits, and underscores, -not beginning with a digit. +not beginning with a digit and +not being a reserved word. Identifiers are used to name variables, table fields, and labels. @@ -1179,9 +1083,10 @@ and cannot be used as names: Lua is a case-sensitive language: and is a reserved word, but And and AND are two different, valid names. -As a convention, names starting with an underscore followed by -uppercase letters (such as _VERSION) -are reserved for variables used by Lua. +As a convention, +programs should avoid creating +names that start with an underscore followed by +one or more uppercase letters (such as _VERSION).

@@ -1189,6 +1094,7 @@ The following strings denote other tokens:

      +     -     *     /     %     ^     #
+     &     ~     |     <<    >>    //
      ==    ~=    <=    >=    <     >     =
      (     )     {     }     [     ]     ::
      ;     :     ,     .     ..    ...
@@ -1219,15 +1125,26 @@ into the string contents.
 
 
 

-A byte in a literal string can also be specified by its numerical value. -This can be done with the escape sequence \xXX, +Strings in Lua can contain any 8-bit value, including embedded zeros, +which can be specified as '\0'. +More generally, +we can specify any byte in a literal string by its numeric value. +This can be done +with the escape sequence \xXX, where XX is a sequence of exactly two hexadecimal digits, or with the escape sequence \ddd, where ddd is a sequence of up to three decimal digits. -(Note that if a decimal escape is to be followed by a digit, +(Note that if a decimal escape sequence is to be followed by a digit, it must be expressed using exactly three digits.) -Strings in Lua can contain any 8-bit value, including embedded zeros, -which can be specified as '\0'. + + +

+The UTF-8 encoding of a Unicode character +can be inserted in a literal string with +the escape sequence \u{XXX} +(note the mandatory enclosing brackets), +where XXX is a sequence of one or more hexadecimal digits +representing the character code point.

@@ -1236,14 +1153,15 @@ enclosed by long brackets. We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. -So, an opening long bracket of level 0 is written as [[, -an opening long bracket of level 1 is written as [=[, +So, an opening long bracket of level 0 is written as [[, +an opening long bracket of level 1 is written as [=[, and so on. A closing long bracket is defined similarly; -for instance, a closing long bracket of level 4 is written as ]====]. +for instance, +a closing long bracket of level 4 is written as ]====]. A long literal starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. -It can contain any text except a closing bracket of the proper level. +It can contain any text except a closing bracket of the same level. Literals in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. @@ -1261,7 +1179,7 @@ and the system file functions may have problems with some control characters. So, it is safer to represent non-text data as a quoted literal with -explicit escape sequences for non-text characters. +explicit escape sequences for the non-text characters.

@@ -1285,7 +1203,8 @@ the five literal strings below denote the same string:

-A numerical constant can be written with an optional fractional part +A numeric constant (or numeral) +can be written with an optional fractional part and an optional decimal exponent, marked by a letter 'e' or 'E'. Lua also accepts hexadecimal constants, @@ -1293,11 +1212,21 @@ which start with 0x or 0X. Hexadecimal constants also accept an optional fractional part plus an optional binary exponent, marked by a letter 'p' or 'P'. -Examples of valid numerical constants are +A numeric constant with a radix point or an exponent +denotes a float; +otherwise, +if its value fits in an integer, +it denotes an integer. +Examples of valid integer constants are + +

+     3   345   0xff   0xBEBADA
+

+Examples of valid float constants are

-     3     3.0     3.1416     314.16e-2     0.31416E1
-     0xff  0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
+     3.0     3.1416     314.16e-2     0.31416E1     34e1
+     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
 

@@ -1466,7 +1395,7 @@ a chunk is simply a block:

Lua handles a chunk as the body of an anonymous function with a variable number of arguments -(see §3.4.10). +(see §3.4.11). As such, chunks can define local variables, receive arguments, and return values. Moreover, such anonymous function is compiled as in the @@ -1478,17 +1407,17 @@ even if it does not use that variable.

A chunk can be stored in a file or in a string inside the host program. To execute a chunk, -Lua first precompiles the chunk into instructions for a virtual machine, -and then it executes the compiled code +Lua first loads it, +precompiling the chunk's code into instructions for a virtual machine, +and then Lua executes the compiled code with an interpreter for the virtual machine.

Chunks can also be precompiled into binary form; -see program luac for details. +see program luac and function string.dump for details. Programs in source and compiled forms are interchangeable; -Lua automatically detects the file type and acts accordingly. - +Lua automatically detects the file type and acts accordingly (see load). @@ -1527,7 +1456,7 @@ before the adjustment

The assignment statement first evaluates all its expressions -and only then are the assignments performed. +and only then the assignments are performed. Thus the code

@@ -1563,7 +1492,7 @@ We use it here only for explanatory purposes.)
 
 
 

-An assignment to a global variable x = val +An assignment to a global name x = val is equivalent to the assignment _ENV.x = val (see §2.2). @@ -1644,7 +1573,8 @@ A break ends the innermost enclosing loop.

The return statement is used to return values -from a function or a chunk (which is a function in disguise). +from a function or a chunk +(which is an anonymous function). Functions can return more than one value, so the syntax for the return statement is @@ -1670,11 +1600,11 @@ because now return is the last statement in its (inner) block.

The for statement has two forms: -one numeric and one generic. +one numerical and one generic.

-The numeric for loop repeats a block of code while a +The numerical for loop repeats a block of code while a control variable runs through an arithmetic progression. It has the following syntax: @@ -1695,13 +1625,19 @@ is equivalent to the code: do local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3) if not (var and limit and step) then error() end - while (step > 0 and var <= limit) or (step <= 0 and var >= limit) do + var = var - step + while true do + var = var + step + if (step >= 0 and var > limit) or (step < 0 and var < limit) then + break + end local v = var block - var = var + step end end -

+ + +

Note the following:

    @@ -1723,14 +1659,13 @@ then a step of 1 is used.
  • -You can use break to exit a for loop. +You can use break and goto to exit a for loop.
  • -The loop variable v is local to the loop; -you cannot use its value after the for ends or is broken. -If you need this value, -assign it to another variable before breaking or exiting the loop. +The loop variable v is local to the loop body. +If you need its value after the loop, +assign it to another variable before exiting the loop.
@@ -1804,7 +1739,7 @@ function calls can be executed as statements: stat ::= functioncall

In this case, all returned values are thrown away. -Function calls are explained in §3.4.9. +Function calls are explained in §3.4.10. @@ -1844,8 +1779,8 @@ The basic expressions in Lua are the following:

 	exp ::= prefixexp
 	exp ::= nil | false | true
-	exp ::= Number
-	exp ::= String
+	exp ::= Numeral
+	exp ::= LiteralString
 	exp ::= functiondef
 	exp ::= tableconstructor
 	exp ::= ‘...’
@@ -1855,24 +1790,26 @@ The basic expressions in Lua are the following:
 

-Numbers and literal strings are explained in §3.1; +Numerals and literal strings are explained in §3.1; variables are explained in §3.2; -function definitions are explained in §3.4.10; -function calls are explained in §3.4.9; -table constructors are explained in §3.4.8. +function definitions are explained in §3.4.11; +function calls are explained in §3.4.10; +table constructors are explained in §3.4.9. Vararg expressions, denoted by three dots ('...'), can only be used when directly inside a vararg function; -they are explained in §3.4.10. +they are explained in §3.4.11.

Binary operators comprise arithmetic operators (see §3.4.1), -relational operators (see §3.4.3), logical operators (see §3.4.4), -and the concatenation operator (see §3.4.5). +bitwise operators (see §3.4.2), +relational operators (see §3.4.4), logical operators (see §3.4.5), +and the concatenation operator (see §3.4.6). Unary operators comprise the unary minus (see §3.4.1), -the unary not (see §3.4.4), -and the unary length operator (see §3.4.6). +the unary bitwise NOT (see §3.4.2), +the unary logical not (see §3.4.5), +and the unary length operator (see §3.4.7).

@@ -1923,38 +1860,152 @@ or nil if f does not return any values.)

3.4.1 – Arithmetic Operators

-Lua supports the usual arithmetic operators: -the binary + (addition), -- (subtraction), * (multiplication), -/ (division), % (modulo), and ^ (exponentiation); -and unary - (mathematical negation). -If the operands are numbers, or strings that can be converted to -numbers (see §3.4.2), -then all operations have the usual meaning. -Exponentiation works for any exponent. -For instance, x^(-0.5) computes the inverse of the square root of x. -Modulo is defined as +Lua supports the following arithmetic operators: -

-     a % b == a - math.floor(a/b)*b
-

-That is, it is the remainder of a division that rounds -the quotient towards minus infinity. +

    +
  • +: addition
  • +
  • -: subtraction
  • +
  • *: multiplication
  • +
  • /: float division
  • +
  • //: floor division
  • +
  • %: modulo
  • +
  • ^: exponentiation
  • +
  • -: unary minus
  • +
+ +

+With the exception of exponentiation and float division, +the arithmetic operators work as follows: +If both operands are integers, +the operation is performed over integers and the result is an integer. +Otherwise, if both operands are numbers +or strings that can be converted to +numbers (see §3.4.3), +then they are converted to floats, +the operation is performed following the usual rules +for floating-point arithmetic +(usually the IEEE 754 standard), +and the result is a float. + + +

+Exponentiation and float division (/) +always convert their operands to floats +and the result is always a float. +Exponentiation uses the ISO C function pow, +so that it works for non-integer exponents too. +

+Floor division (//) is a division +that rounds the quotient towards minus infinity, +that is, the floor of the division of its operands. +

+Modulo is defined as the remainder of a division +that rounds the quotient towards minus infinity (floor division). -

3.4.2 – Coercion

-Lua provides automatic conversion between -string and number values at run time. -Any arithmetic operation applied to a string tries to convert -this string to a number, following the rules of the Lua lexer. -(The string may have leading and trailing spaces and a sign.) -Conversely, whenever a number is used where a string is expected, -the number is converted to a string, in a reasonable format. +In case of overflows in integer arithmetic, +all operations wrap around, +according to the usual rules of two-complement arithmetic. +(In other words, +they return the unique representable integer +that is equal modulo 264 to the mathematical result.) + + + +

3.4.2 – Bitwise Operators

+Lua supports the following bitwise operators: + +

    +
  • &: bitwise AND
  • +
  • |: bitwise OR
  • +
  • ~: bitwise exclusive OR
  • +
  • >>: right shift
  • +
  • <<: left shift
  • +
  • ~: unary bitwise NOT
  • +
+ +

+All bitwise operations convert its operands to integers +(see §3.4.3), +operate on all bits of those integers, +and result in an integer. + + +

+Both right and left shifts fill the vacant bits with zeros. +Negative displacements shift to the other direction; +displacements with absolute values equal to or higher than +the number of bits in an integer +result in zero (as all bits are shifted out). + + + + + +

3.4.3 – Coercions and Conversions

+Lua provides some automatic conversions between some +types and representations at run time. +Bitwise operators always convert float operands to integers. +Exponentiation and float division +always convert integer operands to floats. +All other arithmetic operations applied to mixed numbers +(integers and floats) convert the integer operand to a float; +this is called the usual rule. +The C API also converts both integers to floats and +floats to integers, as needed. +Moreover, string concatenation accepts numbers as arguments, +besides strings. + + +

+Lua also converts strings to numbers, +whenever a number is expected. + + +

+In a conversion from integer to float, +if the integer value has an exact representation as a float, +that is the result. +Otherwise, +the conversion gets the nearest higher or +the nearest lower representable value. +This kind of conversion never fails. + + +

+The conversion from float to integer +checks whether the float has an exact representation as an integer +(that is, the float has an integral value and +it is in the range of integer representation). +If it does, that representation is the result. +Otherwise, the conversion fails. + + +

+The conversion from strings to numbers goes as follows: +First, the string is converted to an integer or a float, +following its syntax and the rules of the Lua lexer. +(The string may have also leading and trailing spaces and a sign.) +Then, the resulting number (float or integer) +is converted to the type (float or integer) required by the context +(e.g., the operation that forced the conversion). + + +

+All conversions from strings to numbers +accept both a dot and the current locale mark +as the radix character. +(The Lua lexer, however, accepts only a dot.) + + +

+The conversion from numbers to strings uses a +non-specified human-readable format. For complete control over how numbers are converted to strings, use the format function from the string library (see string.format). @@ -1963,12 +2014,17 @@ use the format function from the string library -

3.4.3 – Relational Operators

-The relational operators in Lua are +

3.4.4 – Relational Operators

+Lua supports the following relational operators: -

-     ==    ~=    <     >     <=    >=
-

+

    +
  • ==: equality
  • +
  • ~=: inequality
  • +
  • <: less than
  • +
  • >: greater than
  • +
  • <=: less or equal
  • +
  • >=: greater or equal
  • +

These operators always result in false or true. @@ -1976,7 +2032,11 @@ These operators always result in false or true. Equality (==) first compares the type of its operands. If the types are different, then the result is false. Otherwise, the values of the operands are compared. -Numbers and strings are compared in the usual way. +Strings are compared in the obvious way. +Numbers are equal if they denote the same mathematical value. + + +

Tables, userdata, and threads are compared by reference: two objects are considered equal only if they are the same object. @@ -1994,8 +2054,8 @@ by using the "eq" metamethod (see §2.4).

-The conversion rules of §3.4.2 -do not apply to equality comparisons. +Equality comparisons do not convert strings to numbers +or vice versa. Thus, "0"==0 evaluates to false, and t[0] and t["0"] denote different entries in a table. @@ -2007,7 +2067,9 @@ The operator ~= is exactly the negation of equality (== The order operators work as follows. -If both arguments are numbers, then they are compared as such. +If both arguments are numbers, +then they are compared according to their mathematical values +(regardless of their subtypes). Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Lua tries to call the "lt" or the "le" @@ -2016,10 +2078,16 @@ A comparison a > b is translated to b < a and a >= b is translated to b <= a. +

+Following the IEEE 754 standard, +NaN is considered neither smaller than, +nor equal to, nor greater than any value (including itself). + + -

3.4.4 – Logical Operators

+

3.4.5 – Logical Operators

The logical operators in Lua are and, or, and not. Like the control structures (see §3.3.4), @@ -2035,7 +2103,7 @@ otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false; otherwise, or returns its second argument. -Both and and or use short-cut evaluation; +Both and and or use short-circuit evaluation; that is, the second operand is evaluated only if necessary. Here are some examples: @@ -2057,18 +2125,18 @@ Here are some examples: -

3.4.5 – Concatenation

+

3.4.6 – Concatenation

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to -strings according to the rules mentioned in §3.4.2. +strings according to the rules described in §3.4.3. Otherwise, the __concat metamethod is called (see §2.4). -

3.4.6 – The Length Operator

+

3.4.7 – The Length Operator

The length operator is denoted by the unary prefix operator #. @@ -2106,7 +2174,7 @@ with whether a table is a sequence. -

3.4.7 – Precedence

+

3.4.8 – Precedence

Operator precedence in Lua follows the table below, from lower to higher priority: @@ -2114,10 +2182,14 @@ from lower to higher priority: or and < > <= >= ~= == + | + ~ + & + << >> .. + - - * / % - not # - (unary) + * / // % + unary operators (not # - ~) ^

As usual, @@ -2130,7 +2202,7 @@ All other binary operators are left associative. -

3.4.8 – Table Constructors

+

3.4.9 – Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table @@ -2150,7 +2222,7 @@ with key exp1 and value exp2. A field of the form name = exp is equivalent to ["name"] = exp. Finally, fields of the form exp are equivalent to -[i] = exp, where i are consecutive numerical integers, +[i] = exp, where i are consecutive integers starting with 1. Fields in the other formats do not affect this counting. For example, @@ -2175,10 +2247,15 @@ is equivalent to

+The order of the assignments in a constructor is undefined. +(This order would be relevant only when there are repeated keys.) + + +

If the last field in the list has the form exp and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively -(see §3.4.9). +(see §3.4.10).

@@ -2189,7 +2266,7 @@ as a convenience for machine-generated code. -

3.4.9 – Function Calls

+

3.4.10 – Function Calls

A function call in Lua has the following syntax:

@@ -2224,7 +2301,7 @@ Arguments have the following syntax:
 
 	args ::= ‘(’ [explist] ‘)’
 	args ::= tableconstructor
-	args ::= String
+	args ::= LiteralString
 

All argument expressions are evaluated before the call. A call of the form f{fields} is @@ -2264,7 +2341,7 @@ So, none of the following examples are tail calls: -

3.4.10 – Function Definitions

+

3.4.11 – Function Definitions

The syntax for function definition is @@ -2555,12 +2632,13 @@ you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function lua_checkstack -to ensure that the stack has extra slots when pushing new elements. +to ensure that the stack has enough space for pushing new elements.

Whenever Lua calls C, -it ensures that the stack has at least LUA_MINSTACK extra slots. +it ensures that the stack has space for +at least LUA_MINSTACK extra slots. LUA_MINSTACK is defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. @@ -2569,7 +2647,7 @@ unless your code has loops pushing elements onto the stack.

When you call a Lua function without a fixed number of results (see lua_call), -Lua ensures that the stack has enough size for all results, +Lua ensures that the stack has enough space for all results, but it does not ensure any extra space. So, before pushing anything in the stack after such a call you should use lua_checkstack. @@ -2587,29 +2665,22 @@ works only with valid indices or acceptable indices.

A valid index is an index that refers to a -real position within the stack, that is, -its position lies between 1 and the stack top -(1 ≤ abs(index) ≤ top). - -Usually, functions that can modify the value at an index -require valid indices. - - -

-Unless otherwise noted, -any function that accepts valid indices also accepts pseudo-indices, -which represent some Lua values that are accessible to C code -but which are not in the stack. -Pseudo-indices are used to access the registry +position that stores a modifiable Lua value. +It comprises stack indices between 1 and the stack top +(1 ≤ abs(index) ≤ top) + +plus pseudo-indices, +which represent some positions that are accessible to C code +but that are not in the stack. +Pseudo-indices are used to access the registry (see §4.5) and the upvalues of a C function (see §4.4).

-Functions that do not need a specific stack position, -but only a value in the stack (e.g., query functions), +Functions that do not need a specific mutable position, +but only a value (e.g., query functions), can be called with acceptable indices. An acceptable index can be any valid index, -including the pseudo-indices, but it also can be any positive index after the stack top within the space allocated for the stack, that is, indices up to the stack size. @@ -2652,11 +2723,13 @@ Whenever a C function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro lua_upvalueindex. -The first value associated with a function is at position +The first upvalue associated with a function is at index lua_upvalueindex(1), and so on. Any access to lua_upvalueindex(n), where n is greater than the number of upvalues of the -current function (but not greater than 256), +current function +(but not greater than 256, +which is one plus the maximum number of upvalues in a closure), produces an acceptable but invalid index. @@ -2670,25 +2743,24 @@ Lua provides a registry, a predefined table that can be used by any C code to store whatever Lua values it needs to store. The registry table is always located at pseudo-index -LUA_REGISTRYINDEX, -which is a valid index. +LUA_REGISTRYINDEX. Any C library can store data into this table, -but it should take care to choose keys +but it must take care to choose keys that are different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name, or a light userdata with the address of a C object in your code, or any Lua object created by your code. -As with global names, +As with variable names, string keys starting with an underscore followed by uppercase letters are reserved for Lua.

-The integer keys in the registry are used by the reference mechanism, -implemented by the auxiliary library, +The integer keys in the registry are used +by the reference mechanism (see luaL_ref) and by some predefined values. -Therefore, integer keys should not be used for other purposes. +Therefore, integer keys must not be used for other purposes.

@@ -2716,8 +2788,8 @@ the global environment.

Internally, Lua uses the C longjmp facility to handle errors. -(You can also choose to use exceptions if you compile Lua as C++; -search for LUAI_THROW in the source code.) +(Lua will use exceptions if you compile it as C++; +search for LUAI_THROW in the source code for details.) When Lua faces any error (such as a memory allocation error, type errors, syntax errors, and runtime errors) @@ -2740,21 +2812,21 @@ never returning

The panic function runs as if it were a message handler (see §2.3); -in particular, the error message is at the top of the stack. -However, there is no guarantees about stack space. +in particular, the error object is at the top of the stack. +However, there is no guarantee about stack space. To push anything on the stack, -the panic function should first check the available space (see §4.2). +the panic function must first check the available space (see §4.2).

-Most functions in the API can throw an error, +Most functions in the API can raise an error, for instance due to a memory allocation error. The documentation for each function indicates whether -it can throw errors. +it can raise errors.

-Inside a C function you can throw an error by calling lua_error. +Inside a C function you can raise an error by calling lua_error. @@ -2764,7 +2836,7 @@ Inside a C function you can throw an error by calling

Internally, Lua uses the C longjmp facility to yield a coroutine. -Therefore, if a function foo calls an API function +Therefore, if a C function foo calls an API function and this API function yields (directly or indirectly by calling another function that yields), Lua cannot return to foo any more, @@ -2777,7 +2849,7 @@ Lua raises an error whenever it tries to yield across an API call, except for three functions: lua_yieldk, lua_callk, and lua_pcallk. All those functions receive a continuation function -(as a parameter called k) to continue execution after a yield. +(as a parameter named k) to continue execution after a yield.

@@ -2807,6 +2879,81 @@ of the original function.

+As an illustration, consider the following function: + +

+     int original_function (lua_State *L) {
+       ...     /* code 1 */
+       status = lua_pcall(L, n, m, h);  /* calls Lua */
+       ...     /* code 2 */
+     }
+

+Now we want to allow +the Lua code being run by lua_pcall to yield. +First, we can rewrite our function like here: + +

+     int k (lua_State *L, int status, lua_KContext ctx) {
+       ...  /* code 2 */
+     }
+     
+     int original_function (lua_State *L) {
+       ...     /* code 1 */
+       return k(L, lua_pcall(L, n, m, h), ctx);
+     }
+

+In the above code, +the new function k is a +continuation function (with type lua_KFunction), +which should do all the work that the original function +was doing after calling lua_pcall. +Now, we must inform Lua that it must call k if the Lua code +being executed by lua_pcall gets interrupted in some way +(errors or yielding), +so we rewrite the code as here, +replacing lua_pcall by lua_pcallk: + +

+     int original_function (lua_State *L) {
+       ...     /* code 1 */
+       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
+     }
+

+Note the external, explicit call to the continuation: +Lua will call the continuation only if needed, that is, +in case of errors or resuming after a yield. +If the called function returns normally without ever yielding, +lua_pcallk (and lua_callk) will also return normally. +(Of course, instead of calling the continuation in that case, +you can do the equivalent work directly inside the original function.) + + +

+Besides the Lua state, +the continuation function has two other parameters: +the final status of the call plus the context value (ctx) that +was passed originally to lua_pcallk. +(Lua does not use this context value; +it only passes this value from the original function to the +continuation function.) +For lua_pcallk, +the status is the same value that would be returned by lua_pcallk, +except that it is LUA_YIELD when being executed after a yield +(instead of LUA_OK). +For lua_yieldk and lua_callk, +the status is always LUA_YIELD when Lua calls the continuation. +(For these two functions, +Lua will not call the continuation in case of errors, +because they do not handle errors.) +Similarly, when using lua_callk, +you should call the continuation function +with LUA_OK as the status. +(For lua_yieldk, there is not much point in calling +directly the continuation function, +because lua_yieldk usually does not return.) + + +

Lua treats the continuation function as if it were the original function. The continuation function receives the same Lua stack from the original function, @@ -2819,11 +2966,6 @@ Whatever it returns is handled by Lua as if it were the return of the original function. -

-The only difference in the Lua state between the original function -and its continuation is the result of a call to lua_getctx. - - @@ -2850,10 +2992,14 @@ we cannot know how many elements the function pops/pushes by looking only at its arguments (e.g., they may depend on what is on the stack). The third field, x, -tells whether the function may throw errors: -'-' means the function never throws any error; -'e' means the function may throw errors; -'v' means the function may throw an error on purpose. +tells whether the function may raise errors: +'-' means the function never raises any error; +'m' means the function may raise out-of-memory errors +and errors running a __gc metamethod; +'e' means the function may raise any errors +(it can run arbitrary Lua code, +either directly or through metamethods); +'v' means the function may raise an error on purpose. @@ -2862,7 +3008,8 @@ tells whether the function may throw errors:

int lua_absindex (lua_State *L, int idx);

-Converts the acceptable index idx into an absolute index +Converts the acceptable index idx +into an equivalent absolute index (that is, one that does not depend on the stack top). @@ -2885,7 +3032,7 @@ Its arguments are ptr, a pointer to the block being allocated/reallocated/freed; osize, the original size of the block or some code about what is being allocated; -nsize, the new size of the block. +and nsize, the new size of the block.

@@ -2911,13 +3058,13 @@ Lua assumes the following behavior from the allocator function:

When nsize is zero, -the allocator should behave like free +the allocator must behave like free and return NULL.

When nsize is not zero, -the allocator should behave like realloc. +the allocator must behave like realloc. The allocator returns NULL if and only if it cannot fulfill the request. Lua assumes that the allocator never fails when @@ -2942,7 +3089,7 @@ It is used in the auxiliary library by luaL_newst

Note that Standard C ensures that free(NULL) has no effect and that -realloc(NULL, size) is equivalent to malloc(size). +realloc(NULL,size) is equivalent to malloc(size). This code assumes that realloc does not fail when shrinking a block. (Although Standard C does not ensure this behavior, it seems to be a safe assumption.) @@ -2956,8 +3103,8 @@ it seems to be a safe assumption.)

void lua_arith (lua_State *L, int op);

-Performs an arithmetic operation over the two values -(or one, in the case of negation) +Performs an arithmetic or bitwise operation over the two values +(or one, in the case of negations) at the top of the stack, with the value at the top being the second operand, pops these values, and pushes the result of the operation. @@ -2973,10 +3120,17 @@ The value of op must be one of the following constants:

  • LUA_OPADD: performs addition (+)
  • LUA_OPSUB: performs subtraction (-)
  • LUA_OPMUL: performs multiplication (*)
  • -
  • LUA_OPDIV: performs division (/)
  • +
  • LUA_OPDIV: performs float division (/)
  • +
  • LUA_OPIDIV: performs floor division (//)
  • LUA_OPMOD: performs modulo (%)
  • LUA_OPPOW: performs exponentiation (^)
  • LUA_OPUNM: performs mathematical negation (unary -)
  • +
  • LUA_OPBNOT: performs bitwise NOT (~)
  • +
  • LUA_OPBAND: performs bitwise AND (&)
  • +
  • LUA_OPBOR: performs bitwise OR (|)
  • +
  • LUA_OPBXOR: performs bitwise exclusive OR (~)
  • +
  • LUA_OPSHL: performs left shift (<<)
  • +
  • LUA_OPSHR: performs right shift (>>)
  • @@ -3016,7 +3170,8 @@ The function results are pushed onto the stack when the function returns. The number of results is adjusted to nresults, unless nresults is LUA_MULTRET. In this case, all results from the function are pushed. -Lua takes care that the returned values fit into the stack space. +Lua takes care that the returned values fit into the stack space, +but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack. @@ -3038,7 +3193,7 @@ Here it is in C:
          lua_getglobal(L, "f");                  /* function to be called */
    -     lua_pushstring(L, "how");                        /* 1st argument */
    +     lua_pushliteral(L, "how");                       /* 1st argument */
          lua_getglobal(L, "t");                    /* table to be indexed */
          lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
          lua_remove(L, -2);                  /* remove 't' from the stack */
    @@ -3046,7 +3201,7 @@ Here it is in C:
          lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
          lua_setglobal(L, "a");                         /* set global 'a' */
     

    -Note that the code above is "balanced": +Note that the code above is balanced: at its end, the stack is back to its original configuration. This is considered good programming practice. @@ -3056,8 +3211,11 @@ This is considered good programming practice.


    lua_callk

    [-(nargs + 1), +nresults, e] -

    void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
    -                lua_CFunction k);
    +
    void lua_callk (lua_State *L,
    +                int nargs,
    +                int nresults,
    +                lua_KContext ctx,
    +                lua_KFunction k);

    This function behaves exactly like lua_call, @@ -3095,16 +3253,16 @@ many results.

    As an example, the following function receives a variable number -of numerical arguments and returns their average and sum: +of numeric arguments and returns their average and their sum:

          static int foo (lua_State *L) {
            int n = lua_gettop(L);    /* number of arguments */
    -       lua_Number sum = 0;
    +       lua_Number sum = 0.0;
            int i;
            for (i = 1; i <= n; i++) {
              if (!lua_isnumber(L, i)) {
    -           lua_pushstring(L, "incorrect argument");
    +           lua_pushliteral(L, "incorrect argument");
                lua_error(L);
              }
              sum += lua_tonumber(L, i);
    @@ -3120,16 +3278,18 @@ of numerical arguments and returns their average and sum:
     
     

    lua_checkstack

    [-0, +0, –] -

    int lua_checkstack (lua_State *L, int extra);
    +
    int lua_checkstack (lua_State *L, int n);

    -Ensures that there are at least extra free stack slots in the stack. +Ensures that the stack has space for at least n extra slots +(that is, that you can safely push up to n values into it). It returns false if it cannot fulfill the request, -because it would cause the stack to be larger than a fixed maximum size -(typically at least a few thousand elements) or -because it cannot allocate memory for the new stack size. +either because it would cause the stack +to be larger than a fixed maximum size +(typically at least several thousand elements) or +because it cannot allocate memory for the extra space. This function never shrinks the stack; -if the stack is already larger than the new size, +if the stack already has space for the extra slots, it is left unchanged. @@ -3148,7 +3308,7 @@ On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, -might need to close states as soon as they are not needed. +will probably need to close states as soon as they are not needed. @@ -3165,7 +3325,7 @@ when compared with the value at index index2, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns 0. -Also returns 0 if any of the indices is non valid. +Also returns 0 if any of the indices is not valid.

    @@ -3193,7 +3353,7 @@ If n is 1, the result is the single value on the stack (that is, the function does nothing); if n is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua -(see §3.4.5). +(see §3.4.6). @@ -3204,17 +3364,17 @@ Concatenation is performed following the usual semantics of Lua

    void lua_copy (lua_State *L, int fromidx, int toidx);

    -Moves the element at index fromidx -into the valid index toidx -without shifting any element -(therefore replacing the value at that position). +Copies the element at index fromidx +into the valid index toidx, +replacing the value at that position. +Values at other positions are not affected.


    lua_createtable

    -[-0, +1, e] +[-0, +1, m]

    void lua_createtable (lua_State *L, int narr, int nrec);

    @@ -3224,7 +3384,7 @@ will have as a sequence; parameter nrec is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. -This pre-allocation is useful for performance when you know in advance +This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function lua_newtable. @@ -3233,8 +3393,11 @@ Otherwise you can use the function lua_newtable

    lua_dump

    -[-0, +0, e] -

    int lua_dump (lua_State *L, lua_Writer writer, void *data);
    +[-0, +0, –] +
    int lua_dump (lua_State *L,
    +                        lua_Writer writer,
    +                        void *data,
    +                        int strip);

    Dumps a function as a binary chunk. @@ -3249,6 +3412,13 @@ to write them.

    +If strip is true, +the binary representation may not include all debug information +about the function, +to save space. + + +

    The value returned is the error code returned by the last call to the writer; 0 means no errors. @@ -3266,9 +3436,8 @@ This function does not pop the Lua function from the stack.

    int lua_error (lua_State *L);

    -Generates a Lua error. -The error message (which can actually be a Lua value of any type) -must be on the stack top. +Generates a Lua error, +using the value at the top of the stack as the error object. This function does a long jump, and therefore never returns (see luaL_error). @@ -3278,7 +3447,7 @@ and therefore never returns


    lua_gc

    -[-0, +0, e] +[-0, +0, m]

    int lua_gc (lua_State *L, int what, int data);

    @@ -3314,24 +3483,18 @@ memory in use by Lua by 1024.

  • LUA_GCSTEP: performs an incremental step of garbage collection. -The step "size" is controlled by data -(larger values mean more steps) in a non-specified way. -If you want to control the step size -you must experimentally tune the value of data. -The function returns 1 if the step finished a -garbage-collection cycle.
  • LUA_GCSETPAUSE: sets data as the new value -for the pause of the collector (see §2.5). -The function returns the previous value of the pause. +for the pause of the collector (see §2.5) +and returns the previous value of the pause.
  • LUA_GCSETSTEPMUL: sets data as the new value for the step multiplier of -the collector (see §2.5). -The function returns the previous value of the step multiplier. +the collector (see §2.5) +and returns the previous value of the step multiplier.
  • LUA_GCISRUNNING: @@ -3339,16 +3502,6 @@ returns a boolean that tells whether the collector is running (i.e., not stopped).
  • -
  • LUA_GCGEN: -changes the collector to generational mode -(see §2.5). -
  • - -
  • LUA_GCINC: -changes the collector to incremental mode. -This is the default mode. -
  • -

    @@ -3366,68 +3519,80 @@ see collectgarbage.

    Returns the memory-allocation function of a given state. If ud is not NULL, Lua stores in *ud the -opaque pointer passed to lua_newstate. +opaque pointer given when the memory-allocator function was set. + + + +


    lua_getfield

    +[-0, +1, e] +

    int lua_getfield (lua_State *L, int index, const char *k);
    + +

    +Pushes onto the stack the value t[k], +where t is the value at the given index. +As in Lua, this function may trigger a metamethod +for the "index" event (see §2.4). + + +

    +Returns the type of the pushed value. + -


    lua_getctx

    + +


    lua_getextraspace

    [-0, +0, –] -

    int lua_getctx (lua_State *L, int *ctx);
    +
    void *lua_getextraspace (lua_State *L);

    -This function is called by a continuation function (see §4.7) -to retrieve the status of the thread and a context information. +Returns a pointer to a raw memory area associated with the +given Lua state. +The application can use this area for any purpose; +Lua does not use it for anything.

    -When called in the original function, -lua_getctx always returns LUA_OK -and does not change the value of its argument ctx. -When called inside a continuation function, -lua_getctx returns LUA_YIELD and sets -the value of ctx to be the context information -(the value passed as the ctx argument -to the callee together with the continuation function). +Each new thread has this area initialized with a copy +of the area of the main thread.

    -When the callee is lua_pcallk, -Lua may also call its continuation function -to handle errors during the call. -That is, upon an error in the function called by lua_pcallk, -Lua may not return to the original function -but instead may call the continuation function. -In that case, a call to lua_getctx will return the error code -(the value that would be returned by lua_pcallk); -the value of ctx will be set to the context information, -as in the case of a yield. +By default, this area has the size of a pointer to void, +but you can recompile Lua with a different size for this area. +(See LUA_EXTRASPACE in luaconf.h.) -


    lua_getfield

    +


    lua_getglobal

    [-0, +1, e] -

    void lua_getfield (lua_State *L, int index, const char *k);
    +
    int lua_getglobal (lua_State *L, const char *name);

    -Pushes onto the stack the value t[k], -where t is the value at the given index. -As in Lua, this function may trigger a metamethod -for the "index" event (see §2.4). +Pushes onto the stack the value of the global name. +Returns the type of that value. -


    lua_getglobal

    +


    lua_geti

    [-0, +1, e] -

    void lua_getglobal (lua_State *L, const char *name);
    +
    int lua_geti (lua_State *L, int index, lua_Integer i);

    -Pushes onto the stack the value of the global name. +Pushes onto the stack the value t[i], +where t is the value at the given index. +As in Lua, this function may trigger a metamethod +for the "index" event (see §2.4). + + +

    +Returns the type of the pushed value. @@ -3438,8 +3603,9 @@ Pushes onto the stack the value of the global name.

    int lua_getmetatable (lua_State *L, int index);

    -Pushes onto the stack the metatable of the value at the given index. -If the value does not have a metatable, +If the value at the given index has a metatable, +the function pushes that metatable onto the stack and returns 1. +Otherwise, the function returns 0 and pushes nothing on the stack. @@ -3448,7 +3614,7 @@ the function returns 0 and pushes nothing on the stack.


    lua_gettable

    [-1, +1, e] -

    void lua_gettable (lua_State *L, int index);
    +
    int lua_gettable (lua_State *L, int index);

    Pushes onto the stack the value t[k], @@ -3457,12 +3623,16 @@ and k is the value at the top of the stack.

    -This function pops the key from the stack -(putting the resulting value in its place). +This function pops the key from the stack, +pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4). +

    +Returns the type of the pushed value. + + @@ -3473,8 +3643,8 @@ for the "index" event (see §2.4).

    Returns the index of the top element in the stack. Because indices start at 1, -this result is equal to the number of elements in the stack -(and so 0 means an empty stack). +this result is equal to the number of elements in the stack; +in particular, 0 means an empty stack. @@ -3482,12 +3652,15 @@ this result is equal to the number of elements in the stack


    lua_getuservalue

    [-0, +1, –] -

    void lua_getuservalue (lua_State *L, int index);
    +
    int lua_getuservalue (lua_State *L, int index);

    Pushes onto the stack the Lua value associated with the userdata at the given index. -This Lua value must be a table or nil. + + +

    +Returns the type of the pushed value. @@ -3508,16 +3681,24 @@ because a pseudo-index is not an actual stack position.


    lua_Integer

    -
    typedef ptrdiff_t lua_Integer;
    +
    typedef ... lua_Integer;
    + +

    +The type of integers in Lua. +

    -The type used by the Lua API to represent signed integral values. +By default this type is long long, +(usually a 64-bit two-complement integer), +but that can be changed to long or int +(usually a 32-bit two-complement integer). +(See LUA_INT_TYPE in luaconf.h.)

    -By default it is a ptrdiff_t, -which is usually the largest signed integral type the machine handles -"comfortably". +Lua also defines the constants +LUA_MININTEGER and LUA_MAXINTEGER, +with the minimum and the maximum values that fit in this type. @@ -3559,6 +3740,19 @@ Returns 1 if the value at the given index is a function +


    lua_isinteger

    +[-0, +0, –] +

    int lua_isinteger (lua_State *L, int index);
    + +

    +Returns 1 if the value at the given index is an integer +(that is, the value is a number and is represented as an integer), +and 0 otherwise. + + + + +


    lua_islightuserdata

    [-0, +0, –]

    int lua_islightuserdata (lua_State *L, int index);
    @@ -3670,13 +3864,51 @@ Returns 1 if the value at the given index is a userdata +

    lua_isyieldable

    +[-0, +0, –] +

    int lua_isyieldable (lua_State *L);
    + +

    +Returns 1 if the given coroutine can yield, +and 0 otherwise. + + + + + +


    lua_KContext

    +
    typedef ... lua_KContext;
    + +

    +The type for continuation-function contexts. +It must be a numeric type. +This type is defined as intptr_t +when intptr_t is available, +so that it can store pointers too. +Otherwise, it is defined as ptrdiff_t. + + + + + +


    lua_KFunction

    +
    typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
    + +

    +Type for continuation functions (see §4.7). + + + + +


    lua_len

    [-0, +1, e]

    void lua_len (lua_State *L, int index);

    -Returns the "length" of the value at the given index; -it is equivalent to the '#' operator in Lua (see §3.4.6). +Returns the length of the value at the given index. +It is equivalent to the '#' operator in Lua (see §3.4.7) and +may trigger a metamethod for the "length" event (see §2.4). The result is pushed on the stack. @@ -3688,11 +3920,11 @@ The result is pushed on the stack.

    int lua_load (lua_State *L,
                   lua_Reader reader,
                   void *data,
    -              const char *source,
    +              const char *chunkname,
                   const char *mode);

    -Loads a Lua chunk (without running it). +Loads a Lua chunk without running it. If there are no errors, lua_load pushes the compiled chunk as a Lua function on top of the stack. @@ -3710,7 +3942,7 @@ The return values of lua_load are: syntax error during precompilation;

  • LUA_ERRMEM: -memory allocation error;
  • +memory allocation (out-of-memory) error;
  • LUA_ERRGCMM: error while running a __gc metamethod. @@ -3727,7 +3959,7 @@ The data argument is an opaque value passed to the reader function.

    -The source argument gives a name to the chunk, +The chunkname argument gives a name to the chunk, which is used for error messages and in debug information (see §4.9). @@ -3741,16 +3973,17 @@ a NULL value is equivalent to the string "bt".

    lua_load uses the stack internally, -so the reader function should always leave the stack +so the reader function must always leave the stack unmodified when returning.

    -If the resulting function has one upvalue, -this upvalue is set to the value of the global environment +If the resulting function has upvalues, +its first upvalue is set to the value of the global environment stored at index LUA_RIDX_GLOBALS in the registry (see §4.5). When loading main chunks, this upvalue will be the _ENV variable (see §2.2). +Other upvalues are initialized with nil. @@ -3762,7 +3995,7 @@ this upvalue will be the _ENV variable (see §2.

    Creates a new thread running in a new, independent state. -Returns NULL if cannot create the thread or the state +Returns NULL if it cannot create the thread or the state (due to lack of memory). The argument f is the allocator function; Lua does all memory allocation for this state through this function. @@ -3774,7 +4007,7 @@ passes to the allocator in every call.


    lua_newtable

    -[-0, +1, e] +[-0, +1, m]

    void lua_newtable (lua_State *L);

    @@ -3786,7 +4019,7 @@ It is equivalent to lua_createtable(L, 0, 0).


    lua_newthread

    -[-0, +1, e] +[-0, +1, m]

    lua_State *lua_newthread (lua_State *L);

    @@ -3807,7 +4040,7 @@ like any Lua object.


    lua_newuserdata

    -[-0, +1, e] +[-0, +1, m]

    void *lua_newuserdata (lua_State *L, size_t size);

    @@ -3866,13 +4099,38 @@ the table during its traversal.


    lua_Number

    -
    typedef double lua_Number;
    +
    typedef ... lua_Number;
    + +

    +The type of floats in Lua. + + +

    +By default this type is double, +but that can be changed to a single float or a long double. +(See LUA_FLOAT_TYPE in luaconf.h.) + + + + + +


    lua_numbertointeger

    +
    int lua_numbertointeger (lua_Number n, lua_Integer *p);

    -The type of numbers in Lua. -By default, it is double, but that can be changed in luaconf.h. -Through this configuration file you can change -Lua to operate with another type for numbers (e.g., float or long). +Converts a Lua float to a Lua integer. +This macro assumes that n has an integral value. +If that value is within the range of Lua integers, +it is converted to an integer and assigned to *p. +The macro results in a boolean indicating whether the +conversion was successful. +(Note that this range test can be tricky to do +correctly without this macro, +due to roundings.) + + +

    +This macro may evaluate its arguments more than once. @@ -3893,7 +4151,7 @@ If there are no errors during the call, lua_pcall behaves exactly like lua_call. However, if there is any error, lua_pcall catches it, -pushes a single value on the stack (the error message), +pushes a single value on the stack (the error object), and returns an error code. Like lua_call, lua_pcall always removes the function @@ -3902,26 +4160,26 @@ and its arguments from the stack.

    If msgh is 0, -then the error message returned on the stack -is exactly the original error message. +then the error object returned on the stack +is exactly the original error object. Otherwise, msgh is the stack index of a message handler. -(In the current implementation, this index cannot be a pseudo-index.) +(This index cannot be a pseudo-index.) In case of runtime errors, -this function will be called with the error message -and its return value will be the message +this function will be called with the error object +and its return value will be the object returned on the stack by lua_pcall.

    Typically, the message handler is used to add more debug -information to the error message, such as a stack traceback. +information to the error object, such as a stack traceback. Such information cannot be gathered after the return of lua_pcall, since by then the stack has unwound.

    -The lua_pcall function returns one of the following codes +The lua_pcall function returns one of the following constants (defined in lua.h):

      @@ -3944,8 +4202,7 @@ error while running the message handler.
    • LUA_ERRGCMM: error while running a __gc metamethod. -(This error typically has no relation with the function being called. -It is generated by the garbage collector.) +(This error typically has no relation with the function being called.)
    @@ -3958,9 +4215,9 @@ It is generated by the garbage collector.)
    int lua_pcallk (lua_State *L,
                     int nargs,
                     int nresults,
    -                int errfunc,
    -                int ctx,
    -                lua_CFunction k);
    + int msgh, + lua_KContext ctx, + lua_KFunction k);
  • This function behaves exactly like lua_pcall, @@ -3993,7 +4250,7 @@ Pushes a boolean value with value b onto the stack.


    lua_pushcclosure

    -[-n, +1, e] +[-n, +1, m]

    void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);

    @@ -4006,11 +4263,11 @@ it is possible to associate some values with it, thus creating a C closure (see §4.4); these values are then accessible to the function whenever it is called. To associate values with a C function, -first these values should be pushed onto the stack +first these values must be pushed onto the stack (when there are multiple values, the first value is pushed first). Then lua_pushcclosure is called to create and push the C function onto the stack, -with the argument n telling how many values should be +with the argument n telling how many values will be associated with the function. lua_pushcclosure also pops these values from the stack. @@ -4023,7 +4280,7 @@ The maximum value for n is 255. When n is zero, this function creates a light C function, which is just a pointer to the C function. -In that case, it never throws a memory error. +In that case, it never raises a memory error. @@ -4041,20 +4298,11 @@ when called, invokes the corresponding C function.

    -Any function to be registered in Lua must +Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see lua_CFunction). -

    -lua_pushcfunction is defined as a macro: - -

    -     #define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)
    -

    -Note that f is used twice. - - @@ -4080,16 +4328,24 @@ the result is a Lua string and Lua takes care of memory allocation The conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can only be -'%%' (inserts a '%' in the string), +'%%' (inserts the character '%'), '%s' (inserts a zero-terminated string, with no size restrictions), '%f' (inserts a lua_Number), +'%I' (inserts a lua_Integer), '%p' (inserts a pointer as a hexadecimal numeral), -'%d' (inserts an int), and -'%c' (inserts an int as a byte). +'%d' (inserts an int), +'%c' (inserts an int as a one-byte character), and +'%U' (inserts a long int as a UTF-8 byte sequence). +

    +Unlike other push functions, +this function checks for the stack space it needs, +including the slot for its result. + + @@ -4109,7 +4365,7 @@ Pushes the global environment onto the stack.

    void lua_pushinteger (lua_State *L, lua_Integer n);

    -Pushes a number with value n onto the stack. +Pushes an integer with value n onto the stack. @@ -4137,20 +4393,19 @@ light userdata with the same C address.


    lua_pushliteral

    -[-0, +1, e] +[-0, +1, m]

    const char *lua_pushliteral (lua_State *L, const char *s);

    -This macro is equivalent to lua_pushlstring, -but can be used only when s is a literal string. -It automatically provides the string length. +This macro is equivalent to lua_pushstring, +but should be used only when s is a literal string.


    lua_pushlstring

    -[-0, +1, e] +[-0, +1, m]

    const char *lua_pushlstring (lua_State *L, const char *s, size_t len);

    @@ -4186,14 +4441,14 @@ Pushes a nil value onto the stack.

    void lua_pushnumber (lua_State *L, lua_Number n);

    -Pushes a number with value n onto the stack. +Pushes a float with value n onto the stack.


    lua_pushstring

    -[-0, +1, e] +[-0, +1, m]

    const char *lua_pushstring (lua_State *L, const char *s);

    @@ -4227,17 +4482,6 @@ Returns 1 if this thread is the main thread of its state. -


    lua_pushunsigned

    -[-0, +1, –] -

    void lua_pushunsigned (lua_State *L, lua_Unsigned n);
    - -

    -Pushes a number with value n onto the stack. - - - - -


    lua_pushvalue

    [-0, +1, –]

    void lua_pushvalue (lua_State *L, int index);
    @@ -4251,7 +4495,7 @@ onto the stack.

    lua_pushvfstring

    -[-0, +1, e] +[-0, +1, m]

    const char *lua_pushvfstring (lua_State *L,
                                   const char *fmt,
                                   va_list argp);
    @@ -4271,9 +4515,9 @@ instead of a variable number of arguments.

    Returns 1 if the two values in indices index1 and index2 are primitively equal -(that is, without calling metamethods). +(that is, without calling the __eq metamethod). Otherwise returns 0. -Also returns 0 if any of the indices are non valid. +Also returns 0 if any of the indices are not valid. @@ -4281,7 +4525,7 @@ Also returns 0 if any of the indices are non valid.


    lua_rawget

    [-1, +1, –] -

    void lua_rawget (lua_State *L, int index);
    +
    int lua_rawget (lua_State *L, int index);

    Similar to lua_gettable, but does a raw access @@ -4293,13 +4537,17 @@ Similar to lua_gettable, but does a raw


    lua_rawgeti

    [-0, +1, –] -

    void lua_rawgeti (lua_State *L, int index, int n);
    +
    int lua_rawgeti (lua_State *L, int index, lua_Integer n);

    Pushes onto the stack the value t[n], where t is the table at the given index. -The access is raw; -that is, it does not invoke metamethods. +The access is raw, +that is, it does not invoke the __index metamethod. + + +

    +Returns the type of the pushed value. @@ -4307,14 +4555,18 @@ that is, it does not invoke metamethods.


    lua_rawgetp

    [-0, +1, –] -

    void lua_rawgetp (lua_State *L, int index, const void *p);
    +
    int lua_rawgetp (lua_State *L, int index, const void *p);

    Pushes onto the stack the value t[k], where t is the table at the given index and k is the pointer p represented as a light userdata. The access is raw; -that is, it does not invoke metamethods. +that is, it does not invoke the __index metamethod. + + +

    +Returns the type of the pushed value. @@ -4338,7 +4590,7 @@ for other values, it is 0.


    lua_rawset

    -[-2, +0, e] +[-2, +0, m]

    void lua_rawset (lua_State *L, int index);

    @@ -4350,39 +4602,39 @@ Similar to lua_settable, but does a raw


    lua_rawseti

    -[-1, +0, e] -

    void lua_rawseti (lua_State *L, int index, int n);
    +[-1, +0, m] +
    void lua_rawseti (lua_State *L, int index, lua_Integer i);

    -Does the equivalent of t[n] = v, +Does the equivalent of t[i] = v, where t is the table at the given index and v is the value at the top of the stack.

    This function pops the value from the stack. -The assignment is raw; -that is, it does not invoke metamethods. +The assignment is raw, +that is, it does not invoke the __newindex metamethod.


    lua_rawsetp

    -[-1, +0, e] +[-1, +0, m]

    void lua_rawsetp (lua_State *L, int index, const void *p);

    -Does the equivalent of t[k] = v, +Does the equivalent of t[p] = v, where t is the table at the given index, -k is the pointer p represented as a light userdata, +p is encoded as a light userdata, and v is the value at the top of the stack.

    This function pops the value from the stack. -The assignment is raw; -that is, it does not invoke metamethods. +The assignment is raw, +that is, it does not invoke __newindex metamethod. @@ -4447,7 +4699,7 @@ because a pseudo-index is not an actual stack position.

    Moves the top element into the given valid index without shifting any element -(therefore replacing the value at the given index), +(therefore replacing the value at that given index), and then pops the top element. @@ -4459,7 +4711,7 @@ and then pops the top element.

    int lua_resume (lua_State *L, lua_State *from, int nargs);

    -Starts and resumes a coroutine in a given thread. +Starts and resumes a coroutine in the given thread L.

    @@ -4481,7 +4733,7 @@ or an error code in case of errors (see lua_pcall @@ -4501,6 +4753,26 @@ this parameter can be NULL. +


    lua_rotate

    +[-0, +0, –] +

    void lua_rotate (lua_State *L, int idx, int n);
    + +

    +Rotates the stack elements between the valid index idx +and the top of the stack. +The elements are rotated n positions in the direction of the top, +for a positive n, +or -n positions in the direction of the bottom, +for a negative n. +The absolute value of n must not be greater than the size +of the slice being rotated. +This function cannot be called with a pseudo-index, +because a pseudo-index is not an actual stack position. + + + + +


    lua_setallocf

    [-0, +0, –]

    void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
    @@ -4544,6 +4816,25 @@ sets it as the new value of global name. +

    lua_seti

    +[-1, +0, e] +

    void lua_seti (lua_State *L, int index, lua_Integer n);
    + +

    +Does the equivalent to t[n] = v, +where t is the value at the given index +and v is the value at the top of the stack. + + +

    +This function pops the value from the stack. +As in Lua, this function may trigger a metamethod +for the "newindex" event (see §2.4). + + + + +


    lua_setmetatable

    [-1, +0, –]

    void lua_setmetatable (lua_State *L, int index);
    @@ -4596,7 +4887,7 @@ If index is 0, then all stack elements are removed.
    void lua_setuservalue (lua_State *L, int index);

    -Pops a table or nil from the stack and sets it as +Pops a value from the stack and sets it as the new value associated to the userdata at the given index. @@ -4648,6 +4939,27 @@ You can resume threads with status LUA_OK +


    lua_stringtonumber

    +[-0, +1, –] +

    size_t lua_stringtonumber (lua_State *L, const char *s);
    + +

    +Converts the zero-terminated string s to a number, +pushes that number into the stack, +and returns the total size of the string, +that is, its length plus one. +The conversion can result in an integer or a float, +according to the lexical conventions of Lua (see §3.1). +The string may have leading and trailing spaces and a sign. +If the string is not a valid numeral, +returns 0 and pushes nothing. +(Note that the result can be used as a boolean, +true if the conversion succeeds.) + + + + +


    lua_toboolean

    [-0, +0, –]

    int lua_toboolean (lua_State *L, int index);
    @@ -4697,17 +5009,12 @@ Equivalent to lua_tointegerx with Converts the Lua value at the given index to the signed integral type lua_Integer. -The Lua value must be a number or a string convertible to a number -(see §3.4.2); +The Lua value must be an integer, +or a number or string convertible to an integer (see §3.4.3); otherwise, lua_tointegerx returns 0.

    -If the number is not an integer, -it is truncated in some non-specified way. - - -

    If isnum is not NULL, its referent is assigned a boolean value that indicates whether the operation succeeded. @@ -4717,13 +5024,13 @@ indicates whether the operation succeeded.


    lua_tolstring

    -[-0, +0, e] +[-0, +0, m]

    const char *lua_tolstring (lua_State *L, int index, size_t *len);

    Converts the Lua value at the given index to a C string. If len is not NULL, -it also sets *len with the string length. +it sets *len with the string length. The Lua value must be a string or a number; otherwise, the function returns NULL. If the value is a number, @@ -4734,14 +5041,17 @@ when lua_tolstring is applied to keys during a table traversal.)

    -lua_tolstring returns a fully aligned pointer +lua_tolstring returns a pointer to a string inside the Lua state. This string always has a zero ('\0') after its last character (as in C), but can contain other zeros in its body. + + +

    Because Lua has garbage collection, there is no guarantee that the pointer returned by lua_tolstring -will be valid after the corresponding value is removed from the stack. +will be valid after the corresponding Lua value is removed from the stack. @@ -4766,7 +5076,7 @@ Equivalent to lua_tonumberx with lua_Number (see lua_Number). The Lua value must be a number or a string convertible to a number -(see §3.4.2); +(see §3.4.3); otherwise, lua_tonumberx returns 0. @@ -4793,14 +5103,14 @@ There is no way to convert the pointer back to its original value.

    -Typically this function is used only for debug information. +Typically this function is used only for hashing and debug information.


    lua_tostring

    -[-0, +0, e] +[-0, +0, m]

    const char *lua_tostring (lua_State *L, int index);

    @@ -4824,46 +5134,6 @@ otherwise, the function returns NULL. -


    lua_tounsigned

    -[-0, +0, –] -

    lua_Unsigned lua_tounsigned (lua_State *L, int index);
    - -

    -Equivalent to lua_tounsignedx with isnum equal to NULL. - - - - - -


    lua_tounsignedx

    -[-0, +0, –] -

    lua_Unsigned lua_tounsignedx (lua_State *L, int index, int *isnum);
    - -

    -Converts the Lua value at the given index -to the unsigned integral type lua_Unsigned. -The Lua value must be a number or a string convertible to a number -(see §3.4.2); -otherwise, lua_tounsignedx returns 0. - - -

    -If the number is not an integer, -it is truncated in some non-specified way. -If the number is outside the range of representable values, -it is normalized to the remainder of its division by -one more than the maximum representable value. - - -

    -If isnum is not NULL, -its referent is assigned a boolean value that -indicates whether the operation succeeded. - - - - -


    lua_touserdata

    [-0, +0, –]

    void *lua_touserdata (lua_State *L, int index);
    @@ -4888,7 +5158,7 @@ Returns the type of the value in the given valid index, or LUA_TNONE for a non-valid (but acceptable) index. The types returned by lua_type are coded by the following constants defined in lua.h: -LUA_TNIL, +LUA_TNIL (0), LUA_TNUMBER, LUA_TBOOLEAN, LUA_TSTRING, @@ -4916,16 +5186,10 @@ which must be one the values returned by lua_type

    lua_Unsigned

    -
    typedef unsigned long lua_Unsigned;
    - -

    -The type used by the Lua API to represent unsigned integral values. -It must have at least 32 bits. - +

    typedef ... lua_Unsigned;

    -By default it is an unsigned int or an unsigned long, -whichever can hold 32-bit values. +The unsigned version of lua_Integer. @@ -4944,11 +5208,13 @@ the running function (see §4.4).


    lua_version

    -[-0, +0, v] +[-0, +0, –]

    const lua_Number *lua_version (lua_State *L);

    -Returns the address of the version number stored in the Lua core. +Returns the address of the version number +(a C static variable) +stored in the Lua core. When called with a valid lua_State, returns the address of the version used to create that state. When called with NULL, @@ -5000,14 +5266,14 @@ and pushes them onto the stack to.


    lua_yield

    -[-?, +?, –] +[-?, +?, e]

    int lua_yield (lua_State *L, int nresults);

    This function is equivalent to lua_yieldk, but it has no continuation (see §4.7). Therefore, when the thread resumes, -it returns to the function that called +it continues the function that called the function calling lua_yield. @@ -5015,25 +5281,22 @@ the function calling lua_yield.


    lua_yieldk

    -[-?, +?, –] -

    int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k);
    +[-?, +?, e] +
    int lua_yieldk (lua_State *L,
    +                int nresults,
    +                lua_KContext ctx,
    +                lua_KFunction k);

    -Yields a coroutine. +Yields a coroutine (thread).

    -This function should only be called as the -return expression of a C function, as follows: - -

    -     return lua_yieldk (L, n, i, k);
    -

    -When a C function calls lua_yieldk in that way, +When a C function calls lua_yieldk, the running coroutine suspends its execution, and the call to lua_resume that started this coroutine returns. The parameter nresults is the number of values from the stack -that are passed as results to lua_resume. +that will be passed as results to lua_resume.

    @@ -5042,11 +5305,34 @@ Lua calls the given continuation function k to continue the execution of the C function that yielded (see §4.7). This continuation function receives the same stack from the previous function, -with the results removed and +with the n results removed and replaced by the arguments passed to lua_resume. Moreover, -the continuation function may access the value ctx -by calling lua_getctx. +the continuation function receives the value ctx +that was passed to lua_yieldk. + + +

    +Usually, this function does not return; +when the coroutine eventually resumes, +it continues executing the continuation function. +However, there is one special case, +which is when this function is called +from inside a line or a count hook (see §4.9). +In that case, lua_yieldk should be called with no continuation +(probably in the form of lua_yield) and no results, +and the hook should return immediately after the call. +Lua will yield and, +when the coroutine resumes again, +it will continue the normal execution +of the (Lua) function that triggered the hook. + + +

    +This function can raise an error if it is called from a thread +with a pending C call with no continuation function, +or it is called from a thread that is not running inside a resume +(e.g., the main thread). @@ -5100,7 +5386,7 @@ The fields of lua_Debug have the following

    • source: -the source of the chunk that created the function. +the name of the chunk that created the function. If source starts with a '@', it means that the function was defined in a file where the file name follows the '@'. @@ -5279,6 +5565,11 @@ numbers of the lines that are valid on the function. (A valid line is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.) + + +

      +If this option is given together with option 'f', +its table is pushed after the function.

    @@ -5293,7 +5584,7 @@ This function returns 0 on error

    lua_getlocal

    [-0, +(0|1), –] -

    const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);
    +
    const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);

    Gets information about a local variable of @@ -5316,7 +5607,7 @@ and returns its name.

    -In the second case, ar should be NULL and the function +In the second case, ar must be NULL and the function to be inspected must be at the top of the stack. In this case, only parameters of Lua functions are visible (as there is no information about what variables are active) @@ -5360,24 +5651,26 @@ it returns 0.

    const char *lua_getupvalue (lua_State *L, int funcindex, int n);

    -Gets information about a closure's upvalue. -(For Lua functions, -upvalues are the external local variables that the function uses, -and that are consequently included in its closure.) -lua_getupvalue gets the index n of an upvalue, -pushes the upvalue's value onto the stack, +Gets information about the n-th upvalue +of the closure at index funcindex. +It pushes the upvalue's value onto the stack and returns its name. -funcindex points to the closure in the stack. -(Upvalues have no particular order, -as they are active through the whole function. -So, they are numbered in an arbitrary order.) +Returns NULL (and pushes nothing) +when the index n is greater than the number of upvalues.

    -Returns NULL (and pushes nothing) -when the index is greater than the number of upvalues. For C functions, this function uses the empty string "" as a name for all upvalues. +(For Lua functions, +upvalues are the external local variables that the function uses, +and that are consequently included in its closure.) + + +

    +Upvalues have no particular order, +as they are active through the whole function. +They are numbered in an arbitrary order. @@ -5422,10 +5715,10 @@ that is, they cannot call lua_yieldk,

    Hook functions can yield under the following conditions: -Only count and line events can yield -and they cannot yield any value; -to yield a hook function must finish its execution -calling lua_yield with nresults equal to zero. +Only count and line events can yield; +to yield, a hook function must finish its execution +calling lua_yield with nresults equal to zero +(that is, with no values). @@ -5433,7 +5726,7 @@ calling lua_yield with nresults

    lua_sethook

    [-0, +0, –] -

    int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
    +
    void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);

    Sets the debugging hook function. @@ -5442,7 +5735,7 @@ Sets the debugging hook function.

    Argument f is the hook function. mask specifies on which events the hook will be called: -it is formed by a bitwise or of the constants +it is formed by a bitwise OR of the constants LUA_MASKCALL, LUA_MASKRET, LUA_MASKLINE, @@ -5486,13 +5779,11 @@ A hook is disabled by setting mask to zero.


    lua_setlocal

    [-(0|1), +0, –] -

    const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
    +
    const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);

    Sets the value of a local variable of a given activation record. -Parameters ar and n are as in lua_getlocal -(see lua_getlocal). -lua_setlocal assigns the value at the top of the stack +It assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. @@ -5503,6 +5794,10 @@ when the index is greater than the number of active local variables. +

    +Parameters ar and n are as in function lua_getlocal. + + @@ -5515,13 +5810,15 @@ Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. -Parameters funcindex and n are as in the lua_getupvalue -(see lua_getupvalue).

    Returns NULL (and pops nothing) -when the index is greater than the number of upvalues. +when the index n is greater than the number of upvalues. + + +

    +Parameters funcindex and n are as in function lua_getupvalue. @@ -5532,11 +5829,8 @@ when the index is greater than the number of upvalues.

    void *lua_upvalueid (lua_State *L, int funcindex, int n);

    -Returns an unique identifier for the upvalue numbered n +Returns a unique identifier for the upvalue numbered n from the closure at index funcindex. -Parameters funcindex and n are as in the lua_getupvalue -(see lua_getupvalue) -(but n cannot be greater than the number of upvalues).

    @@ -5547,6 +5841,11 @@ Lua closures that share an upvalue will return identical ids for those upvalue indices. +

    +Parameters funcindex and n are as in function lua_getupvalue, +but n cannot be greater than the number of upvalues. + + @@ -5609,7 +5908,7 @@ you should not use these functions for other stack values.

    Functions called luaL_check* -always throw an error if the check is not satisfied. +always raise an error if the check is not satisfied. @@ -5622,7 +5921,7 @@ in alphabetical order.


    luaL_addchar

    -[-?, +?, e] +[-?, +?, m]

    void luaL_addchar (luaL_Buffer *B, char c);

    @@ -5634,7 +5933,7 @@ Adds the byte c to the buffer B


    luaL_addlstring

    -[-?, +?, e] +[-?, +?, m]

    void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);

    @@ -5648,7 +5947,7 @@ The string can contain embedded zeros.


    luaL_addsize

    -[-?, +?, e] +[-?, +?, –]

    void luaL_addsize (luaL_Buffer *B, size_t n);

    @@ -5661,21 +5960,20 @@ buffer area (see luaL_prepbuffer).


    luaL_addstring

    -[-?, +?, e] +[-?, +?, m]

    void luaL_addstring (luaL_Buffer *B, const char *s);

    Adds the zero-terminated string pointed to by s to the buffer B (see luaL_Buffer). -The string cannot contain embedded zeros.


    luaL_addvalue

    -[-1, +?, e] +[-1, +?, m]

    void luaL_addvalue (luaL_Buffer *B);

    @@ -5703,7 +6001,7 @@ which is the value to be added to the buffer.

    Checks whether cond is true. -If not, raises an error with a standard message. +If it is not, raises an error with a standard message (see luaL_argerror). @@ -5714,14 +6012,15 @@ If not, raises an error with a standard message.

    int luaL_argerror (lua_State *L, int arg, const char *extramsg);

    -Raises an error with a standard message -that includes extramsg as a comment. +Raises an error reporting a problem with argument arg +of the C function that called it, +using a standard message +that includes extramsg as a comment: - -

    -This function never returns, -but it is an idiom to use it in C functions -as return luaL_argerror(args). +

    +     bad argument #arg to 'funcname' (extramsg)
    +

    +This function never returns. @@ -5812,7 +6111,7 @@ the buffer must be declared as a variable


    luaL_buffinitsize

    -[-?, +?, e] +[-?, +?, m]

    char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);

    @@ -5856,37 +6155,14 @@ of any type (including nil) at position arg. -


    luaL_checkint

    -[-0, +0, v] -

    int luaL_checkint (lua_State *L, int arg);
    - -

    -Checks whether the function argument arg is a number -and returns this number cast to an int. - - - - -


    luaL_checkinteger

    [-0, +0, v]

    lua_Integer luaL_checkinteger (lua_State *L, int arg);

    -Checks whether the function argument arg is a number -and returns this number cast to a lua_Integer. - - - - - -


    luaL_checklong

    -[-0, +0, v] -

    long luaL_checklong (lua_State *L, int arg);
    - -

    -Checks whether the function argument arg is a number -and returns this number cast to a long. +Checks whether the function argument arg is an integer +(or can be converted to an integer) +and returns this integer cast to a lua_Integer. @@ -6010,20 +6286,8 @@ returns the userdata address (see lua_touserdata -


    luaL_checkunsigned

    -[-0, +0, v] -

    lua_Unsigned luaL_checkunsigned (lua_State *L, int arg);
    - -

    -Checks whether the function argument arg is a number -and returns this number cast to a lua_Unsigned. - - - - -


    luaL_checkversion

    -[-0, +0, –] +[-0, +0, v]

    void luaL_checkversion (lua_State *L);

    @@ -6098,7 +6362,7 @@ as return luaL_error(args).


    luaL_execresult

    -[-0, +3, e] +[-0, +3, m]

    int luaL_execresult (lua_State *L, int stat);

    @@ -6111,7 +6375,7 @@ process-related functions in the standard library


    luaL_fileresult

    -[-0, +(1|3), e] +[-0, +(1|3), m]

    int luaL_fileresult (lua_State *L, int stat, const char *fname);

    @@ -6124,27 +6388,29 @@ file-related functions in the standard library


    luaL_getmetafield

    -[-0, +(0|1), e] +[-0, +(0|1), m]

    int luaL_getmetafield (lua_State *L, int obj, const char *e);

    Pushes onto the stack the field e from the metatable -of the object at index obj. +of the object at index obj and returns the type of pushed value. If the object does not have a metatable, or if the metatable does not have this field, -returns false and pushes nothing. +pushes nothing and returns LUA_TNIL.


    luaL_getmetatable

    -[-0, +1, –] -

    void luaL_getmetatable (lua_State *L, const char *tname);
    +[-0, +1, m] +
    int luaL_getmetatable (lua_State *L, const char *tname);

    Pushes onto the stack the metatable associated with name tname -in the registry (see luaL_newmetatable). +in the registry (see luaL_newmetatable) +(nil if there is no metatable associated with that name). +Returns the type of the pushed value. @@ -6167,7 +6433,7 @@ and false if it creates a new table.


    luaL_gsub

    -[-0, +1, e] +[-0, +1, m]

    const char *luaL_gsub (lua_State *L,
                            const char *s,
                            const char *p,
    @@ -6185,13 +6451,13 @@ Pushes the resulting string on the stack and returns it.
     
     

    luaL_len

    [-0, +0, e] -

    int luaL_len (lua_State *L, int index);
    +
    lua_Integer luaL_len (lua_State *L, int index);

    Returns the "length" of the value at the given index as a number; -it is equivalent to the '#' operator in Lua (see §3.4.6). -Raises an error if the result of the operation is not a number. +it is equivalent to the '#' operator in Lua (see §3.4.7). +Raises an error if the result of the operation is not an integer. (This case only can happen through metamethods.) @@ -6237,7 +6503,7 @@ The string mode works as in function lua_


    luaL_loadfile

    -[-0, +1, e] +[-0, +1, m]

    int luaL_loadfile (lua_State *L, const char *filename);

    @@ -6248,7 +6514,7 @@ Equivalent to luaL_loadfilex with

    luaL_loadfilex

    -[-0, +1, e] +[-0, +1, m]

    int luaL_loadfilex (lua_State *L, const char *filename,
                                                 const char *mode);
    @@ -6302,23 +6568,29 @@ it does not run it.

    luaL_newlib

    -[-0, +1, e] -

    void luaL_newlib (lua_State *L, const luaL_Reg *l);
    +[-0, +1, m] +
    void luaL_newlib (lua_State *L, const luaL_Reg l[]);

    Creates a new table and registers there the functions in list l. + + +

    It is implemented as the following macro:

          (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
    -
    +

    +The array l must be the actual array, +not a pointer to it. +


    luaL_newlibtable

    -[-0, +1, e] +[-0, +1, m]

    void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);

    @@ -6339,7 +6611,7 @@ not a pointer to it.


    luaL_newmetatable

    -[-0, +1, e] +[-0, +1, m]

    int luaL_newmetatable (lua_State *L, const char *tname);

    @@ -6347,8 +6619,10 @@ If the registry already has the key tname, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, -adds it to the registry with key tname, +adds to this new table the pair __name = tname, +adds to the registry the pair [tname] = new table, and returns 1. +(The entry __name is used by some error-reporting functions.)

    @@ -6391,16 +6665,22 @@ Opens all standard Lua libraries into the given state. -


    luaL_optint

    -[-0, +0, v] -

    int luaL_optint (lua_State *L, int arg, int d);
    +

    luaL_opt

    +[-0, +0, e] +

    T luaL_opt (L, func, arg, dflt);

    -If the function argument arg is a number, -returns this number cast to an int. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. +This macro is defined as follows: + +

    +     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
    +

    +In words, if the argument arg is nil or absent, +the macro results in the default dflt. +Otherwise, it results in the result of calling func +with the state L and the argument index arg as +parameters. +Note that it evaluates the expression dflt only if needed. @@ -6413,23 +6693,9 @@ Otherwise, raises an error. lua_Integer d);

    -If the function argument arg is a number, -returns this number cast to a lua_Integer. -If this argument is absent or is nil, -returns d. -Otherwise, raises an error. - - - - - -


    luaL_optlong

    -[-0, +0, v] -

    long luaL_optlong (lua_State *L, int arg, long d);
    - -

    -If the function argument arg is a number, -returns this number cast to a long. +If the function argument arg is an integer +(or convertible to an integer), +returns this integer. If this argument is absent or is nil, returns d. Otherwise, raises an error. @@ -6456,6 +6722,9 @@ Otherwise, raises an error.

    If l is not NULL, fills the position *l with the result's length. +If the result is NULL +(only possible when returning d and d == NULL), +its length is considered zero. @@ -6493,25 +6762,8 @@ Otherwise, raises an error. -


    luaL_optunsigned

    -[-0, +0, v] -

    lua_Unsigned luaL_optunsigned (lua_State *L,
    -                               int arg,
    -                               lua_Unsigned u);
    - -

    -If the function argument arg is a number, -returns this number cast to a lua_Unsigned. -If this argument is absent or is nil, -returns u. -Otherwise, raises an error. - - - - -


    luaL_prepbuffer

    -[-?, +?, e] +[-?, +?, m]

    char *luaL_prepbuffer (luaL_Buffer *B);

    @@ -6523,7 +6775,7 @@ with the predefined size LUAL_BUFFERSIZE

    luaL_prepbuffsize

    -[-?, +?, e] +[-?, +?, m]

    char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);

    @@ -6539,7 +6791,7 @@ it to the buffer.


    luaL_pushresult

    -[-?, +1, e] +[-?, +1, m]

    void luaL_pushresult (luaL_Buffer *B);

    @@ -6551,7 +6803,7 @@ the top of the stack.


    luaL_pushresultsize

    -[-?, +1, e] +[-?, +1, m]

    void luaL_pushresultsize (luaL_Buffer *B, size_t sz);

    @@ -6562,7 +6814,7 @@ Equivalent to the sequence luaL_addsize


    luaL_ref

    -[-1, +0, e] +[-1, +0, m]

    int luaL_ref (lua_State *L, int t);

    @@ -6601,7 +6853,7 @@ Type for arrays of functions to be registered by luaL_setfuncs. name is the function name and func is a pointer to the function. -Any array of luaL_Reg must end with an sentinel entry +Any array of luaL_Reg must end with a sentinel entry in which both name and func are NULL. @@ -6614,25 +6866,26 @@ in which both name and func are NULL. lua_CFunction openf, int glb);

    -Calls function openf with string modname as an argument +If modname is not already present in package.loaded, +calls function openf with string modname as an argument and sets the call result in package.loaded[modname], as if that function has been called through require.

    If glb is true, -also stores the result into global modname. +also stores the module into global modname.

    -Leaves a copy of that result on the stack. +Leaves a copy of the module on the stack.


    luaL_setfuncs

    -[-nup, +0, e] +[-nup, +0, m]

    void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);

    @@ -6665,14 +6918,52 @@ in the registry (see luaL_newmetatable +


    luaL_Stream

    +
    typedef struct luaL_Stream {
    +  FILE *f;
    +  lua_CFunction closef;
    +} luaL_Stream;
    + +

    +The standard representation for file handles, +which is used by the standard I/O library. + + +

    +A file handle is implemented as a full userdata, +with a metatable called LUA_FILEHANDLE +(where LUA_FILEHANDLE is a macro with the actual metatable's name). +The metatable is created by the I/O library +(see luaL_newmetatable). + + +

    +This userdata must start with the structure luaL_Stream; +it can contain other data after this initial structure. +Field f points to the corresponding C stream +(or it can be NULL to indicate an incompletely created handle). +Field closef points to a Lua function +that will be called to close the stream +when the handle is closed or collected; +this function receives the file handle as its sole argument and +must return either true (in case of success) +or nil plus an error message (in case of error). +Once Lua calls this field, +it changes the field value to NULL +to signal that the handle is closed. + + + + +


    luaL_testudata

    -[-0, +0, e] +[-0, +0, m]

    void *luaL_testudata (lua_State *L, int arg, const char *tname);

    This function works like luaL_checkudata, except that, when the test fails, -it returns NULL instead of throwing an error. +it returns NULL instead of raising an error. @@ -6692,7 +6983,7 @@ the function also sets *len with the string length.

    -If the value has a metatable with a "__tostring" field, +If the value has a metatable with a __tostring field, then luaL_tolstring calls the corresponding metamethod with the value as argument, and uses the result of the call as its result. @@ -6702,7 +6993,7 @@ and uses the result of the call as its result.


    luaL_traceback

    -[-0, +1, e] +[-0, +1, m]

    void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
                          int level);
    @@ -6749,7 +7040,7 @@ If ref is LUA_NOREF or

    luaL_where

    -[-0, +1, e] +[-0, +1, m]

    void luaL_where (lua_State *L, int lvl);

    @@ -6802,11 +7093,11 @@ Currently, Lua has the following standard libraries:

  • string manipulation (§6.4);
  • -
  • table manipulation (§6.5);
  • +
  • basic UTF-8 support (§6.5);
  • -
  • mathematical functions (§6.6) (sin, log, etc.);
  • +
  • table manipulation (§6.6);
  • -
  • bitwise operations (§6.7);
  • +
  • mathematical functions (§6.7) (sin, log, etc.);
  • input and output (§6.8);
  • @@ -6831,11 +7122,11 @@ the host program can open them individually by using luaopen_package (for the package library), luaopen_coroutine (for the coroutine library), luaopen_string (for the string library), +luaopen_utf8 (for the UTF8 library), luaopen_table (for the table library), luaopen_math (for the mathematical library), -luaopen_bit32 (for the bit library), luaopen_io (for the I/O library), -luaopen_os (for the Operating System library), +luaopen_os (for the operating system library), and luaopen_debug (for the debug library). These functions are declared in lualib.h. @@ -6852,11 +7143,15 @@ implementations for some of its facilities.


    assert (v [, message])

    -Issues an error when + + +

    +Calls error if the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. -message is an error message; -when absent, it defaults to "assertion failed!" +In case of error, +message is the error object; +when absent, it defaults to "assertion failed!" @@ -6887,25 +7182,21 @@ restarts automatic execution of the garbage collector.

  • "count": -returns the total memory in use by Lua (in Kbytes) and -a second value with the total memory in bytes modulo 1024. -The first value has a fractional part, -so the following equality is always true: - -
    -     k, b = collectgarbage("count")
    -     assert(k*1024 == math.floor(k)*1024 + b)
    -

    -(The second result is useful when Lua is compiled -with a non floating-point type for numbers.) +returns the total memory in use by Lua in Kbytes. +The value has a fractional part, +so that it multiplied by 1024 +gives the exact number of bytes in use by Lua +(except for overflows).

  • "step": performs a garbage-collection step. -The step "size" is controlled by arg -(larger values mean more steps) in a non-specified way. -If you want to control the step size -you must experimentally tune the value of arg. +The step "size" is controlled by arg. +With a zero value, +the collector will perform one basic (indivisible) step. +For non-zero values, +the collector will perform as if that amount of memory +(in KBytes) had been allocated by Lua. Returns true if the step finished a collection cycle.
  • @@ -6926,16 +7217,6 @@ returns a boolean that tells whether the collector is running (i.e., not stopped). -
  • "generational": -changes the collector to generational mode. -This is an experimental feature (see §2.5). -
  • - -
  • "incremental": -changes the collector to incremental mode. -This is the default mode. -
  • - @@ -6955,7 +7236,7 @@ to its caller (that is, dofile does not run in protected mode).


    error (message [, level])

    Terminates the last protected function called -and returns message as the error message. +and returns message as the error object. Function error never returns. @@ -6979,7 +7260,7 @@ A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, -nor vice-versa. +nor vice versa. @@ -6991,7 +7272,7 @@ nor vice-versa.

    If object does not have a metatable, returns nil. Otherwise, -if the object's metatable has a "__metatable" field, +if the object's metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object. @@ -7003,27 +7284,21 @@ Otherwise, returns the metatable of the given object.

    -If t has a metamethod __ipairs, -calls it with t as argument and returns the first three -results from the call. - - -

    -Otherwise, -returns three values: an iterator function, the table t, and 0, +Returns three values (an iterator function, the table t, and 0) so that the construction

          for i,v in ipairs(t) do body end
     

    -will iterate over the pairs (1,t[1]), (2,t[2]), ..., -up to the first integer key absent from the table. +will iterate over the key–value pairs +(1,t[1]), (2,t[2]), ..., +up to the first nil value.

    -


    load (ld [, source [, mode [, env]]])

    +

    load (chunk [, chunkname [, mode [, env]]])

    @@ -7031,10 +7306,10 @@ Loads a chunk.

    -If ld is a string, the chunk is this string. -If ld is a function, +If chunk is a string, the chunk is this string. +If chunk is a function, load calls it repeatedly to get the chunk pieces. -Each call to ld must return a string that concatenates +Each call to chunk must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk. @@ -7050,18 +7325,22 @@ If the resulting function has upvalues, the first upvalue is set to the value of env, if that parameter is given, or to the value of the global environment. +Other upvalues are initialized with nil. (When you load a main chunk, the resulting function will always have exactly one upvalue, the _ENV variable (see §2.2). -When you load a binary chunk created from a function (see string.dump), -the resulting function can have arbitrary upvalues.) +However, +when you load a binary chunk created from a function (see string.dump), +the resulting function can have an arbitrary number of upvalues.) +All upvalues are fresh, that is, +they are not shared with any other function.

    -source is used as the source of the chunk for error messages +chunkname is used as the name of the chunk for error messages and debug information (see §4.9). When absent, -it defaults to ld, if ld is a string, +it defaults to chunk, if chunk is a string, or to "=(load)" otherwise. @@ -7074,6 +7353,12 @@ or "bt" (both binary and text). The default is "bt". +

    +Lua does not check the consistency of binary chunks. +Maliciously crafted binary chunks can crash +the interpreter. + +

    @@ -7113,7 +7398,7 @@ you can use next(t) to check whether a table is empty.

    The order in which the indices are enumerated is not specified, even for numeric indices. -(To traverse a table in numeric order, +(To traverse a table in numerical order, use a numerical for.) @@ -7191,7 +7476,7 @@ use string.format and rawequal (v1, v2) Checks whether v1 is equal to v2, -without invoking any metamethod. +without invoking the __eq metamethod. Returns a boolean. @@ -7200,7 +7485,7 @@ Returns a boolean.


    rawget (table, index)

    Gets the real value of table[index], -without invoking any metamethod. +without invoking the __index metamethod. table must be a table; index may be any value. @@ -7211,8 +7496,8 @@ without invoking any metamethod.

    rawlen (v)

    Returns the length of the object v, which must be a table or a string, -without invoking any metamethod. -Returns an integer number. +without invoking the __len metamethod. +Returns an integer. @@ -7220,7 +7505,7 @@ Returns an integer number.


    rawset (table, index, value)

    Sets the real value of table[index] to value, -without invoking any metamethod. +without invoking the __newindex metamethod. table must be a table, index any value different from nil and NaN, and value any Lua value. @@ -7252,10 +7537,11 @@ and select returns the total number of extra arguments it received.

    Sets the metatable for the given table. -(You cannot change the metatable of other types from Lua, only from C.) +(To change the metatable of other types from Lua code, +you must use the debug library (§6.10).) If metatable is nil, removes the metatable of the given table. -If the original metatable has a "__metatable" field, +If the original metatable has a __metatable field, raises an error. @@ -7273,14 +7559,20 @@ This function returns table. When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or -a string convertible to a number (see §3.4.2), +a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.

    +The conversion of strings can result in integers or floats, +according to the lexical conventions of Lua (see §3.1). +(The string may have leading and trailing spaces and a sign.) + + +

    When called with base, -then e should be a string to be interpreted as +then e must be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) @@ -7295,13 +7587,13 @@ the function returns nil.


    tostring (v)

    Receives a value of any type and -converts it to a string in a reasonable format. +converts it to a string in a human-readable format. (For complete control of how numbers are converted, use string.format.)

    -If the metatable of v has a "__tostring" field, +If the metatable of v has a __tostring field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result. @@ -7327,9 +7619,12 @@ and "userdata".


    _VERSION

    + + +

    A global variable (not a function) that -holds a string containing the current interpreter version. -The current contents of this variable is "Lua 5.2". +holds a string containing the running Lua version. +The current value of this variable is "Lua 5.3". @@ -7351,8 +7646,8 @@ except that it sets a new message handler msgh.

    6.2 – Coroutine Manipulation

    -The operations related to coroutines comprise a sub-library of -the basic library and come inside the table coroutine. +This library comprises the operations to manipulate coroutines, +which come inside the table coroutine. See §2.6 for a general description of coroutines. @@ -7362,7 +7657,7 @@ See §2.6 for a general description of coroutines.

    Creates a new coroutine, with body f. -f must be a Lua function. +f must be a function. Returns this new coroutine, an object with type "thread". @@ -7370,6 +7665,21 @@ an object with type "thread".

    +


    coroutine.isyieldable ()

    + + +

    +Returns true when the running coroutine can yield. + + +

    +A running coroutine is yieldable if it is not the main thread and +it is not inside a non-yieldable C function. + + + + +


    coroutine.resume (co [, val1, ···])

    @@ -7388,8 +7698,8 @@ as the results from the yield.

    If the coroutine runs without any errors, resume returns true plus any values passed to yield -(if the coroutine yields) or any values returned by the body function -(if the coroutine terminates). +(when the coroutine yields) or any values returned by the body function +(when the coroutine terminates). If there is any error, resume returns false plus the error message. @@ -7431,7 +7741,7 @@ or if it has stopped with an error.

    Creates a new coroutine, with body f. -f must be a Lua function. +f must be a function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to resume. @@ -7491,7 +7801,7 @@ for package.searchers.

    First require queries package.preload[modname]. If it has a value, -this value (which should be a function) is the loader. +this value (which must be a function) is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it searches for a C loader using the @@ -7547,7 +7857,7 @@ Default is '?'. is replaced by the executable's directory. Default is '!'. -

  • The fifth line is a mark to ignore all text before it +
  • The fifth line is a mark to ignore all text after it when building the luaopen_ function name. Default is '-'.
  • @@ -7566,7 +7876,7 @@ The path used by require to search for a

    Lua initializes the C path package.cpath in the same way it initializes the Lua path package.path, -using the environment variable LUA_CPATH_5_2 +using the environment variable LUA_CPATH_5_3 or the environment variable LUA_CPATH or a default path defined in luaconf.h. @@ -7644,7 +7954,7 @@ The path used by require to search for a

    At start-up, Lua initializes this variable with -the value of the environment variable LUA_PATH_5_2 or +the value of the environment variable LUA_PATH_5_3 or the environment variable LUA_PATH or with a default path defined in luaconf.h, if those environment variables are not defined. @@ -7729,9 +8039,9 @@ The name of this C function is the string "luaopen_" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, -its prefix up to (and including) the first hyphen is removed. -For instance, if the module name is a.v1-b.c, -the function name will be luaopen_b_c. +its suffix after (and including) the first hyphen is removed. +For instance, if the module name is a.b.c-v2.1, +the function name will be luaopen_a_b_c.

    @@ -7830,7 +8140,7 @@ The string library assumes one-byte character encodings.


    string.byte (s [, i [, j]])

    -Returns the internal numerical codes of the characters s[i], +Returns the internal numeric codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i. @@ -7839,7 +8149,7 @@ following the same rules of function string.sub<

    -Numerical codes are not necessarily portable across platforms. +Numeric codes are not necessarily portable across platforms. @@ -7848,24 +8158,39 @@ Numerical codes are not necessarily portable across platforms.


    string.char (···)

    Receives zero or more integers. Returns a string with length equal to the number of arguments, -in which each character has the internal numerical code equal +in which each character has the internal numeric code equal to its corresponding argument.

    -Numerical codes are not necessarily portable across platforms. +Numeric codes are not necessarily portable across platforms.

    -


    string.dump (function)

    +

    string.dump (function [, strip])

    -Returns a string containing a binary representation of the given function, +Returns a string containing a binary representation +(a binary chunk) +of the given function, so that a later load on this string returns a copy of the function (but with new upvalues). +If strip is a true value, +the binary representation may not include all debug information +about the function, +to save space. + + +

    +Functions with upvalues have only their number of upvalues saved. +When (re)loaded, +those upvalues receive fresh instances containing nil. +(You can use the debug library to serialize +and reload the upvalues of a function +in a way adequate to your needs.) @@ -7876,11 +8201,11 @@ a copy of the function (but with new upvalues).

    Looks for the first match of -pattern in the string s. +pattern (see §6.4.1) in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. -A third, optional numerical argument init specifies +A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain @@ -7911,6 +8236,9 @@ The only differences are that the options/modifiers *, h, L, l, n, and p are not supported and that there is an extra option, q. + + +

    The q option formats a string between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. @@ -7928,20 +8256,22 @@ may produce the string:

    Options -A and a (when available), -E, e, f, +A, a, E, e, f, G, and g all expect a number as argument. Options c, d, i, o, u, X, and x -also expect a number, -but the range of that number may be limited by -the underlying C implementation. -For options o, u, X, and x, -the number cannot be negative. -Option q expects a string; -option s expects a string without embedded zeros. -If the argument to option s is not a string, +expect an integer. +When Lua is compiled with a C89 compiler, +options A and a (hexadecimal floats) +do not support any modifier (flags, width, length). + + +

    +Option s expects a string; +if its argument is not a string, it is converted to one following the same rules of tostring. +If the option has any modifier (flags, width, length), +the string argument should not contain embedded zeros. @@ -7950,7 +8280,8 @@ it is converted to one following the same rules of

    string.gmatch (s, pattern)

    Returns an iterator function that, each time it is called, -returns the next captures from pattern over the string s. +returns the next captures from pattern (see §6.4.1) +over the string s. If pattern specifies no captures, then the whole match is produced in each call. @@ -7988,7 +8319,7 @@ work as an anchor, as this would prevent the iteration.

    string.gsub (s, pattern, repl [, n])

    Returns a copy of s in which all (or the first n, if given) -occurrences of the pattern have been +occurrences of the pattern (see §6.4.1) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, @@ -8053,9 +8384,9 @@ Here are some examples: end) --> x="4+5 = 9" - local t = {name="lua", version="5.2"} + local t = {name="lua", version="5.3"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) - --> x="lua-5.2.tar.gz" + --> x="lua-5.3.tar.gz" @@ -8083,13 +8414,13 @@ The definition of what an uppercase letter is depends on the current locale.


    string.match (s, pattern [, init])

    Looks for the first match of -pattern in the string s. +pattern (see §6.4.1) in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. -A third, optional numerical argument init specifies +A third, optional numeric argument init specifies where to start the search; its default value is 1 and can be negative. @@ -8097,11 +8428,42 @@ its default value is 1 and can be negative.

    +


    string.pack (fmt, v1, v2, ···)

    + + +

    +Returns a binary string containing the values v1, v2, etc. +packed (that is, serialized in binary form) +according to the format string fmt (see §6.4.2). + + + + +

    +


    string.packsize (fmt)

    + + +

    +Returns the size of a string resulting from string.pack +with the given format. +The format string cannot have the variable-length options +'s' or 'z' (see §6.4.2). + + + + +


    string.rep (s, n [, sep])

    Returns a string that is the concatenation of n copies of the string s separated by the string sep. The default value for sep is the empty string (that is, no separator). +Returns the empty string if n is not positive. + + +

    +(Note that it is very easy to exhaust the memory of your machine +with a single call to this function.) @@ -8141,6 +8503,21 @@ the function returns the empty string.

    +


    string.unpack (fmt, s [, pos])

    + + +

    +Returns the values packed in string s (see string.pack) +according to the format string fmt (see §6.4.2). +An optional pos marks where +to start reading in s (default is 1). +After the read values, +this function also returns the index of the first unread byte in s. + + + + +


    string.upper (s)

    Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. @@ -8149,8 +8526,21 @@ The definition of what a lowercase letter is depends on the current locale. + +

    6.4.1 – Patterns

    +

    +Patterns in Lua are described by regular strings, +which are interpreted as patterns by the pattern-matching functions +string.find, +string.gmatch, +string.gsub, +and string.match. +This section describes the syntax and the meaning +(that is, what they match) of these strings. + +

    Character Class:

    A character class is used to represent a set of characters. @@ -8189,7 +8579,8 @@ represents the character x itself.

  • %x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. -Any punctuation character (even the non magic) +Any non-alphanumeric character +(including all punctuation characters, even the non-magical) can be preceded by a '%' when used to represent itself in a pattern.
  • @@ -8199,7 +8590,7 @@ represents the class which is the union of all characters in set. A range of characters can be specified by separating the end characters of the range, -in ascending order, with a '-', +in ascending order, with a '-'. All classes %x described above can also be used as components in set. All other characters in set represent themselves. @@ -8211,6 +8602,14 @@ the lowercase letters plus the '-' character.

    +You can put a closing square bracket in a set +by positioning it as the first character in the set. +You can put an hyphen in a set +by positioning it as the first or the last character in the set. +(You can also use an escape for both cases.) + + +

    The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning. @@ -8248,26 +8647,27 @@ which matches any single character in the class;

  • a single character class followed by '*', -which matches 0 or more repetitions of characters in the class. +which matches zero or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '+', -which matches 1 or more repetitions of characters in the class. +which matches one or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '-', -which also matches 0 or more repetitions of characters in the class. +which also matches zero or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;
  • a single character class followed by '?', -which matches 0 or 1 occurrence of a character in the class; +which matches zero or one occurrence of a character in the class. +It always matches one occurrence if possible;
  • @@ -8340,688 +8740,669 @@ string "flaaap", there will be two captures: 3 and 5. +

    6.4.2 – Format Strings for Pack and Unpack

    +

    +The first argument to string.pack, +string.packsize, and string.unpack +is a format string, +which describes the layout of the structure being created or read. - -

    6.5 – Table Manipulation

    -

    -This library provides generic functions for table manipulation. -It provides all its functions inside the table table. +A format string is a sequence of conversion options. +The conversion options are as follows: + +

      +
    • <: sets little endian
    • +
    • >: sets big endian
    • +
    • =: sets native endian
    • +
    • ![n]: sets maximum alignment to n +(default is native alignment)
    • +
    • b: a signed byte (char)
    • +
    • B: an unsigned byte (char)
    • +
    • h: a signed short (native size)
    • +
    • H: an unsigned short (native size)
    • +
    • l: a signed long (native size)
    • +
    • L: an unsigned long (native size)
    • +
    • j: a lua_Integer
    • +
    • J: a lua_Unsigned
    • +
    • T: a size_t (native size)
    • +
    • i[n]: a signed int with n bytes +(default is native size)
    • +
    • I[n]: an unsigned int with n bytes +(default is native size)
    • +
    • f: a float (native size)
    • +
    • d: a double (native size)
    • +
    • n: a lua_Number
    • +
    • cn: a fixed-sized string with n bytes
    • +
    • z: a zero-terminated string
    • +
    • s[n]: a string preceded by its length +coded as an unsigned integer with n bytes +(default is a size_t)
    • +
    • x: one byte of padding
    • +
    • Xop: an empty item that aligns +according to option op +(which is otherwise ignored)
    • +
    • ' ': (empty space) ignored
    • +

    +(A "[n]" means an optional integral numeral.) +Except for padding, spaces, and configurations +(options "xX <=>!"), +each option corresponds to an argument (in string.pack) +or a result (in string.unpack).

    -Remember that, whenever an operation needs the length of a table, -the table should be a proper sequence -or have a __len metamethod (see §3.4.6). -All functions ignore non-numeric keys -in tables given as arguments. +For options "!n", "sn", "in", and "In", +n can be any integer between 1 and 16. +All integral options check overflows; +string.pack checks whether the given value fits in the given size; +string.unpack checks whether the read value fits in a Lua integer.

    -For performance reasons, -all table accesses (get/set) performed by these functions are raw. +Any format string starts as if prefixed by "!1=", +that is, +with maximum alignment of 1 (no alignment) +and native endianness.

    -


    table.concat (list [, sep [, i [, j]]])

    +Alignment works as follows: +For each option, +the format gets extra padding until the data starts +at an offset that is a multiple of the minimum between the +option size and the maximum alignment; +this minimum must be a power of 2. +Options "c" and "z" are not aligned; +option "s" follows the alignment of its starting integer.

    -Given a list where all elements are strings or numbers, -returns the string list[i]..sep..list[i+1] ··· sep..list[j]. -The default value for sep is the empty string, -the default for i is 1, -and the default for j is #list. -If i is greater than j, returns the empty string. +All padding is filled with zeros by string.pack +(and ignored by string.unpack). -

    -


    table.insert (list, [pos,] value)

    -

    -Inserts element value at position pos in list, -shifting up the elements -list[pos], list[pos+1], ···, list[#list]. -The default value for pos is #list+1, -so that a call table.insert(t,x) inserts x at the end -of list t. +

    6.5 – UTF-8 Support

    +

    +This library provides basic support for UTF-8 encoding. +It provides all its functions inside the table utf8. +This library does not provide any support for Unicode other +than the handling of the encoding. +Any operation that needs the meaning of a character, +such as character classification, is outside its scope.

    -


    table.pack (···)

    +Unless stated otherwise, +all functions that expect a byte position as a parameter +assume that the given position is either the start of a byte sequence +or one plus the length of the subject string. +As in the string library, +negative indices count from the end of the string.

    -Returns a new table with all parameters stored into keys 1, 2, etc. -and with a field "n" with the total number of parameters. -Note that the resulting table may not be a sequence. +


    utf8.char (···)

    +Receives zero or more integers, +converts each one to its corresponding UTF-8 byte sequence +and returns a string with the concatenation of all these sequences.

    -


    table.remove (list [, pos])

    +

    utf8.charpattern

    +The pattern (a string, not a function) "[\0-\x7F\xC2-\xF4][\x80-\xBF]*" +(see §6.4.1), +which matches exactly one UTF-8 byte sequence, +assuming that the subject is a valid UTF-8 string. + +

    -Removes from list the element at position pos, -returning the value of the removed element. -When pos is an integer between 1 and #list, -it shifts down the elements -list[pos+1], list[pos+2], ···, list[#list] -and erases element list[#list]; -The index pos can also be 0 when #list is 0, -or #list + 1; -in those cases, the function erases the element list[pos]. +


    utf8.codes (s)

    -The default value for pos is #list, -so that a call table.remove(t) removes the last element -of list t. +Returns values so that the construction + +

    +     for p, c in utf8.codes(s) do body end
    +

    +will iterate over all characters in string s, +with p being the position (in bytes) and c the code point +of each character. +It raises an error if it meets any invalid byte sequence.

    -


    table.sort (list [, comp])

    +

    utf8.codepoint (s [, i [, j]])

    +Returns the codepoints (as integers) from all characters in s +that start between byte position i and j (both included). +The default for i is 1 and for j is i. +It raises an error if it meets any invalid byte sequence. -

    -Sorts list elements in a given order, in-place, -from list[1] to list[#list]. -If comp is given, -then it must be a function that receives two list elements -and returns true when the first element must come -before the second in the final order -(so that not comp(list[i+1],list[i]) will be true after the sort). -If comp is not given, -then the standard Lua operator < is used instead.

    -The sort algorithm is not stable; -that is, elements considered equal by the given order -may have their relative positions changed by the sort. +


    utf8.len (s [, i [, j]])

    +Returns the number of UTF-8 characters in string s +that start between positions i and j (both inclusive). +The default for i is 1 and for j is -1. +If it finds any invalid byte sequence, +returns a false value plus the position of the first invalid byte.

    -


    table.unpack (list [, i [, j]])

    +

    utf8.offset (s, n [, i])

    +Returns the position (in bytes) where the encoding of the +n-th character of s +(counting from position i) starts. +A negative n gets characters before position i. +The default for i is 1 when n is non-negative +and #s + 1 otherwise, +so that utf8.offset(s, -n) gets the offset of the +n-th character from the end of the string. +If the specified character is neither in the subject +nor right after its end, +the function returns nil.

    -Returns the elements from the given table. -This function is equivalent to +As a special case, +when n is 0 the function returns the start of the encoding +of the character that contains the i-th byte of s. -

    -     return list[i], list[i+1], ···, list[j]
    -

    -By default, i is 1 and j is #list. - - - - - - - -

    6.6 – Mathematical Functions

    -This library is an interface to the standard C math library. -It provides all its functions inside the table math. +This function assumes that s is a valid UTF-8 string. -

    -


    math.abs (x)

    -

    -Returns the absolute value of x. +

    6.6 – Table Manipulation

    -


    math.acos (x)

    +This library provides generic functions for table manipulation. +It provides all its functions inside the table table.

    -Returns the arc cosine of x (in radians). - - +Remember that, whenever an operation needs the length of a table, +the table must be a proper sequence +or have a __len metamethod (see §3.4.7). +All functions ignore non-numeric keys +in the tables given as arguments.

    -


    math.asin (x)

    +

    table.concat (list [, sep [, i [, j]]])

    -Returns the arc sine of x (in radians). +Given a list where all elements are strings or numbers, +returns the string list[i]..sep..list[i+1] ··· sep..list[j]. +The default value for sep is the empty string, +the default for i is 1, +and the default for j is #list. +If i is greater than j, returns the empty string.

    -


    math.atan (x)

    +

    table.insert (list, [pos,] value)

    -Returns the arc tangent of x (in radians). +Inserts element value at position pos in list, +shifting up the elements +list[pos], list[pos+1], ···, list[#list]. +The default value for pos is #list+1, +so that a call table.insert(t,x) inserts x at the end +of list t.

    -


    math.atan2 (y, x)

    +

    table.move (a1, f, e, t [,a2])

    -Returns the arc tangent of y/x (in radians), -but uses the signs of both parameters to find the -quadrant of the result. -(It also handles correctly the case of x being zero.) - - +Moves elements from table a1 to table a2, +performing the equivalent to the following +multiple assignment: +a2[t],··· = a1[f],···,a1[e]. +The default for a2 is a1. +The destination range can overlap with the source range. +The number of elements to be moved must fit in a Lua integer.

    -


    math.ceil (x)

    - - -

    -Returns the smallest integer larger than or equal to x. +Returns the destination table a2.

    -


    math.cos (x)

    +

    table.pack (···)

    -Returns the cosine of x (assumed to be in radians). - - +Returns a new table with all parameters stored into keys 1, 2, etc. +and with a field "n" with the total number of parameters. +Note that the resulting table may not be a sequence. -

    -


    math.cosh (x)

    -Returns the hyperbolic cosine of x. - - +


    table.remove (list [, pos])

    -


    math.deg (x)

    +Removes from list the element at position pos, +returning the value of the removed element. +When pos is an integer between 1 and #list, +it shifts down the elements +list[pos+1], list[pos+2], ···, list[#list] +and erases element list[#list]; +The index pos can also be 0 when #list is 0, +or #list + 1; +in those cases, the function erases the element list[pos].

    -Returns the angle x (given in radians) in degrees. +The default value for pos is #list, +so that a call table.remove(l) removes the last element +of list l.

    -


    math.exp (x)

    +

    table.sort (list [, comp])

    -Returns the value ex. - - +Sorts list elements in a given order, in-place, +from list[1] to list[#list]. +If comp is given, +then it must be a function that receives two list elements +and returns true when the first element must come +before the second in the final order +(so that, after the sort, +i < j implies not comp(list[j],list[i])). +If comp is not given, +then the standard Lua operator < is used instead.

    -


    math.floor (x)

    +Note that the comp function must define +a strict partial order over the elements in the list; +that is, it must be asymmetric and transitive. +Otherwise, no valid sort may be possible.

    -Returns the largest integer smaller than or equal to x. +The sort algorithm is not stable; +that is, elements not comparable by the given order +(e.g., equal elements) +may have their relative positions changed by the sort.

    -


    math.fmod (x, y)

    +

    table.unpack (list [, i [, j]])

    -Returns the remainder of the division of x by y -that rounds the quotient towards zero. - - - +Returns the elements from the given list. +This function is equivalent to -

    -


    math.frexp (x)

    +
    +     return list[i], list[i+1], ···, list[j]
    +

    +By default, i is 1 and j is #list. -

    -Returns m and e such that x = m2e, -e is an integer and the absolute value of m is -in the range [0.5, 1) -(or zero when x is zero). -

    -


    math.huge

    +

    6.7 – Mathematical Functions

    -The value HUGE_VAL, -a value larger than or equal to any other numerical value. - - +This library provides basic mathematical functions. +It provides all its functions and constants inside the table math. +Functions with the annotation "integer/float" give +integer results for integer arguments +and float results for float (or mixed) arguments. +Rounding functions +(math.ceil, math.floor, and math.modf) +return an integer when the result fits in the range of an integer, +or a float otherwise.

    -


    math.ldexp (m, e)

    +

    math.abs (x)

    -Returns m2e (e should be an integer). +Returns the absolute value of x. (integer/float)

    -


    math.log (x [, base])

    +

    math.acos (x)

    -Returns the logarithm of x in the given base. -The default for base is e -(so that the function returns the natural logarithm of x). +Returns the arc cosine of x (in radians).

    -


    math.max (x, ···)

    +

    math.asin (x)

    -Returns the maximum value among its arguments. +Returns the arc sine of x (in radians).

    -


    math.min (x, ···)

    +

    math.atan (y [, x])

    -Returns the minimum value among its arguments. - - - -

    -


    math.modf (x)

    +Returns the arc tangent of y/x (in radians), +but uses the signs of both parameters to find the +quadrant of the result. +(It also handles correctly the case of x being zero.)

    -Returns two numbers, -the integral part of x and the fractional part of x. +The default value for x is 1, +so that the call math.atan(y) +returns the arc tangent of y.

    -


    math.pi

    +

    math.ceil (x)

    -The value of π. +Returns the smallest integral value larger than or equal to x.

    -


    math.pow (x, y)

    +

    math.cos (x)

    -Returns xy. -(You can also use the expression x^y to compute this value.) +Returns the cosine of x (assumed to be in radians).

    -


    math.rad (x)

    +

    math.deg (x)

    -Returns the angle x (given in degrees) in radians. - +Converts the angle x from radians to degrees. -

    -


    math.random ([m [, n]])

    -

    -This function is an interface to the simple -pseudo-random generator function rand provided by Standard C. -(No guarantees can be given for its statistical properties.) +


    math.exp (x)

    -When called without arguments, -returns a uniform pseudo-random real number -in the range [0,1). -When called with an integer number m, -math.random returns -a uniform pseudo-random integer in the range [1, m]. -When called with two integer numbers m and n, -math.random returns a uniform pseudo-random -integer in the range [m, n]. +Returns the value ex +(where e is the base of natural logarithms).

    -


    math.randomseed (x)

    +

    math.floor (x)

    -Sets x as the "seed" -for the pseudo-random generator: -equal seeds produce equal sequences of numbers. +Returns the largest integral value smaller than or equal to x.

    -


    math.sin (x)

    +

    math.fmod (x, y)

    -Returns the sine of x (assumed to be in radians). +Returns the remainder of the division of x by y +that rounds the quotient towards zero. (integer/float)

    -


    math.sinh (x)

    +

    math.huge

    -Returns the hyperbolic sine of x. +The float value HUGE_VAL, +a value larger than any other numeric value.

    -


    math.sqrt (x)

    +

    math.log (x [, base])

    -Returns the square root of x. -(You can also use the expression x^0.5 to compute this value.) +Returns the logarithm of x in the given base. +The default for base is e +(so that the function returns the natural logarithm of x).

    -


    math.tan (x)

    +

    math.max (x, ···)

    -Returns the tangent of x (assumed to be in radians). - +Returns the argument with the maximum value, +according to the Lua operator <. (integer/float) -

    -


    math.tanh (x)

    -

    -Returns the hyperbolic tangent of x. +


    math.maxinteger

    +An integer with the maximum value for an integer. - - - -

    6.7 – Bitwise Operations

    -

    -This library provides bitwise operations. -It provides all its functions inside the table bit32. +


    math.min (x, ···)

    -Unless otherwise stated, -all functions accept numeric arguments in the range -(-251,+251); -each argument is normalized to -the remainder of its division by 232 -and truncated to an integer (in some unspecified way), -so that its final value falls in the range [0,232 - 1]. -Similarly, all results are in the range [0,232 - 1]. -Note that bit32.bnot(0) is 0xFFFFFFFF, -which is different from -1. +Returns the argument with the minimum value, +according to the Lua operator <. (integer/float) -

    -


    bit32.arshift (x, disp)

    -Returns the number x shifted disp bits to the right. -The number disp may be any representable integer. -Negative displacements shift to the left. - - -

    -This shift operation is what is called arithmetic shift. -Vacant bits on the left are filled -with copies of the higher bit of x; -vacant bits on the right are filled with zeros. -In particular, -displacements with absolute values higher than 31 -result in zero or 0xFFFFFFFF (all original bits are shifted out). +


    math.mininteger

    +An integer with the minimum value for an integer.

    -


    bit32.band (···)

    +

    math.modf (x)

    -Returns the bitwise and of its operands. +Returns the integral part of x and the fractional part of x. +Its second result is always a float.

    -


    bit32.bnot (x)

    +

    math.pi

    -Returns the bitwise negation of x. -For any integer x, -the following identity holds: +The value of π. -

    -     assert(bit32.bnot(x) == (-1 - x) % 2^32)
    -

    -


    bit32.bor (···)

    +

    math.rad (x)

    -Returns the bitwise or of its operands. - +Converts the angle x from degrees to radians. -

    -


    bit32.btest (···)

    -

    -Returns a boolean signaling -whether the bitwise and of its operands is different from zero. - - +


    math.random ([m [, n]])

    -


    bit32.bxor (···)

    +When called without arguments, +returns a pseudo-random float with uniform distribution +in the range [0,1). +When called with two integers m and n, +math.random returns a pseudo-random integer +with uniform distribution in the range [m, n]. +(The value n-m cannot be negative and must fit in a Lua integer.) +The call math.random(n) is equivalent to math.random(1,n).

    -Returns the bitwise exclusive or of its operands. - +This function is an interface to the underling +pseudo-random generator function provided by C. -

    -


    bit32.extract (n, field [, width])

    -

    -Returns the unsigned number formed by the bits -field to field + width - 1 from n. -Bits are numbered from 0 (least significant) to 31 (most significant). -All accessed bits must be in the range [0, 31]. +


    math.randomseed (x)

    -The default for width is 1. +Sets x as the "seed" +for the pseudo-random generator: +equal seeds produce equal sequences of numbers.

    -


    bit32.replace (n, v, field [, width])

    +

    math.sin (x)

    -Returns a copy of n with -the bits field to field + width - 1 -replaced by the value v. -See bit32.extract for details about field and width. - - +Returns the sine of x (assumed to be in radians). -

    -


    bit32.lrotate (x, disp)

    -Returns the number x rotated disp bits to the left. -The number disp may be any representable integer. +


    math.sqrt (x)

    -For any valid displacement, -the following identity holds: - -

    -     assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))
    -

    -In particular, -negative displacements rotate to the right. - - +Returns the square root of x. +(You can also use the expression x^0.5 to compute this value.) -

    -


    bit32.lshift (x, disp)

    -Returns the number x shifted disp bits to the left. -The number disp may be any representable integer. -Negative displacements shift to the right. -In any direction, vacant bits are filled with zeros. -In particular, -displacements with absolute values higher than 31 -result in zero (all bits are shifted out). +


    math.tan (x)

    -For positive displacements, -the following equality holds: +Returns the tangent of x (assumed to be in radians). -

    -     assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
    -

    -


    bit32.rrotate (x, disp)

    +

    math.tointeger (x)

    -Returns the number x rotated disp bits to the right. -The number disp may be any representable integer. - +If the value x is convertible to an integer, +returns that integer. +Otherwise, returns nil. -

    -For any valid displacement, -the following identity holds: -

    -     assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))
    -

    -In particular, -negative displacements rotate to the left. +

    +


    math.type (x)

    -


    bit32.rshift (x, disp)

    +Returns "integer" if x is an integer, +"float" if it is a float, +or nil if x is not a number. -

    -Returns the number x shifted disp bits to the right. -The number disp may be any representable integer. -Negative displacements shift to the left. -In any direction, vacant bits are filled with zeros. -In particular, -displacements with absolute values higher than 31 -result in zero (all bits are shifted out).

    -For positive displacements, -the following equality holds: +


    math.ult (m, n)

    -
    -     assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
    -

    -This shift operation is what is called logical shift. +Returns a boolean, +true if integer m is below integer n when +they are compared as unsigned integers. @@ -9033,24 +9414,24 @@ This shift operation is what is called logical shift.

    The I/O library provides two different styles for file manipulation. -The first one uses implicit file descriptors; +The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. -The second style uses explicit file descriptors. +The second style uses explicit file handles.

    -When using implicit file descriptors, +When using implicit file handles, all operations are supplied by table io. -When using explicit file descriptors, -the operation io.open returns a file descriptor -and then all operations are supplied as methods of the file descriptor. +When using explicit file handles, +the operation io.open returns a file handle +and then all operations are supplied as methods of the file handle.

    The table io also provides -three predefined file descriptors with their usual meanings from C: +three predefined file handles with their usual meanings from C: io.stdin, io.stdout, and io.stderr. The I/O library never closes these files. @@ -9061,7 +9442,7 @@ all I/O functions return nil on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from nil on success. -On non-Posix systems, +On non-POSIX systems, the computation of the error message and error code in case of errors may be not thread safe, @@ -9110,7 +9491,7 @@ instead of returning an error code.

    -


    io.lines ([filename ···])

    +

    io.lines ([filename, ···])

    @@ -9118,12 +9499,12 @@ Opens the given file name in read mode and returns an iterator function that works like file:lines(···) over the opened file. When the iterator function detects the end of file, -it returns nil (to finish the loop) and automatically closes the file. +it returns no values (to finish the loop) and automatically closes the file.

    The call io.lines() (with no file name) is equivalent -to io.input():lines(); +to io.input():lines("*l"); that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends. @@ -9142,8 +9523,8 @@ instead of returning an error code.

    This function opens a file, in the mode specified in the string mode. -It returns a new file handle, -or, in case of errors, nil plus an error message. +In case of success, +it returns a new file handle.

    @@ -9208,7 +9589,8 @@ Equivalent to io.input():read(···).

    -Returns a handle for a temporary file. +In case of success, +returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends. @@ -9276,7 +9658,7 @@ Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, -uses "*l" as a default. +uses "l" as a default. As an example, the construction

    @@ -9303,8 +9685,10 @@ instead of returning an error code.
     Reads the file file,
     according to the given formats, which specify what to read.
     For each format,
    -the function returns a string (or a number) with the characters read,
    +the function returns a string or a number with the characters read,
     or nil if it cannot read data with the specified format.
    +(In this latter case,
    +the function does not read subsequent formats.)
     When called without formats,
     it uses a default format that reads the next line
     (see below).
    @@ -9315,36 +9699,44 @@ The available formats are
     
     
      -
    • "*n": -reads a number; -this is the only format that returns a number instead of a string. +
    • "n": +reads a numeral and returns it as a float or an integer, +following the lexical conventions of Lua. +(The numeral may have leading spaces and a sign.) +This format always reads the longest input sequence that +is a valid prefix for a numeral; +if that prefix does not form a valid numeral +(e.g., an empty string, "0x", or "3.4e-"), +it is discarded and the function returns nil.
    • -
    • "*a": +
    • "a": reads the whole file, starting at the current position. On end of file, it returns the empty string.
    • -
    • "*l": +
    • "l": reads the next line skipping the end of line, returning nil on end of file. This is the default format.
    • -
    • "*L": -reads the next line keeping the end of line (if present), +
    • "L": +reads the next line keeping the end-of-line character (if present), returning nil on end of file.
    • number: reads a string with up to this number of bytes, returning nil on end of file. -If number is zero, +If number is zero, it reads nothing and returns an empty string, or nil on end of file.
    • -
    +

    +The formats "l" and "L" should be used only for text files. + @@ -9474,10 +9866,10 @@ then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following fields: -year (four digits), month (1–12), day (1–31), +year, month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61), -wday (weekday, Sunday is 1), -yday (day of the year), +wday (weekday, 1–7, Sunday is 1), +yday (day of the year, 1–366), and isdst (daylight saving flag, a boolean). This last field may be absent if the information is not available. @@ -9492,12 +9884,12 @@ formatted according to the same rules as the ISO C function strftime<

    When called without arguments, date returns a reasonable date and time representation that depends on -the host system and on the current locale -(that is, os.date() is equivalent to os.date("%c")). +the host system and on the current locale. +(More specifically, os.date() is equivalent to os.date("%c").)

    -On non-Posix systems, +On non-POSIX systems, this function may be not thread safe because of its reliance on C function gmtime and C function localtime. @@ -9509,7 +9901,9 @@ because of its reliance on C function gmtime and C functi

    -Returns the number of seconds from time t1 to time t2. +Returns the difference, in seconds, +from time t1 to time t2 +(where the times are values returned by os.time). In POSIX, Windows, and some other systems, this value is exactly t2-t1. @@ -9527,7 +9921,7 @@ Its first result is true if the command terminated successfully, or nil otherwise. After this first result -the function returns a string and a number, +the function returns a string plus a number, as follows:

      @@ -9552,7 +9946,7 @@ When called without a command,

      -


      os.exit ([code [, close])

      +

      os.exit ([code [, close]])

      @@ -9650,17 +10044,26 @@ because of its reliance on C function setlocale.

      Returns the current time when called without arguments, -or a time representing the date and time specified by the given table. +or a time representing the local date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). +Other fields are ignored. For a description of these fields, see the os.date function.

      +The values in these fields do not need to be inside their valid ranges. +For instance, if sec is -10, +it means -10 seconds from the time specified by the other fields; +if hour is 1000, +it means +1000 hours from the time specified by the other fields. + + +

      The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number @@ -9797,7 +10200,7 @@ valid lines.

      For instance, the expression debug.getinfo(1,"n").name returns -a table with a name for the current function, +a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information @@ -9819,7 +10222,9 @@ but also parameters, temporaries, etc.

      The first parameter or local variable has index 1, and so on, -until the last active variable. +following the order that they are declared in the code, +counting only the variables that are active +in the current scope of the function. Negative indices refer to vararg parameters; -1 is the first vararg parameter. The function returns nil if there is no variable with the given index, @@ -9828,9 +10233,10 @@ and raises an error when called with a level out of range.

      -Variable names starting with '(' (open parenthesis) -represent internal variables -(loop control variables, temporaries, varargs, and C function locals). +Variable names starting with '(' (open parenthesis) +represent variables with no known names +(internal variables such as loop control variables, +and variables from chunks saved without debug information).

      @@ -9871,6 +10277,12 @@ with index up of the function f. The function returns nil if there is no upvalue with the given index. +

      +Variable names starting with '(' (open parenthesis) +represent variables with no known names +(variables from chunks saved without debug information). + +

      @@ -9982,7 +10394,6 @@ Otherwise, it returns the name of the upvalue.

      Sets the given value as the Lua value associated to the given udata. -value must be a table or nil; udata must be a full userdata. @@ -10001,7 +10412,7 @@ If message is present but is neither a string nor nil, this function returns message without further processing. Otherwise, it returns a string with a traceback of the call stack. -An optional message string is appended +The optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback @@ -10015,7 +10426,7 @@ to start the traceback

      -Returns an unique identifier (as a light userdata) +Returns a unique identifier (as a light userdata) for the upvalue numbered n from the given function. @@ -10071,8 +10482,7 @@ The options are:

    • --: stops handling options;
    • -: executes stdin as a file and stops handling options.

    -After handling its options, lua runs the given script, -passing to it the given args as string arguments. +After handling its options, lua runs the given script. When called without arguments, lua behaves as lua -v -i when the standard input (stdin) is a terminal, @@ -10081,8 +10491,8 @@ and as lua - otherwise.

    When called without option -E, -the interpreter checks for an environment variable LUA_INIT_5_2 -(or LUA_INIT if it is not defined) +the interpreter checks for an environment variable LUA_INIT_5_3 +(or LUA_INIT if the versioned name is not defined) before running any argument. If the variable content has the format @filename, then lua executes the file. @@ -10112,50 +10522,71 @@ and finally run the file script.lua with no arguments.

    -Before starting to run the script, -lua collects all arguments in the command line +Before running any code, +lua collects all command-line arguments in a global table called arg. -The script name is stored at index 0, +The script name goes to index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name -(that is, the interpreter name plus the options) +(that is, the interpreter name plus its options) go to negative indices. For instance, in the call

          $ lua -la b.lua t1 t2
     

    -the interpreter first runs the file a.lua, -then creates a table +the table is like this:

          arg = { [-2] = "lua", [-1] = "-la",
                  [0] = "b.lua",
                  [1] = "t1", [2] = "t2" }
     

    -and finally runs the file b.lua. -The script is called with arg[1], arg[2], ... -as arguments; -it can also access these arguments with the vararg expression '...'. +If there is no script in the call, +the interpreter name goes to index 0, +followed by the other arguments. +For instance, the call + +

    +     $ lua -e "print(arg[1])"
    +

    +will print "-e". +If there is a script, +the script is called with parameters +arg[1], ···, arg[#arg]. +(Like all chunks in Lua, +the script is compiled as a vararg function.)

    In interactive mode, -if you write an incomplete statement, +Lua repeatedly prompts and waits for a line. +After reading a line, +Lua first try to interpret the line as an expression. +If it succeeds, it prints its value. +Otherwise, it interprets the line as a statement. +If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

    +If the global variable _PROMPT contains a string, +then its value is used as the prompt. +Similarly, if the global variable _PROMPT2 contains a string, +its value is used as the secondary prompt +(issued during incomplete statements). + + +

    In case of unprotected errors in the script, the interpreter reports the error to the standard error stream. -If the error object is a string, -the interpreter adds a stack traceback to it. -Otherwise, if the error object has a metamethod __tostring, +If the error object is not a string but +has a metamethod __tostring, the interpreter calls this metamethod to produce the final message. -Finally, if the error object is nil, -the interpreter does not report the error. +Otherwise, the interpreter converts the error object to a string +and adds a stack traceback to it.

    @@ -10194,67 +10625,80 @@ is a more portable solution.)

    Here we list the incompatibilities that you may find when moving a program -from Lua 5.1 to Lua 5.2. +from Lua 5.2 to Lua 5.3. You can avoid some incompatibilities by compiling Lua with appropriate options (see file luaconf.h). However, -all these compatibility options will be removed in the next version of Lua. -Similarly, -all features marked as deprecated in Lua 5.1 -have been removed in Lua 5.2. +all these compatibility options will be removed in the future. +

    +Lua versions can always change the C API in ways that +do not imply source-code changes in a program, +such as the numeric values for constants +or the implementation of functions as macros. +Therefore, +you should not assume that binaries are compatible between +different Lua versions. +Always recompile clients of the Lua API when +using a new version. -

    8.1 – Changes in the Language

    -
      -
    • -The concept of environment changed. -Only Lua functions have environments. -To set the environment of a Lua function, -use the variable _ENV or the function load. +

      +Similarly, Lua versions can always change the internal representation +of precompiled chunks; +precompiled chunks are not compatible between different Lua versions.

      -C functions no longer have environments. -Use an upvalue with a shared table if you need to keep -shared state among several C functions. -(You may use luaL_setfuncs to open a C library -with all functions sharing a common upvalue.) +The standard paths in the official distribution may +change between versions. -

      -To manipulate the "environment" of a userdata -(which is now called user value), -use the new functions -lua_getuservalue and lua_setuservalue. -

    • -
    • -Lua identifiers cannot use locale-dependent letters. -
    • +

      8.1 – Changes in the Language

      +
      • -Doing a step or a full collection in the garbage collector -does not restart the collector if it has been stopped. -
      • +The main difference between Lua 5.2 and Lua 5.3 is the +introduction of an integer subtype for numbers. +Although this change should not affect "normal" computations, +some computations +(mainly those that involve some kind of overflow) +can give different results. -
      • -Weak tables with weak keys now perform like ephemeron tables. + +

        +You can fix these differences by forcing a number to be a float +(in Lua 5.2 all numbers were float), +in particular writing constants with an ending .0 +or using x = x + 0.0 to convert a variable. +(This recommendation is only for a quick fix +for an occasional incompatibility; +it is not a general guideline for good programming. +For good programming, +use floats where you need floats +and integers where you need integers.)

      • -The event tail return in debug hooks was removed. -Instead, tail calls generate a special new event, -tail call, so that the debugger can know that -there will not be a corresponding return event. +The conversion of a float to a string now adds a .0 suffix +to the result if it looks like an integer. +(For instance, the float 2.0 will be printed as 2.0, +not as 2.) +You should always use an explicit format +when you need a specific format for numbers. + + +

        +(Formally this is not an incompatibility, +because Lua does not specify how numbers are formatted as strings, +but some programs assumed a specific format.)

      • -Equality between function values has changed. -Now, a function definition may not create a new value; -it may reuse some previous value if there is no -observable difference to the new function. +The generational mode for the garbage collector was removed. +(It was an experimental feature in Lua 5.2.)
      @@ -10266,67 +10710,57 @@ observable difference to the new function.
      • -Function module is deprecated. -It is easy to set up a module with regular Lua code. -Modules are not expected to set global variables. -
      • - -
      • -Functions setfenv and getfenv were removed, -because of the changes in environments. -
      • - -
      • -Function math.log10 is deprecated. -Use math.log with 10 as its second argument, instead. -
      • - -
      • -Function loadstring is deprecated. -Use load instead; it now accepts string arguments -and are exactly equivalent to loadstring. -
      • - -
      • -Function table.maxn is deprecated. -Write it in Lua if you really need it. +The bit32 library has been deprecated. +It is easy to require a compatible external library or, +better yet, to replace its functions with appropriate bitwise operations. +(Keep in mind that bit32 operates on 32-bit integers, +while the bitwise operators in Lua 5.3 operate on Lua integers, +which by default have 64 bits.)
      • -Function os.execute now returns true when command -terminates successfully and nil plus error information -otherwise. +The Table library now respects metamethods +for setting and getting elements.
      • -Function unpack was moved into the table library -and therefore must be called as table.unpack. +The ipairs iterator now respects metamethods and +its __ipairs metamethod has been deprecated.
      • -Character class %z in patterns is deprecated, -as now patterns may contain '\0' as a regular character. +Option names in io.read do not have a starting '*' anymore. +For compatibility, Lua will continue to accept (and ignore) this character.
      • -The table package.loaders was renamed package.searchers. +The following functions were deprecated in the mathematical library: +atan2, cosh, sinh, tanh, pow, +frexp, and ldexp. +You can replace math.pow(x,y) with x^y; +you can replace math.atan2 with math.atan, +which now accepts one or two parameters; +you can replace math.ldexp(x,exp) with x * 2.0^exp. +For the other operations, +you can either use an external library or +implement them in Lua.
      • -Lua does not have bytecode verification anymore. -So, all functions that load code -(load and loadfile) -are potentially insecure when loading untrusted binary data. -(Actually, those functions were already insecure because -of flaws in the verification algorithm.) -When in doubt, -use the mode argument of those functions -to restrict them to loading textual chunks. +The searcher for C loaders used by require +changed the way it handles versioned names. +Now, the version should come after the module name +(as is usual in most other tools). +For compatibility, that searcher still tries the old format +if it cannot find an open function according to the new style. +(Lua 5.2 already worked that way, +but it did not document the change.)
      • -The standard paths in the official distribution may -change between versions. +The call collectgarbage("count") now returns only one result. +(You can compute that second result from the fractional part +of the first result.)
      @@ -10335,75 +10769,36 @@ change between versions.

      8.3 – Changes in the API

      -
        - -
      • -Pseudoindex LUA_GLOBALSINDEX was removed. -You must get the global environment from the registry -(see §4.5). -
      • - -
      • -Pseudoindex LUA_ENVIRONINDEX -and functions lua_getfenv/lua_setfenv -were removed, -as C functions no longer have environments. -
      • - -
      • -Function luaL_register is deprecated. -Use luaL_setfuncs so that your module does not create globals. -(Modules are not expected to set global variables anymore.) -
      • - -
      • -The osize argument to the allocation function -may not be zero when creating a new block, -that is, when ptr is NULL -(see lua_Alloc). -Use only the test ptr == NULL to check whether -the block is new. -
      • - -
      • -Finalizers (__gc metamethods) for userdata are called in the -reverse order that they were marked for finalization, -not that they were created (see §2.5.1). -(Most userdata are marked immediately after they are created.) -Moreover, -if the metatable does not have a __gc field when set, -the finalizer will not be called, -even if it is set later. -
      • -
      • -luaL_typerror was removed. -Write your own version if you need it. -
      • -
      • -Function lua_cpcall is deprecated. -You can simply push the function with lua_pushcfunction -and call it with lua_pcall. -
      • +
        • -Functions lua_equal and lua_lessthan are deprecated. -Use the new lua_compare with appropriate options instead. +Continuation functions now receive as parameters what they needed +to get through lua_getctx, +so lua_getctx has been removed. +Adapt your code accordingly.
        • -Function lua_objlen was renamed lua_rawlen. +Function lua_dump has an extra parameter, strip. +Use 0 as the value of this parameter to get the old behavior.
        • -Function lua_load has an extra parameter, mode. -Pass NULL to simulate the old behavior. +Functions to inject/project unsigned integers +(lua_pushunsigned, lua_tounsigned, lua_tounsignedx, +luaL_checkunsigned, luaL_optunsigned) +were deprecated. +Use their signed equivalents with a type cast.
        • -Function lua_resume has an extra parameter, from. -Pass NULL or the thread doing the call. +Macros to project non-default integer types +(luaL_checkint, luaL_optint, luaL_checklong, luaL_optlong) +were deprecated. +Use their equivalent over lua_Integer with a type cast +(or, when possible, use lua_Integer in your code).
        @@ -10415,7 +10810,13 @@ Pass NULL or the thread doing the call.

        Here is the complete syntax of Lua in extended BNF. -(It does not describe operator precedences.) +As usual in extended BNF, +{A} means 0 or more As, +and [A] means an optional A. +(For operator precedences, see §3.4.8; +for a description of the terminals +Name, Numeral, +and LiteralString, see §3.1.) @@ -10456,14 +10857,14 @@ Here is the complete syntax of Lua in extended BNF. explist ::= exp {‘,’ exp} - exp ::= nil | false | true | Number | String | ‘...’ | functiondef | + exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | ‘(’ exp ‘)’ functioncall ::= prefixexp args | prefixexp ‘:’ Name args - args ::= ‘(’ [explist] ‘)’ | tableconstructor | String + args ::= ‘(’ [explist] ‘)’ | tableconstructor | LiteralString functiondef ::= function funcbody @@ -10479,11 +10880,12 @@ Here is the complete syntax of Lua in extended BNF. fieldsep ::= ‘,’ | ‘;’ - binop ::= ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘^’ | ‘%’ | ‘..’ | + binop ::= ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | + ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | and | or - unop ::= ‘-’ | not | ‘#’ + unop ::= ‘-’ | not | ‘#’ | ‘~

    @@ -10495,13 +10897,13 @@ Here is the complete syntax of Lua in extended BNF. -
    - + + diff --git a/doc/readme.html b/doc/readme.html index a4ee991..6629304 100644 --- a/doc/readme.html +++ b/doc/readme.html @@ -1,7 +1,7 @@ -Lua 5.2 readme +Lua 5.3 readme