<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head><title>Lua 5.3 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.3 Reference Manual</h1> by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes<p><small>Copyright © 2015 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.146 2015/01/06 11:23:01 roberto Exp $ --> <h1>1 – <a name="1">Introduction</a></h1> <p>Lua is an extension programming language designed to supportgeneral procedural programming with data descriptionfacilities.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.Lua is implemented as a library, written in <em>clean C</em>,the common subset of Standard C and C++. <p>As 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 witha 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 availableat 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 thatvariables 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 bothinteger numbers and real (floating-point) numbers.<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>').Lua is also encoding-agnostic;it makes no assumptions about the contents of a string. <p>The type <em>number</em> uses two internal representations,one called <em>integer</em> and the other called <em>float</em>.Lua has explicit rules about when each representation is used,but it also converts between them automatically as needed (see <a href="#3.4.3">§3.4.3</a>).Therefore,the programmer may choose to mostly ignore the differencebetween integers and floatsor 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 ituses 32-bit integers and/or single-precision (32-bit) floats.The option with 32 bits for both integers and floats is particularly attractivefor small machines and embedded systems.(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.) <p>Lua can call (and manipulate) functions written in Lua andfunctions written in C (see <a href="#3.4.10">§3.4.10</a>).Both are represented by the type <em>function</em>. <p>The type <em>userdata</em> is provided to allow arbitrary C data tobe stored in Lua variables.A userdata value represents a block of raw memory.There are two kinds of userdata:<em>full userdata</em>,which is an object with a block of memory managed by Lua,and <em>light userdata</em>,which is simply a C pointer value.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 executionand it is used to implement coroutines (see <a href="#2.6">§2.6</a>).Lua threads are not related to operating-system threads.Lua supports coroutines on all systems,even those that do not support threads natively. <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> is a special numeric value used to representundefined 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 hasan 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 byproviding <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.9">§3.4.9</a>). <p>We use the term <em>sequence</em> to denote a table wherethe set of all positive numeric keys is equal to {1..<em>n</em>}for some non-negative integer <em>n</em>,which is called the length of the sequence (see <a href="#3.4.7">§3.4.7</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.11">§3.4.11</a>). <p>The indexing of tables followsthe definition of raw equality in the language.The expressions <code>a[i]</code> and <code>a[j]</code>denote the same table elementif and only if <code>i</code> and <code>j</code> are raw equal(that is, equal without metamethods).In particular, floats with integral valuesare equal to their respective integers(e.g., <code>1.0 == 1</code>).To avoid ambiguities,any float with integral value used as a keyis converted to its respective integer.For instance, if you write <code>a[2.0] = true</code>,the actual key inserted into the table will be theinteger <code>2</code>.(On the other hand,2 and "<code>2</code>" are different Lua values and thereforedenote different table entries.) <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 returnsalways 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 typeof 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 free name(that is, a name not bound to any declaration) <code>var</code>is syntactically translated to <code>_ENV.var</code>.Moreover, every chunk is compiled in the scope ofan external local variable named <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>),so <code>_ENV</code> itself is never a free name in a chunk. <p>Despite the existence of this external <code>_ENV</code> variable andthe translation of free 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 free name uses the <code>_ENV</code> that isvisible 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 global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.(<a href="#pdf-_G"><code>_G</code></a> is never used internally.) <p>When Lua loads a chunk,the default value for its <code>_ENV</code> upvalueis the global environment (see <a href="#pdf-load"><code>load</code></a>).Therefore, by default,free names in Lua code refer to entries in the global environment(and, therefore, they are also called <em>global variables</em>).Moreover, all standard libraries are loaded in the global environmentand some 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 valueof its first upvalue.) <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 programcalling a function from the Lua library.(When you use Lua standalone,the <code>lua</code> application is the host program.)Whenever an error occurs duringthe 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 whose error object is a string,but programs may generate errors withany value as the error object.It is up to the Lua program or its host to handle such error objects. <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 messageand 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 handlerwill call the message handler again.If this loop goes on for too long,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 tablethat defines the behavior of the original valueunder certain special operations.You can change several aspects of the behaviorof 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 valueusing the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function. <p>You can replace the metatable of tablesusing 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 (<a href="#6.10">§6.10</a>));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 inarithmetic operations, bitwise operations,order comparisons, concatenation, length operation, calls, and indexing.A metatable also can define a function to be calledwhen a userdata or a table is garbage collected (<a href="#2.5">§2.5</a>). <p>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 bytwo underscores, '<code>__</code>';for instance, the key for operation "add" is thestring "<code>__add</code>".Note that queries for metamethods are always raw;the access to a metamethod does not invoke other metamethods.You can emulate how Lua queries a metamethod for an object <code>obj</code>with the following code: <pre> rawget(getmetatable(obj) or {}, "__" .. event_name)</pre> <p>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.) <ul> <li><b>"add": </b>the <code>+</code> operation. If any operand for an addition is not a number(nor a string coercible to a number),Lua will try to call a metamethod.First, Lua will check the first operand (even if it is valid).If that operand does not define a metamethod for the "<code>__add</code>" 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.</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.</li> <li><b>"pow": </b>the <code>^</code> (exponentiation) operation. Behavior similar to the "add" operation.</li> <li><b>"unm": </b>the <code>-</code> (unary minus) operation. Behavior similar to the "add" operation.</li>Lines 1–500 of 10789. Load more
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Lua 5.3 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.3 Reference Manual </h1> by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes <p> <small> Copyright © 2015 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.146 2015/01/06 11:23:01 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. 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. Lua is implemented as a library, written in <em>clean C</em>, the common subset of Standard C and C++. <p> As 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 both integer numbers and real (floating-point) numbers. <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>'). Lua is also encoding-agnostic; it makes no assumptions about the contents of a string. <p> The type <em>number</em> uses two internal representations, one called <em>integer</em> and the other called <em>float</em>. Lua has explicit rules about when each representation is used, but it also converts between them automatically as needed (see <a href="#3.4.3">§3.4.3</a>). 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 <code>LUA_32BITS</code> in file <code>luaconf.h</code>.) <p> Lua can call (and manipulate) functions written in Lua and functions written in C (see <a href="#3.4.10">§3.4.10</a>). Both are represented by the type <em>function</em>. <p> The type <em>userdata</em> is provided to allow arbitrary C data to be stored in Lua variables. A userdata value represents a block of raw memory. There are two kinds of userdata: <em>full userdata</em>, which is an object with a block of memory managed by Lua, and <em>light userdata</em>, which is simply a C pointer value. 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>). Lua threads are not related to operating-system threads. Lua supports coroutines on all systems, even those that do not support threads natively. <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> is 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.9">§3.4.9</a>). <p> We use the term <em>sequence</em> to denote a table where the set of all positive numeric keys is equal to {1..<em>n</em>} for some non-negative integer <em>n</em>, which is called the length of the sequence (see <a href="#3.4.7">§3.4.7</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.11">§3.4.11</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). In particular, floats with integral values are equal to their respective integers (e.g., <code>1.0 == 1</code>). To avoid ambiguities, any float with integral value used as a key is converted to its respective integer. For instance, if you write <code>a[2.0] = true</code>, the actual key inserted into the table will be the integer <code>2</code>. (On the other hand, 2 and "<code>2</code>" are different Lua values and therefore denote different table entries.) <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 free name (that is, a name not bound to any declaration) <code>var</code> is syntactically translated to <code>_ENV.var</code>. Moreover, every chunk is compiled in the scope of an external local variable named <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>), so <code>_ENV</code> itself is never a free name in a chunk. <p> Despite the existence of this external <code>_ENV</code> variable and the translation of free 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 free 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 global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value. (<a href="#pdf-_G"><code>_G</code></a> is never used internally.) <p> When Lua loads a chunk, the default value for its <code>_ENV</code> upvalue is the global environment (see <a href="#pdf-load"><code>load</code></a>). Therefore, by default, free names in Lua code refer to entries in the global environment (and, therefore, they are also called <em>global variables</em>). Moreover, all standard libraries are loaded in the global environment and some 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.) <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. (When you use Lua standalone, the <code>lua</code> application is the host program.) 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 whose error object is a string, but programs may generate errors with any value as the error object. It is up to the Lua program or its host to handle such error objects. <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 for too long, 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 (<a href="#6.10">§6.10</a>)); 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, 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 (<a href="#2.5">§2.5</a>). <p> 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, '<code>__</code>'; for instance, the key for operation "add" is the string "<code>__add</code>". Note that queries for metamethods are always raw; the access to a metamethod does not invoke other metamethods. You can emulate how Lua queries a metamethod for an object <code>obj</code> with the following code: <pre> rawget(getmetatable(obj) or {}, "__" .. event_name) </pre> <p> 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.) <ul> <li><b>"add": </b> the <code>+</code> operation. If any operand for an addition is not a number (nor a string coercible to a number), Lua will try to call a metamethod. First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for the "<code>__add</code>" 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. </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. </li> <li><b>"pow": </b> the <code>^</code> (exponentiation) operation. Behavior similar to the "add" operation. </li> <li><b>"unm": </b> the <code>-</code> (unary minus) operation. Behavior similar to the "add" operation. </li>