10425 lines · 297.2 KB · HTML
RawDownload
<!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 &copy; 2011&ndash;2012 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>&middot;<a href="contents.html#index">index</A> <!-- ====================================================================== --><p> <!-- $Id: manual.of,v 1.99 2012/06/08 15:30:20 roberto Exp $ -->    <h1>1 &ndash; <a name="1">Introduction</a></h1> <p>Lua is an extension programming language designed to supportgeneral procedural programming with data descriptionfacilities.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&nbsp;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&nbsp;functions to be called by Lua code.Through the use of C&nbsp;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 &ndash; <a name="2">Basic Concepts</a></h1> <p>This section describes the basic concepts of the language.   <h2>2.1 &ndash; <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 real (double-precision floating-point) numbers.Operations on numbers follow the same rules ofthe underlying C&nbsp;implementation,which, in turn, usually follows the IEEE 754 standard.(It is easy to build Lua interpreters that use otherinternal 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 andfunctions written in C(see <a href="#3.4.9">&sect;3.4.9</a>).  <p>The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data tobe 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">&sect;2.4</a>).Userdata values cannot be created or modified in Lua,only through the C&nbsp;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">&sect;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 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.8">&sect;3.4.8</a>).  <p>We use the term <em>sequence</em> to denote a table wherethe 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">&sect;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">&sect;3.4.10</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).  <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">&sect;6.1</a>).     <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2> <p>As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,any reference to a global name <code>var</code> is syntactically translatedto <code>_ENV.var</code>.Moreover, every chunk is compiled in the scope ofan external local variable called <code>_ENV</code> (see <a href="#3.3.2">&sect;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 andthe 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 isvisible at that point in the program,following the usual visibility rules of Lua (see <a href="#3.5">&sect;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">&sect;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> upvaluewith 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 environmentand 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 valueof 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 &ndash; <a name="2.3">Error Handling</a></h2> <p>Because Lua is an embedded extension language,all Lua actions start from C&nbsp;code in the host programcalling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).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 where the error object is a string,but programs may generate errors withany 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 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, Lua breaks it and returns an appropriate message.     <h2>2.4 &ndash; <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);you must use the C&nbsp;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">&sect;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 calledwhen 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 bytwo underscores, '<code>__</code>';for instance, the key for operation "add" is thestring "<code>__add</code>".  <p>The semantics of these operations is better explained by a Lua functiondescribing how the interpreter executes the operation.The code shown here in Lua is only illustrative;the real behavior is hard coded in the interpreterand 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">&sect;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 presentin 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 handlerfor 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(&middot;&middot;&middot;)         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> 

Lines 1–500 of 10425.