diff options
Diffstat (limited to 'tests/lua/doc/manual.html')
-rw-r--r-- | tests/lua/doc/manual.html | 10507 |
1 files changed, 10507 insertions, 0 deletions
diff --git a/tests/lua/doc/manual.html b/tests/lua/doc/manual.html new file mode 100644 index 00000000..85365363 --- /dev/null +++ b/tests/lua/doc/manual.html @@ -0,0 +1,10507 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html> + +<head> +<title>Lua 5.2 Reference Manual</title> +<link rel="stylesheet" type="text/css" href="lua.css"> +<link rel="stylesheet" type="text/css" href="manual.css"> +<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1"> +</head> + +<body> + +<hr> +<h1> +<a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a> +Lua 5.2 Reference Manual +</h1> + +by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes +<p> +<small> +Copyright © 2011–2013 Lua.org, PUC-Rio. +Freely available under the terms of the +<a href="http://www.lua.org/license.html">Lua license</a>. +</small> +<hr> +<p> + +<a href="contents.html#contents">contents</A> +· +<a href="contents.html#index">index</A> + +<!-- ====================================================================== --> +<p> + +<!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ --> + + + + +<h1>1 – <a name="1">Introduction</a></h1> + +<p> +Lua is an extension programming language designed to support +general procedural programming with data description +facilities. +It also offers good support for object-oriented programming, +functional programming, and data-driven programming. +Lua is intended to be used as a powerful, lightweight, +embeddable scripting language for any program that needs one. +Lua is implemented as a library, written in <em>clean C</em>, +the common subset of Standard C and C++. + + +<p> +Being an extension language, Lua has no notion of a "main" program: +it only works <em>embedded</em> in a host client, +called the <em>embedding program</em> or simply the <em>host</em>. +The host program can invoke functions to execute a piece of Lua code, +can write and read Lua variables, +and can register C functions to be called by Lua code. +Through the use of C functions, Lua can be augmented to cope with +a wide range of different domains, +thus creating customized programming languages sharing a syntactical framework. +The Lua distribution includes a sample host program called <code>lua</code>, +which uses the Lua library to offer a complete, standalone Lua interpreter, +for interactive or batch use. + + +<p> +Lua is free software, +and is provided as usual with no guarantees, +as stated in its license. +The implementation described in this manual is available +at Lua's official web site, <code>www.lua.org</code>. + + +<p> +Like any other reference manual, +this document is dry in places. +For a discussion of the decisions behind the design of Lua, +see the technical papers available at Lua's web site. +For a detailed introduction to programming in Lua, +see Roberto's book, <em>Programming in Lua</em>. + + + +<h1>2 – <a name="2">Basic Concepts</a></h1> + +<p> +This section describes the basic concepts of the language. + + + +<h2>2.1 – <a name="2.1">Values and Types</a></h2> + +<p> +Lua is a <em>dynamically typed language</em>. +This means that +variables do not have types; only values do. +There are no type definitions in the language. +All values carry their own type. + + +<p> +All values in Lua are <em>first-class values</em>. +This means that all values can be stored in variables, +passed as arguments to other functions, and returned as results. + + +<p> +There are eight basic types in Lua: +<em>nil</em>, <em>boolean</em>, <em>number</em>, +<em>string</em>, <em>function</em>, <em>userdata</em>, +<em>thread</em>, and <em>table</em>. +<em>Nil</em> is the type of the value <b>nil</b>, +whose main property is to be different from any other value; +it usually represents the absence of a useful value. +<em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>. +Both <b>nil</b> and <b>false</b> make a condition false; +any other value makes it true. +<em>Number</em> 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 <code>luaconf.h</code>.) +<em>String</em> represents immutable sequences of bytes. + +Lua is 8-bit clean: +strings can contain any 8-bit value, +including embedded zeros ('<code>\0</code>'). + + +<p> +Lua can call (and manipulate) functions written in Lua and +functions written in C +(see <a href="#3.4.9">§3.4.9</a>). + + +<p> +The type <em>userdata</em> 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. +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. +Userdata has no predefined operations in Lua, +except assignment and identity test. +By using <em>metatables</em>, +the programmer can define operations for full userdata values +(see <a href="#2.4">§2.4</a>). +Userdata values cannot be created or modified in Lua, +only through the C API. +This guarantees the integrity of data owned by the host program. + + +<p> +The type <em>thread</em> represents independent threads of execution +and it is used to implement coroutines (see <a href="#2.6">§2.6</a>). +Do not confuse Lua threads with operating-system threads. +Lua supports coroutines on all systems, +even those that do not support threads. + + +<p> +The type <em>table</em> implements associative arrays, +that is, arrays that can be indexed not only with numbers, +but with any Lua value except <b>nil</b> and NaN +(<em>Not a Number</em>, a special numeric value used to represent +undefined or unrepresentable results, such as <code>0/0</code>). +Tables can be <em>heterogeneous</em>; +that is, they can contain values of all types (except <b>nil</b>). +Any key with value <b>nil</b> is not considered part of the table. +Conversely, any key that is not part of a table has +an associated value <b>nil</b>. + + +<p> +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 <code>a.name</code> as syntactic sugar for <code>a["name"]</code>. +There are several convenient ways to create tables in Lua +(see <a href="#3.4.8">§3.4.8</a>). + + +<p> +We use the term <em>sequence</em> to denote a table where +the set of all positive numeric keys is equal to <em>{1..n}</em> +for some integer <em>n</em>, +which is called the length of the sequence (see <a href="#3.4.6">§3.4.6</a>). + + +<p> +Like indices, +the values of table fields can be of any type. +In particular, +because functions are first-class values, +table fields can contain functions. +Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">§3.4.10</a>). + + +<p> +The indexing of tables follows +the definition of raw equality in the language. +The expressions <code>a[i]</code> and <code>a[j]</code> +denote the same table element +if and only if <code>i</code> and <code>j</code> are raw equal +(that is, equal without metamethods). + + +<p> +Tables, functions, threads, and (full) userdata values are <em>objects</em>: +variables do not actually <em>contain</em> these values, +only <em>references</em> to them. +Assignment, parameter passing, and function returns +always manipulate references to such values; +these operations do not imply any kind of copy. + + +<p> +The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type +of a given value (see <a href="#6.1">§6.1</a>). + + + + + +<h2>2.2 – <a name="2.2">Environments and the Global Environment</a></h2> + +<p> +As will be discussed in <a href="#3.2">§3.2</a> and <a href="#3.3.3">§3.3.3</a>, +any reference to a global name <code>var</code> is syntactically translated +to <code>_ENV.var</code>. +Moreover, every chunk is compiled in the scope of +an external local variable called <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>), +so <code>_ENV</code> itself is never a global name in a chunk. + + +<p> +Despite the existence of this external <code>_ENV</code> variable and +the translation of global names, +<code>_ENV</code> 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 <code>_ENV</code> that is +visible at that point in the program, +following the usual visibility rules of Lua (see <a href="#3.5">§3.5</a>). + + +<p> +Any table used as the value of <code>_ENV</code> is called an <em>environment</em>. + + +<p> +Lua keeps a distinguished environment called the <em>global environment</em>. +This value is kept at a special index in the C registry (see <a href="#4.5">§4.5</a>). +In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value. + + +<p> +When Lua compiles a chunk, +it initializes the value of its <code>_ENV</code> upvalue +with the global environment (see <a href="#pdf-load"><code>load</code></a>). +Therefore, by default, +global variables in Lua code refer to entries in the global environment. +Moreover, all standard libraries are loaded in the global environment +and several functions there operate on that environment. +You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>) +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.) + + +<p> +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 <code>_ENV</code> variable. +Moreover, the variable <a href="#pdf-_G"><code>_G</code></a> +(which is stored in the original global environment) +is never updated by Lua. + + + + + +<h2>2.3 – <a name="2.3">Error Handling</a></h2> + +<p> +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 <a href="#lua_pcall"><code>lua_pcall</code></a>). +Whenever an error occurs during +the compilation or execution of a Lua chunk, +control returns to the host, +which can take appropriate measures +(such as printing an error message). + + +<p> +Lua code can explicitly generate an error by calling the +<a href="#pdf-error"><code>error</code></a> function. +If you need to catch errors in Lua, +you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a> +to call a given function in <em>protected mode</em>. + + +<p> +Whenever there is an error, +an <em>error object</em> (also called an <em>error message</em>) +is propagated with information about the error. +Lua itself only generates errors where the error object is a string, +but programs may generate errors with +any value for the error object. + + +<p> +When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>, +you may give a <em>message handler</em> +to be called in case of errors. +This function is called with the original error message +and returns a new error message. +It is called before the error unwinds the stack, +so that it can gather more information about the error, +for instance by inspecting the stack and creating a stack traceback. +This message handler is still protected by the protected call; +so, an error inside the message handler +will call the message handler again. +If this loop goes on, Lua breaks it and returns an appropriate message. + + + + + +<h2>2.4 – <a name="2.4">Metatables and Metamethods</a></h2> + +<p> +Every value in Lua can have a <em>metatable</em>. +This <em>metatable</em> is an ordinary Lua table +that defines the behavior of the original value +under certain special operations. +You can change several aspects of the behavior +of operations over a value by setting specific fields in its metatable. +For instance, when a non-numeric value is the operand of an addition, +Lua checks for a function in the field "<code>__add</code>" of the value's metatable. +If it finds one, +Lua calls this function to perform the addition. + + +<p> +The keys in a metatable are derived from the <em>event</em> names; +the corresponding values are called <em>metamethods</em>. +In the previous example, the event is <code>"add"</code> +and the metamethod is the function that performs the addition. + + +<p> +You can query the metatable of any value +using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function. + + +<p> +You can replace the metatable of tables +using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> 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. + + +<p> +Tables and full userdata have individual metatables +(although multiple tables and userdata can share their metatables). +Values of all other types share one single metatable per type; +that is, there is one single metatable for all numbers, +one for all strings, etc. +By default, a value has no metatable, +but the string library sets a metatable for the string type (see <a href="#6.4">§6.4</a>). + + +<p> +A metatable controls how an object behaves in arithmetic operations, +order comparisons, concatenation, length operation, 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. + + +<p> +Metatables control the operations listed next. +Each operation is identified by its corresponding name. +The key for each operation is a string with its name prefixed by +two underscores, '<code>__</code>'; +for instance, the key for operation "add" is the +string "<code>__add</code>". + + +<p> +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 +(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.) +are described in <a href="#6.1">§6.1</a>. +In particular, to retrieve the metamethod of a given object, +we use the expression + +<pre> + metatable(obj)[event] +</pre><p> +This should be read as + +<pre> + rawget(getmetatable(obj) or {}, event) +</pre><p> +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 <b>nil</b>). + + +<p> +For the unary <code>-</code> and <code>#</code> 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.) + + + +<ul> + +<li><b>"add": </b> +the <code>+</code> operation. + + + +<p> +The function <code>getbinhandler</code> 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. + +<pre> + function getbinhandler (op1, op2, event) + return metatable(op1)[event] or metatable(op2)[event] + end +</pre><p> +By using this function, +the behavior of the <code>op1 + op2</code> is + +<pre> + 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 +</pre><p> +</li> + +<li><b>"sub": </b> +the <code>-</code> operation. + +Behavior similar to the "add" operation. +</li> + +<li><b>"mul": </b> +the <code>*</code> operation. + +Behavior similar to the "add" operation. +</li> + +<li><b>"div": </b> +the <code>/</code> operation. + +Behavior similar to the "add" operation. +</li> + +<li><b>"mod": </b> +the <code>%</code> operation. + +Behavior similar to the "add" operation, +with the operation +<code>o1 - floor(o1/o2)*o2</code> as the primitive operation. +</li> + +<li><b>"pow": </b> +the <code>^</code> (exponentiation) operation. + +Behavior similar to the "add" operation, +with the function <code>pow</code> (from the C math library) +as the primitive operation. +</li> + +<li><b>"unm": </b> +the unary <code>-</code> operation. + + +<pre> + 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 +</pre><p> +</li> + +<li><b>"concat": </b> +the <code>..</code> (concatenation) operation. + + +<pre> + 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 +</pre><p> +</li> + +<li><b>"len": </b> +the <code>#</code> operation. + + +<pre> + 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 +</pre><p> +See <a href="#3.4.6">§3.4.6</a> for a description of the length of a table. +</li> + +<li><b>"eq": </b> +the <code>==</code> operation. + +The function <code>getequalhandler</code> 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. + +<pre> + 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 +</pre><p> +The "eq" event is defined as follows: + +<pre> + 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 +</pre><p> +Note that the result is always a boolean. +</li> + +<li><b>"lt": </b> +the <code><</code> operation. + + +<pre> + 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 +</pre><p> +Note that the result is always a boolean. +</li> + +<li><b>"le": </b> +the <code><=</code> operation. + + +<pre> + 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 +</pre><p> +Note that, in the absence of a "le" metamethod, +Lua tries the "lt", assuming that <code>a <= b</code> is +equivalent to <code>not (b < a)</code>. + + +<p> +As with the other comparison operators, +the result is always a boolean. +</li> + +<li><b>"index": </b> +The indexing access <code>table[key]</code>. +Note that the metamethod is tried only +when <code>key</code> is not present in <code>table</code>. +(When <code>table</code> is not a table, +no key is ever present, +so the metamethod is always tried.) + + +<pre> + 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 +</pre><p> +</li> + +<li><b>"newindex": </b> +The indexing assignment <code>table[key] = value</code>. +Note that the metamethod is tried only +when <code>key</code> is not present in <code>table</code>. + + +<pre> + 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 +</pre><p> +</li> + +<li><b>"call": </b> +called when Lua calls a value. + + +<pre> + 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 +</pre><p> +</li> + +</ul> + + + + +<h2>2.5 – <a name="2.5">Garbage Collection</a></h2> + +<p> +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. +Lua manages memory automatically by running +a <em>garbage collector</em> to collect all <em>dead objects</em> +(that is, objects that are no longer accessible from Lua). +All memory used by Lua is subject to automatic management: +strings, tables, userdata, functions, threads, internal structures, etc. + + +<p> +Lua implements an incremental mark-and-sweep collector. +It uses two numbers to control its garbage-collection cycles: +the <em>garbage-collector pause</em> and +the <em>garbage-collector step multiplier</em>. +Both use percentage points as units +(e.g., a value of 100 means an internal value of 1). + + +<p> +The garbage-collector pause +controls how long the collector waits before starting a new cycle. +Larger values make the collector less aggressive. +Values smaller than 100 mean the collector will not wait to +start a new cycle. +A value of 200 means that the collector waits for the total memory in use +to double before starting a new cycle. + + +<p> +The garbage-collector step multiplier +controls the relative speed of the collector relative to +memory allocation. +Larger values make the collector more aggressive but also increase +the size of each incremental step. +Values smaller than 100 make the collector too slow and +can result in the collector never finishing a cycle. +The default is 200, +which means that the collector runs at "twice" +the speed of memory allocation. + + +<p> +If you set the step multiplier to a very large number +(larger than 10% of the maximum number of +bytes that the program may use), +the collector behaves like a stop-the-world collector. +If you then set the pause to 200, +the collector behaves as in old Lua versions, +doing a complete collection every time Lua doubles its +memory usage. + + +<p> +You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C +or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua. +You can also use these functions to control +the collector directly (e.g., stop and restart it). + + +<p> +As an experimental feature in Lua 5.2, +you can change the collector's operation mode +from incremental to <em>generational</em>. +A <em>generational collector</em> 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. + + + +<h3>2.5.1 – <a name="2.5.1">Garbage-Collection Metamethods</a></h3> + +<p> +You can set garbage-collector metamethods for tables +and, using the C API, +for full userdata (see <a href="#2.4">§2.4</a>). +These metamethods are also called <em>finalizers</em>. +Finalizers allow you to coordinate Lua's garbage collection +with external resource management +(such as closing files, network or database connections, +or freeing your own memory). + + +<p> +For an object (table or userdata) to be finalized when collected, +you must <em>mark</em> it for finalization. + +You mark an object for finalization when you set its metatable +and the metatable has a field indexed by the string "<code>__gc</code>". +Note that if you set a metatable without a <code>__gc</code> 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 <code>__gc</code> field of its metatable. + + +<p> +When a marked object becomes garbage, +it is not collected immediately by the garbage collector. +Instead, Lua puts it in a list. +After the collection, +Lua does the equivalent of the following function +for each object in that list: + +<pre> + function gc_event (obj) + local h = metatable(obj).__gc + if type(h) == "function" then + h(obj) + end + end +</pre> + +<p> +At the end of each garbage-collection cycle, +the finalizers for objects are called in +the reverse order that they were marked for collection, +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. +The execution of each finalizer may occur at any point during +the execution of the regular code. + + +<p> +Because the object being collected must still be used by the finalizer, +it (and other objects accessible only through it) +must be <em>resurrected</em> 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. +In any case, +the object memory is freed only when it becomes completely inaccessible; +its finalizer will never be called twice. + + +<p> +When you close a state (see <a href="#lua_close"><code>lua_close</code></a>), +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. + + + + + +<h3>2.5.2 – <a name="2.5.2">Weak Tables</a></h3> + +<p> +A <em>weak table</em> is a table whose elements are +<em>weak references</em>. +A weak reference is ignored by the garbage collector. +In other words, +if the only references to an object are weak references, +then the garbage collector will collect that object. + + +<p> +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 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, +the whole pair is removed from the table. +The weakness of a table is controlled by the +<code>__mode</code> field of its metatable. +If the <code>__mode</code> field is a string containing the character '<code>k</code>', +the keys in the table are weak. +If <code>__mode</code> contains '<code>v</code>', +the values in the table are weak. + + +<p> +A table with weak keys and strong values +is also called an <em>ephemeron table</em>. +In an ephemeron table, +a value is considered reachable only if its key is reachable. +In particular, +if the only reference to a key comes through its value, +the pair is removed. + + +<p> +Any change in the weakness of a table may take effect only +at the next collect cycle. +In particular, if you change the weakness to a stronger mode, +Lua may still collect some items from that table +before the change takes effect. + + +<p> +Only objects that have an explicit construction +are removed from weak tables. +Values, such as numbers and light C functions, +are not subject to garbage collection, +and therefore are not removed from weak tables +(unless its associated value is collected). +Although strings are subject to garbage collection, +they do not have an explicit construction, +and therefore are not removed from weak tables. + + +<p> +Resurrected objects +(that is, objects being finalized +and objects accessible only through objects being finalized) +have a special behavior in weak tables. +They are removed from weak values before running their finalizers, +but are removed from weak keys only in the next collection +after running their finalizers, when such objects are actually freed. +This behavior allows the finalizer to access properties +associated with the object through weak tables. + + +<p> +If a weak table is among the resurrected objects in a collection cycle, +it may not be properly cleared until the next cycle. + + + + + + + +<h2>2.6 – <a name="2.6">Coroutines</a></h2> + +<p> +Lua supports coroutines, +also called <em>collaborative multithreading</em>. +A coroutine in Lua represents an independent thread of execution. +Unlike threads in multithread systems, however, +a coroutine only suspends its execution by explicitly calling +a yield |