diff --git a/CMakeLists.txt b/CMakeLists.txt index cc303f5e..b35d92b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2007-2013 LuaDist. +# Copyright (C) 2007-2015 LuaDist. # Created by Peter Drahoš, Peter Kapec # Redistribution and use of this file is allowed according to the terms of the MIT license. # For details see the COPYRIGHT file distributed with LuaDist. @@ -14,10 +14,11 @@ set ( LUA_PATH "LUA_PATH" CACHE STRING "Environment variable to use as package.p set ( LUA_CPATH "LUA_CPATH" CACHE STRING "Environment variable to use as package.cpath." ) set ( LUA_INIT "LUA_INIT" CACHE STRING "Environment variable for initial script." ) -option ( LUA_ANSI "Use only ansi features." OFF ) +option ( LUA_USE_C89 "Use only C89 features." OFF ) option ( LUA_USE_RELATIVE_LOADLIB "Use modified loadlib.c with support for relative paths on posix systems." ON ) -option ( LUA_COMPAT_ALL "Enable backwards compatibility options." ON ) -set ( LUA_IDSIZE 60 CACHE NUMBER "gives the maximum size for the description of the source." ) + +option ( LUA_COMPAT_5_1 "Enable backwards compatibility options with lua-5.1." ON ) +option ( LUA_COMPAT_5_2 "Enable backwards compatibility options with lua-5.2." ON ) #2DO: LUAI_* and LUAL_* settings, for now defaults are used. set ( LUA_DIRSEP "/" ) @@ -38,11 +39,11 @@ set ( LUA_CPATH_DEFAULT "./?${LUA_MODULE_SUFFIX};${LUA_DIR}${LUA_CDIR}/?${LUA_MO if ( WIN32 AND NOT CYGWIN ) # Windows systems - option ( LUA_WIN "Windows specific build." ON ) + option ( LUA_USE_WINDOWS "Windows specific build." ON ) option ( LUA_BUILD_WLUA "Build wLua interpretter without console output." ON ) option ( LUA_BUILD_AS_DLL "Build Lua library as Dll." ${BUILD_SHARED_LIBS} ) - - # Paths (Double escapes ne option needed) + + # Paths (Double escapes needed) set ( LUA_DIRSEP "\\\\" ) string ( REPLACE " /" ${LUA_DIRSEP} LUA_DIR "${LUA_DIR}" ) string ( REPLACE "/" ${LUA_DIRSEP} LUA_LDIR "${LUA_LDIR}" ) @@ -53,16 +54,9 @@ else ( ) # Posix systems (incl. Cygwin) option ( LUA_USE_POSIX "Use POSIX features." ON ) option ( LUA_USE_DLOPEN "Use dynamic linker to load modules." ON ) - option ( LUA_USE_MKSTEMP "Use mkstep." ON ) - option ( LUA_USE_ISATTY "Use tty." ON ) - option ( LUA_USE_POPEN "Use popen." ON ) - option ( LUA_USE_ULONGJMP "Use ulongjmp" ON ) - option ( LUA_USE_GMTIME_R "Use GTIME_R" ON ) # Apple and Linux specific if ( LINUX OR APPLE ) - option ( LUA_USE_STRTODHEX "Assume 'strtod' handles hexa formats" ON ) option ( LUA_USE_AFORMAT "Assume 'printf' handles 'aA' specifiers" ON ) - option ( LUA_USE_LONGLONG "Assume support for long long" ON ) endif ( ) endif ( ) @@ -73,11 +67,6 @@ if ( READLINE_FOUND ) option ( LUA_USE_READLINE "Use readline in the Lua CLI." ON ) endif ( ) -find_package ( Curses ) -if ( CURSES_FOUND ) - option ( LUA_USE_CURSES "Use curses in the Lua CLI." ON ) -endif ( ) - # Setup needed variables and libraries if ( LUA_USE_POSIX ) # On POSIX Lua links to standard math library "m" @@ -88,7 +77,7 @@ if ( LUA_USE_DLOPEN ) # Link to dynamic linker library "dl" find_library ( DL_LIBRARY NAMES dl ) if ( DL_LIBRARY ) - list ( APPEND LIBS ${DL_LIBRARY} ) + list ( APPEND LIBS ${DL_LIBRARY} ) endif ( ) endif ( ) @@ -98,23 +87,18 @@ if ( LUA_USE_READLINE ) list ( APPEND LIBS ${READLINE_LIBRARY} ) endif ( ) -if ( LUA_USE_CURSES ) - # Add curses - include_directories ( ${CURSES_INCLUDE_DIR} ) - list ( APPEND LIBS ${CURSES_LIBRARY} ) -endif ( ) - ## SOURCES # Generate luaconf.h configure_file ( src/luaconf.h.in ${CMAKE_CURRENT_BINARY_DIR}/luaconf.h ) # Sources and headers include_directories ( src ${CMAKE_CURRENT_BINARY_DIR} ) -set ( SRC_CORE src/lapi.c src/lcode.c src/lctype.c src/ldebug.c src/ldo.c src/ldump.c - src/lfunc.c src/lgc.c src/llex.c src/lmem.c src/lobject.c src/lopcodes.c src/lparser.c +set ( SRC_CORE src/lapi.c src/lcode.c src/lctype.c src/ldebug.c src/ldo.c src/ldump.c + src/lfunc.c src/lgc.c src/llex.c src/lmem.c src/lobject.c src/lopcodes.c src/lparser.c src/lstate.c src/lstring.c src/ltable.c src/ltm.c src/lundump.c src/lvm.c src/lzio.c ) -set ( SRC_LIB src/lauxlib.c src/lbaselib.c src/lbitlib.c src/lcorolib.c src/ldblib.c - src/liolib.c src/lmathlib.c src/loslib.c src/lstrlib.c src/ltablib.c src/linit.c ) +set ( SRC_LIB src/lauxlib.c src/lbaselib.c src/lbitlib.c src/lcorolib.c src/ldblib.c + src/liolib.c src/lmathlib.c src/loslib.c src/lstrlib.c src/ltablib.c src/linit.c + src/lutf8lib.c ) set ( SRC_LUA src/lua.c ) set ( SRC_LUAC src/luac.c ) @@ -127,7 +111,7 @@ endif ( ) ## BUILD # Create lua library -add_library ( liblua ${SRC_CORE} ${SRC_LIB} ${LUA_DLL_RC} ${LUA_DEF} ) +add_library ( liblua ${SRC_CORE} ${SRC_LIB} ${LUA_DLL_RC} ) target_link_libraries ( liblua ${LIBS} ) set_target_properties ( liblua PROPERTIES OUTPUT_NAME lua CLEAN_DIRECT_OUTPUT 1 ) if ( LUA_BUILD_AS_DLL ) diff --git a/Makefile b/Makefile index b2a62cfd..e87e958c 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.2 # Targets start here. all: $(PLAT) diff --git a/README.md b/README.md index 710e3ee1..eb6247a4 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -This is Lua 5.2.4, released on 25 Feb 2015. +This is Lua 5.3.2, released on 25 Nov 2015. For installation instructions, license details, and further information about Lua, see doc/readme.html. diff --git a/dist.info b/dist.info index 50f91867..b9987268 100644 --- a/dist.info +++ b/dist.info @@ -1,7 +1,7 @@ --- This file is part of LuaDist project name = "lua" -version = "5.2.4" +version = "5.3.2" desc = "Lua is a powerful, fast, light-weight, embeddable scripting language." author = "Roberto Ierusalimschy, Waldemar Celes, Luiz Henrique de Figueiredo" @@ -9,7 +9,3 @@ license = "MIT/X11" url = "http://www.lua.org" maintainer = "Peter Drahoš" --- Offers functionality of the following packages -provides = { - "bit32-5.2.0" -} diff --git a/doc/contents.html b/doc/contents.html index 9d5202fa..1272c59c 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 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 00000000..c9618357 --- /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 1dbf0436..411531b9 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 5dc9a8b9..eb20fecd 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,27 +55,38 @@ 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 { @@ -104,3 +109,51 @@ 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 ; +} diff --git a/doc/manual.css b/doc/manual.css index ca613cd9..aa0e677d 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 0a95e9e0..60c4c98b 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 Lua.org, PUC-Rio. Freely available under the terms of the Lua license. - -


-

+ -contents +

- + @@ -44,7 +46,7 @@

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, +Lua 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. @@ -53,7 +55,7 @@

1 – Introduction

-Being an extension language, Lua has no notion of a "main" program: +As an extension language, Lua has no notion of a "main" program: it only works embedded in a host client, called the embedding program or simply the host. The host program can invoke functions to execute a piece of Lua code, @@ -113,40 +115,57 @@

2.1 – Values and Types

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 +179,17 @@

2.1 – Values and Types

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 +198,21 @@

2.1 – Values and Types

-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 +221,7 @@

2.1 – Values and Types

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 +231,18 @@

2.1 – Values and Types

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 +266,21 @@

2.2 – Environments and the Global Environment

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 +292,25 @@

2.2 – Environments and the Global 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 +319,9 @@

2.3 – Error Handling

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,9 +341,10 @@

2.3 – Error Handling

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.

@@ -333,7 +359,8 @@

2.3 – Error Handling

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. @@ -369,9 +396,9 @@

2.4 – Metatables and Metamethods

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,57 +412,32 @@

2.4 – Metatables and Metamethods

-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 +A detailed list of events controlled by metatables is given next. +Each operation is identified by its corresponding event name. +The key for each event is a string with its name prefixed by two underscores, '__'; for instance, the key for operation "add" is the string "__add". +Note that queries for metamethods are always raw; +the access to a metamethod does not invoke other metamethods.

-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 - 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.) +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.) @@ -444,39 +446,19 @@

2.4 – Metatables and Metamethods

  • "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
    -

    +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 the "__add" event, +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": @@ -500,267 +482,192 @@

    2.4 – Metatables and Metamethods

  • "mod": the % operation. -Behavior similar to the "add" operation, -with the operation -o1 - floor(o1/o2)*o2 as the primitive operation. +Behavior similar to the "add" operation.
  • "pow": the ^ (exponentiation) operation. -Behavior similar to the "add" operation, -with the function pow (from the C math library) -as the primitive operation. +Behavior similar to the "add" operation.
  • "unm": -the unary - operation. +the - (unary minus) operation. +Behavior similar to the "add" 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
    -

    +

  • "idiv": +the // (floor division) operation. + +Behavior similar to the "add" operation.
  • -
  • "concat": -the .. (concatenation) operation. +
  • "band": +the & (bitwise and) operation. +Behavior similar to the "add" 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). +
  • -
    -     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
    -

    +

  • "bor": +the | (bitwise or) operation. + +Behavior similar to the "band" operation.
  • -
  • "len": -the # operation. +
  • "bxor": +the ~ (bitwise exclusive or) operation. +Behavior similar to the "band" 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. +

  • "bnot": +the ~ (bitwise unary not) operation. + +Behavior similar to the "band" operation.
  • -
  • "eq": -the == operation. +
  • "shl": +the << (bitwise left shift) 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. +Behavior similar to the "band" operation. +
  • -
    -     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: +

  • "shr": +the >> (bitwise right shift) 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. +Behavior similar to the "band" operation.

  • -
  • "lt": -the < operation. +
  • "concat": +the .. (concatenation) operation. +Behavior similar to the "add" 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). +
  • -
    -     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. +

  • "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.
  • -
  • "le": -the <= operation. +
  • "eq": +the == (equal) operation. +Behavior similar to the "add" 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. +
  • -
    -     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). +

  • "lt": +the < (less than) operation. +Behavior similar to the "add" 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 "lt" operation. +If it cannot find such a metamethod, +then it will try the "__lt" event, +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": 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. +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": 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.) + + +

    +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.)

  • "call": -called when Lua calls a value. - +The call operation func(args). -
    -     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
    -

    +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).

  • +

    +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). + + @@ -769,8 +676,8 @@

    2.5 – Garbage Collection

    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 +710,8 @@

    2.5 – Garbage Collection

    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 +736,6 @@

    2.5 – Garbage Collection

    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 +759,6 @@

    2.5.1 – Garbage-Collection Metamethods

    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 +766,19 @@

    2.5.1 – Garbage-Collection Metamethods

    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 +788,27 @@

    2.5.1 – Garbage-Collection Metamethods

    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 +827,8 @@

    2.5.2 – Weak Tables

    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 +865,7 @@

    2.5.2 – 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 +918,10 @@

    2.6 – Coroutines

    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,7 +931,8 @@

    2.6 – Coroutines

    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. @@ -1159,7 +1051,8 @@

    3.1 – Lexical Conventions

    (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 +1072,10 @@

    3.1 – Lexical Conventions

    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 +1083,7 @@

    3.1 – Lexical Conventions

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

    3.1 – Lexical Conventions

    -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 +1142,15 @@

    3.1 – Lexical Conventions

    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. @@ -1285,7 +1192,8 @@

    3.1 – Lexical Conventions

    -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 +1201,19 @@

    3.1 – Lexical Conventions

    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 fractional dot or an exponent +denotes a float; +otherwise it denotes an integer. +Examples of valid integer constants are
    -     3     3.0     3.1416     314.16e-2     0.31416E1
    -     0xff  0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
    +     3   345   0xff   0xBEBADA
    +

    +Examples of valid float constants are + +

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

    @@ -1466,7 +1382,7 @@

    3.3.2 – Chunks

    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 +1394,17 @@

    3.3.2 – Chunks

    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 +1443,7 @@

    3.3.3 – Assignment

    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 +1479,7 @@ 

    3.3.3 – Assignment

    -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 +1560,8 @@

    3.3.4 – Control Structures

    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 +1587,11 @@

    3.3.5 – For Statement

    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 +1612,19 @@

    3.3.5 – For Statement

    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:

    @@ -1804,7 +1726,7 @@

    3.3.6 – Function Calls 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 +1766,8 @@

    3.4 – Expressions

     	exp ::= prefixexp
     	exp ::= nil | false | true
    -	exp ::= Number
    -	exp ::= String
    +	exp ::= Numeral
    +	exp ::= LiteralString
     	exp ::= functiondef
     	exp ::= tableconstructor
     	exp ::= ‘...’
    @@ -1855,24 +1777,26 @@ 

    3.4 – Expressions

    -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 +1847,145 @@

    3.4 – Expressions

    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. +

    + +

    +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. -

    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. +Modulo is defined as the remainder of a division +that rounds the quotient towards minus infinity (floor division). + + +

    +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: + +

    + +

    +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). + + +

    +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 +1994,17 @@

    3.4.2 – Coercion

    -

    3.4.3 – Relational Operators

    -The relational operators in Lua are +

    3.4.4 – Relational Operators

    +Lua supports the following relational operators: -

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

    +

    These operators always result in false or true. @@ -1976,7 +2012,11 @@

    3.4.3 – Relational Operators

    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 +2034,8 @@

    3.4.3 – Relational Operators

    -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 +2047,9 @@

    3.4.3 – Relational Operators

    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 +2058,16 @@

    3.4.3 – Relational Operators

    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 +2083,7 @@

    3.4.4 – Logical Operators

    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 +2105,18 @@

    3.4.4 – Logical Operators

    -

    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 +2154,7 @@

    3.4.6 – The Length Operator

    -

    3.4.7 – Precedence

    +

    3.4.8 – Precedence

    Operator precedence in Lua follows the table below, from lower to higher priority: @@ -2114,10 +2162,14 @@

    3.4.7 – Precedence

    or and < > <= >= ~= == + | + ~ + & + << >> .. + - - * / % - not # - (unary) + * / // % + unary operators (not # - ~) ^

    As usual, @@ -2130,7 +2182,7 @@

    3.4.7 – Precedence

    -

    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 +2202,7 @@

    3.4.8 – Table Constructors

    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, @@ -2174,11 +2226,16 @@

    3.4.8 – Table Constructors

    end +

    +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 +2246,7 @@

    3.4.8 – Table Constructors

    -

    3.4.9 – Function Calls

    +

    3.4.10 – Function Calls

    A function call in Lua has the following syntax:

    @@ -2224,7 +2281,7 @@ 

    3.4.9 – Function Calls

     	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 +2321,7 @@

    3.4.9 – Function Calls

    -

    3.4.10 – Function Definitions

    +

    3.4.11 – Function Definitions

    The syntax for function definition is @@ -2555,12 +2612,13 @@

    4.2 – Stack Size

    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 +2627,7 @@

    4.2 – Stack Size

    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 +2645,22 @@

    4.3 – Valid and 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 +2703,13 @@

    4.4 – C Closures

    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 +2723,24 @@

    4.5 – 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 +2768,8 @@

    4.6 – Error Handling in C

    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) @@ -2741,20 +2793,20 @@

    4.6 – Error Handling in C

    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. +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 +2816,7 @@

    4.7 – Handling Yields in C

    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 +2829,7 @@

    4.7 – Handling Yields in C

    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.

    @@ -2806,6 +2858,81 @@

    4.7 – Handling Yields in C

    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 @@ -2819,11 +2946,6 @@

    4.7 – Handling Yields in C

    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 +2972,11 @@

    4.8 – Functions and Types

    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 memory errors; +'e' means the function may raise errors; +'v' means the function may raise an error on purpose. @@ -2862,7 +2985,8 @@

    4.8 – Functions and Types

    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 +3009,7 @@

    4.8 – Functions and Types

    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 +3035,13 @@

    4.8 – Functions and Types

    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 +3066,7 @@

    4.8 – Functions and Types

    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 +3080,8 @@

    4.8 – Functions and Types

    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 +3097,17 @@

    4.8 – Functions and Types

  • 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 negation (~)
  • +
  • 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 +3147,8 @@

    4.8 – Functions and Types

    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 +3170,7 @@

    4.8 – Functions and Types

          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 +3178,7 @@ 

    4.8 – Functions and Types

    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 +3188,11 @@

    4.8 – Functions and Types


    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 +3230,16 @@

    4.8 – Functions and Types

    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 +3255,18 @@ 

    4.8 – Functions and Types


    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 +3285,7 @@

    4.8 – Functions and Types

    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 +3302,7 @@

    4.8 – Functions and Types

    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 +3330,7 @@

    4.8 – Functions and Types

    (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 +3341,17 @@

    4.8 – Functions and Types

    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 +3361,7 @@

    4.8 – Functions and Types

    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 +3370,11 @@

    4.8 – Functions and Types


    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. @@ -3248,6 +3388,13 @@

    4.8 – Functions and Types

    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; @@ -3266,9 +3413,8 @@

    4.8 – Functions and Types

    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). @@ -3314,24 +3460,18 @@

    4.8 – Functions and Types

  • 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 +3479,6 @@

    4.8 – Functions and Types

    (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 +3496,80 @@

    4.8 – Functions and Types

    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 +3580,9 @@

    4.8 – Functions and Types

    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 +3591,7 @@

    4.8 – Functions and Types


    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 +3600,16 @@

    4.8 – Functions and Types

    -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 +3620,8 @@

    4.8 – Functions and Types

    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 +3629,15 @@

    4.8 – Functions and Types


    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 +3658,24 @@

    4.8 – Functions and Types


    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 +3717,19 @@

    4.8 – Functions and Types

    +

    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 +3841,51 @@

    4.8 – Functions and Types

    +

    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 +3897,11 @@

    4.8 – Functions and Types

    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. @@ -3727,7 +3936,7 @@

    4.8 – Functions and Types

    -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 +3950,17 @@

    4.8 – Functions and Types

    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 +3972,7 @@

    4.8 – Functions and Types

    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 +3984,7 @@

    4.8 – Functions and Types


    lua_newtable

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

    void lua_newtable (lua_State *L);

    @@ -3786,7 +3996,7 @@

    4.8 – Functions and Types


    lua_newthread

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

    lua_State *lua_newthread (lua_State *L);

    @@ -3807,7 +4017,7 @@

    4.8 – Functions and Types


    lua_newuserdata

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

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

    @@ -3866,13 +4076,38 @@

    4.8 – Functions and Types


    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);
    + +

    +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.) +

    -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). +This macro may evaluate its arguments more than once. @@ -3906,7 +4141,7 @@

    4.8 – Functions and Types

    is exactly the original error message. 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 @@ -3921,7 +4156,7 @@

    4.8 – Functions and Types

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

    @@ -3958,9 +4192,9 @@

    4.8 – Functions and Types

    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 +4227,7 @@

    4.8 – Functions and Types


    lua_pushcclosure

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

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

    @@ -4006,11 +4240,11 @@

    4.8 – Functions and Types

    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 +4257,7 @@

    4.8 – Functions and Types

    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,25 +4275,16 @@

    4.8 – Functions and Types

    -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. - -


    lua_pushfstring

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

    const char *lua_pushfstring (lua_State *L, const char *fmt, ...);

    @@ -4080,12 +4305,14 @@

    4.8 – Functions and Types

    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). @@ -4109,7 +4336,7 @@

    4.8 – Functions and Types

    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 +4364,19 @@

    4.8 – Functions and Types


    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 +4412,14 @@

    4.8 – Functions and Types

    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 +4453,6 @@

    4.8 – Functions and Types

    -

    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 +4466,7 @@

    4.8 – Functions and Types


    lua_pushvfstring

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

    const char *lua_pushvfstring (lua_State *L,
                                   const char *fmt,
                                   va_list argp);
    @@ -4273,7 +4488,7 @@

    4.8 – Functions and Types

    index2 are primitively equal (that is, without calling metamethods). 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 +4496,7 @@

    4.8 – Functions and Types


    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,7 +4508,7 @@

    4.8 – Functions and Types


    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], @@ -4302,12 +4517,16 @@

    4.8 – Functions and Types

    that is, it does not invoke metamethods. +

    +Returns the type of the pushed value. + +


    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], @@ -4317,6 +4536,10 @@

    4.8 – Functions and Types

    that is, it does not invoke metamethods. +

    +Returns the type of the pushed value. + + @@ -4338,7 +4561,7 @@

    4.8 – Functions and Types


    lua_rawset

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

    void lua_rawset (lua_State *L, int index);

    @@ -4350,11 +4573,11 @@

    4.8 – Functions and Types


    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. @@ -4369,13 +4592,13 @@

    4.8 – Functions and Types


    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. @@ -4447,7 +4670,7 @@

    4.8 – Functions and Types

    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 +4682,7 @@

    4.8 – Functions and Types

    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.

    @@ -4501,6 +4724,26 @@

    4.8 – Functions and Types

    +

    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 +4787,25 @@

    4.8 – Functions and Types

    +

    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 +4858,7 @@

    4.8 – Functions and Types

    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 +4910,27 @@

    4.8 – Functions and Types

    +

    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,16 +4980,11 @@

    4.8 – Functions and Types

    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 @@ -4717,13 +4995,13 @@

    4.8 – Functions and Types


    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 +5012,17 @@

    4.8 – Functions and Types

    -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 +5047,7 @@

    4.8 – Functions and Types

    Converts the Lua value at the given index to the C type 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 +5074,14 @@

    4.8 – Functions and Types

    -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 +5105,6 @@

    4.8 – Functions and Types

    -

    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 +5129,7 @@

    4.8 – Functions and Types

    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 +5157,10 @@

    4.8 – Functions and Types


    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. @@ -5000,14 +5235,14 @@

    4.8 – Functions and Types


    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 +5250,22 @@

    4.8 – Functions and Types


    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 +5274,34 @@

    4.8 – Functions and Types

    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 hook (see §4.9). +In that case, lua_yieldk should be called with no continuation +(probably in the form of lua_yield), +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 +5355,7 @@

    4.9 – The Debug Interface

    @@ -5293,7 +5553,7 @@

    4.9 – The Debug Interface


    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 +5576,7 @@

    4.9 – The Debug Interface

    -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 +5620,26 @@

    4.9 – The Debug Interface

    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 +5684,10 @@

    4.9 – The Debug Interface

    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 +5695,7 @@

    4.9 – The Debug Interface


    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. @@ -5486,13 +5748,11 @@

    4.9 – The Debug Interface


    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 +5763,10 @@

    4.9 – The Debug Interface

    the number of active local variables. +

    +Parameters ar and n are as in function lua_getlocal. + + @@ -5515,13 +5779,15 @@

    4.9 – The Debug Interface

    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 +5798,8 @@

    4.9 – The Debug Interface

    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 +5810,11 @@

    4.9 – The Debug Interface

    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 +5877,7 @@

    5 – The Auxiliary Library

    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 +5890,7 @@

    5.1 – Functions and Types


    luaL_addchar

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

    void luaL_addchar (luaL_Buffer *B, char c);

    @@ -5634,7 +5902,7 @@

    5.1 – Functions and Types


    luaL_addlstring

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

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

    @@ -5648,7 +5916,7 @@

    5.1 – Functions and Types


    luaL_addsize

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

    void luaL_addsize (luaL_Buffer *B, size_t n);

    @@ -5661,21 +5929,20 @@

    5.1 – Functions and Types


    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 +5970,7 @@

    5.1 – Functions and Types

    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 +5981,15 @@

    5.1 – Functions and Types

    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 +6080,7 @@

    5.1 – Functions and Types


    luaL_buffinitsize

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

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

    @@ -5856,37 +6124,14 @@

    5.1 – Functions and Types

    -

    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,18 +6255,6 @@

    5.1 – Functions and Types

    -

    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, –]

    void luaL_checkversion (lua_State *L);
    @@ -6098,7 +6331,7 @@

    5.1 – Functions and Types


    luaL_execresult

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

    int luaL_execresult (lua_State *L, int stat);

    @@ -6111,7 +6344,7 @@

    5.1 – Functions and Types


    luaL_fileresult

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

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

    @@ -6124,27 +6357,29 @@

    5.1 – Functions and Types


    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 +6402,7 @@

    5.1 – Functions and Types


    luaL_gsub

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

    const char *luaL_gsub (lua_State *L,
                            const char *s,
                            const char *p,
    @@ -6185,13 +6420,13 @@ 

    5.1 – Functions and Types


    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.) @@ -6302,23 +6537,29 @@

    5.1 – Functions and Types


    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 +6580,7 @@

    5.1 – Functions and Types


    luaL_newmetatable

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

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

    @@ -6347,8 +6588,10 @@

    5.1 – Functions and Types

    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,21 +6634,6 @@

    5.1 – Functions and Types

    -

    luaL_optint

    -[-0, +0, v] -

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

    -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. - - - - -


    luaL_optinteger

    [-0, +0, v]

    lua_Integer luaL_optinteger (lua_State *L,
    @@ -6413,23 +6641,9 @@ 

    5.1 – Functions and Types

    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 +6670,9 @@

    5.1 – Functions and Types

    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 +6710,8 @@

    5.1 – Functions and Types

    -

    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 +6723,7 @@

    5.1 – Functions and Types


    luaL_prepbuffsize

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

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

    @@ -6539,7 +6739,7 @@

    5.1 – Functions and Types


    luaL_pushresult

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

    void luaL_pushresult (luaL_Buffer *B);

    @@ -6551,7 +6751,7 @@

    5.1 – Functions and Types


    luaL_pushresultsize

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

    void luaL_pushresultsize (luaL_Buffer *B, size_t sz);

    @@ -6562,7 +6762,7 @@

    5.1 – Functions and Types


    luaL_ref

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

    int luaL_ref (lua_State *L, int t);

    @@ -6601,7 +6801,7 @@

    5.1 – Functions and Types

    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 +6814,26 @@

    5.1 – Functions and Types

    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 +6866,52 @@

    5.1 – Functions and Types

    +

    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. @@ -6702,7 +6941,7 @@

    5.1 – Functions and Types


    luaL_traceback

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

    void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
                          int level);
    @@ -6749,7 +6988,7 @@

    5.1 – Functions and Types


    luaL_where

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

    void luaL_where (lua_State *L, int lvl);

    @@ -6802,11 +7041,11 @@

    6 – 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 +7070,11 @@

    6 – Standard Libraries

    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 +7091,15 @@

    6.1 – Basic Functions


    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 +7130,21 @@

    6.1 – Basic Functions

  • "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 +7165,6 @@

    6.1 – Basic Functions

    (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 +7184,7 @@

    6.1 – Basic Functions


    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 +7208,7 @@

    6.1 – Basic Functions

    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. @@ -7003,27 +7232,21 @@

    6.1 – Basic Functions

    -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 +7254,10 @@

    6.1 – Basic Functions

    -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 +7273,22 @@

    6.1 – Basic Functions

    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 +7301,12 @@

    6.1 – Basic Functions

    The default is "bt". +

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

    @@ -7113,7 +7346,7 @@

    6.1 – Basic Functions

    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.) @@ -7212,7 +7445,7 @@

    6.1 – Basic Functions

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

    6.1 – Basic Functions

    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, @@ -7273,14 +7507,20 @@

    6.1 – Basic Functions

    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,7 +7535,7 @@

    6.1 – Basic Functions


    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.) @@ -7327,9 +7567,12 @@

    6.1 – Basic Functions


    _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 +7594,8 @@

    6.1 – Basic Functions

    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,13 +7605,28 @@

    6.2 – Coroutine Manipulation

    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". +

    +


    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 +7646,8 @@

    6.2 – Coroutine Manipulation

    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 +7689,7 @@

    6.2 – Coroutine Manipulation

    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 +7749,7 @@

    6.3 – Modules

    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 +7805,7 @@

    6.3 – Modules

    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 +7824,7 @@

    6.3 – Modules

    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 +7902,7 @@

    6.3 – Modules

    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 +7987,9 @@

    6.3 – Modules

    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 +8088,7 @@

    6.4 – String Manipulation


    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 +8097,7 @@

    6.4 – String Manipulation

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

    6.4 – String Manipulation


    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 +8149,11 @@

    6.4 – String Manipulation

    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 @@ -7928,20 +8201,23 @@

    6.4 – String Manipulation

    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. +Option q expects a string. +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. + + +

    +When Lua is compiled with a non-C99 compiler, +options A and a (hexadecimal floats) +do not support any modifier (flags, width, length). @@ -7950,7 +8226,8 @@

    6.4 – String Manipulation


    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 +8265,7 @@

    6.4 – String Manipulation


    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 +8330,9 @@

    6.4 – String Manipulation

    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,25 +8360,56 @@

    6.4 – String Manipulation


    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. +

    +


    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.) @@ -8140,6 +8448,21 @@

    6.4 – String Manipulation

    +

    +


    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 @@ -8149,8 +8472,21 @@

    6.4 – String Manipulation

    + +

    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 +8525,8 @@

    Character Class:

  • %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 +8536,7 @@

    Character Class:

    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. @@ -8248,26 +8585,27 @@

    Pattern Item:

  • 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 +8678,665 @@

    Captures:

    +

    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: + +

    +(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 - -

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

    -By default, i is 1 and j is #list. +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. +

    +This function assumes that s is a valid UTF-8 string. -

    6.6 – Mathematical Functions

    -

    -This library is an interface to the standard C math library. -It provides all its functions inside the table math. +

    6.6 – Table Manipulation

    -


    math.abs (x)

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

    -Returns the absolute value of x. - - +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.acos (x)

    +

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

    -Returns the arc cosine of x (in radians). - - - - -

    -


    math.asin (x)

    - - -

    -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. +This function performs 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)

    +

    table.pack (···)

    -Returns the smallest integer larger than or equal to x. - - +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.cos (x)

    -Returns the cosine of x (assumed to be in radians). - - +


    table.remove (list [, pos])

    -


    math.cosh (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 hyperbolic cosine of x. +The default value for pos is #list, +so that a call table.remove(l) removes the last element +of list l.

    -


    math.deg (x)

    +

    table.sort (list [, comp])

    -Returns the angle x (given in radians) in degrees. - - +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.exp (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 value ex. +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.floor (x)

    +

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

    -Returns the largest integer smaller than or equal to x. - - - +Returns the elements from the given list. +This function is equivalent to -

    -


    math.fmod (x, y)

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

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

    -Returns the remainder of the division of x by y -that rounds the quotient towards zero. -

    -


    math.frexp (x)

    +

    6.7 – Mathematical Functions

    -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). - - +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.huge

    +

    math.abs (x)

    -The value HUGE_VAL, -a value larger than or equal to any other numerical value. +Returns the absolute value of x. (integer/float)

    -


    math.ldexp (m, e)

    +

    math.acos (x)

    -Returns m2e (e should be an integer). +Returns the arc cosine of x (in radians).

    -


    math.log (x [, base])

    +

    math.asin (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 sine of x (in radians).

    -


    math.max (x, ···)

    +

    math.atan (y [, x])

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

    -


    math.min (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 the minimum value among its arguments. +The default value for x is 1, +so that the call math.atan(y) +returns the arc tangent of y.

    -


    math.modf (x)

    +

    math.ceil (x)

    -Returns two numbers, -the integral part of x and the fractional part of x. +Returns the smallest integral value larger than or equal to x.

    -


    math.pi

    +

    math.cos (x)

    -The value of π. +Returns the cosine of x (assumed to be in radians).

    -


    math.pow (x, y)

    +

    math.deg (x)

    -Returns xy. -(You can also use the expression x^y to compute this value.) +Converts the angle x from radians to degrees.

    -


    math.rad (x)

    +

    math.exp (x)

    -Returns the angle x (given in degrees) in radians. +Returns the value ex +(where e is the base of natural logarithms).

    -


    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.floor (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 largest integral value smaller than or equal to x.

    -


    math.randomseed (x)

    +

    math.fmod (x, y)

    -Sets x as the "seed" -for the pseudo-random generator: -equal seeds produce equal sequences of numbers. +Returns the remainder of the division of x by y +that rounds the quotient towards zero. (integer/float)

    -


    math.sin (x)

    +

    math.huge

    -Returns the sine of x (assumed to be in radians). +The float value HUGE_VAL, +a value larger than any other numeric value.

    -


    math.sinh (x)

    +

    math.log (x [, base])

    -Returns the hyperbolic sine of 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).

    -


    math.sqrt (x)

    +

    math.max (x, ···)

    -Returns the square root of x. -(You can also use the expression x^0.5 to compute this value.) - +Returns the argument with the maximum value, +according to the Lua operator <. (integer/float) -

    -


    math.tan (x)

    -

    -Returns the tangent of x (assumed to be in radians). +


    math.maxinteger

    +An integer with the maximum value for an integer.

    -


    math.tanh (x)

    +

    math.min (x, ···)

    -Returns the hyperbolic tangent of x. - - - - +Returns the argument with the minimum value, +according to the Lua operator <. (integer/float) -

    6.7 – Bitwise Operations

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

    -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. +


    math.mininteger

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

    -


    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. +


    math.modf (x)

    -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). +Returns the integral part of x and the fractional part of x. +Its second result is always a float.

    -


    bit32.band (···)

    +

    math.pi

    -Returns the bitwise and of its operands. +The value of π.

    -


    bit32.bnot (x)

    +

    math.rad (x)

    -Returns the bitwise negation of x. -For any integer x, -the following identity holds: +Converts the angle x from degrees to radians. -

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

    -


    bit32.bor (···)

    - - -

    -Returns the bitwise or of its operands. - - +


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

    -


    bit32.btest (···)

    +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 a boolean signaling -whether the bitwise and of its operands is different from zero. +This function is an interface to the underling +pseudo-random generator function provided by C.

    -


    bit32.bxor (···)

    +

    math.randomseed (x)

    -Returns the bitwise exclusive or of its operands. - - +Sets x as the "seed" +for the pseudo-random generator: +equal seeds produce equal sequences of numbers. -

    -


    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.sin (x)

    -The default for width is 1. +Returns the sine of x (assumed to be in radians).

    -


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

    - - -

    -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. - - +


    math.sqrt (x)

    -


    bit32.lrotate (x, disp)

    +Returns the square root of x. +(You can also use the expression x^0.5 to compute this value.) -

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

    -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. - - +


    math.tan (x)

    -


    bit32.lshift (x, disp)

    +Returns the tangent of x (assumed to be in radians). -

    -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).

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

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

    math.tointeger (x)

    -


    bit32.rrotate (x, disp)

    +If the value x is convertible to an integer, +returns that integer. +Otherwise, returns nil. -

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

    -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 +9348,24 @@

    6.8 – Input and Output Facilities

    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 +9376,7 @@

    6.8 – Input and Output Facilities

    (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 +9425,7 @@

    6.8 – Input and Output Facilities

    -


    io.lines ([filename ···])

    +

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

    @@ -9118,12 +9433,12 @@

    6.8 – Input and Output Facilities

    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. @@ -9276,7 +9591,7 @@

    6.8 – Input and Output Facilities

    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 +9618,10 @@ 

    6.8 – Input and Output Facilities

    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 +9632,44 @@

    6.8 – Input and Output Facilities

    +

    +The formats "l" and "L" should be used only for text files. + @@ -9474,7 +9799,7 @@

    6.9 – Operating System Facilities

    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), @@ -9492,12 +9817,12 @@

    6.9 – Operating System Facilities

    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 +9834,9 @@

    6.9 – Operating System Facilities

    -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 +9854,7 @@

    6.9 – Operating System Facilities

    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:

    -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 +10424,8 @@

    7 – Lua Standalone

    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,37 +10455,51 @@

    7 – Lua Standalone

    -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. @@ -10150,12 +10507,11 @@

    7 – Lua Standalone

    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 +10550,80 @@

    8 – Incompatibilities with the Previous Version

    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

    -
    @@ -10495,13 +10822,13 @@

    9 – The Complete Syntax of Lua

    -
    - + + diff --git a/doc/readme.html b/doc/readme.html index a4ee9919..152246f9 100644 --- a/doc/readme.html +++ b/doc/readme.html @@ -1,7 +1,7 @@ -Lua 5.2 readme +Lua 5.3 readme