📄 manual.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Lua 5.1 Reference Manual</title><link rel="stylesheet" href="lua.css"><link rel="stylesheet" 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.1 Reference Manual</h1>by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes<p><small>Copyright © 2006-2008 Lua.org, PUC-Rio.Freely available under the terms of the<a href="http://www.lua.org/license.html#5">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.45 2008/01/19 00:17:30 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.It also offers good support for object-oriented programming,functional programming, and data-driven programming.Lua is intended to be used as a powerful, light-weightscripting language for any program that needs one.Lua is implemented as a library, written in <em>clean</em> C(that is, in the common subset of ANSI 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>.This 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, stand-alone Lua interpreter.<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 (Second Edition)</em>.<h1>2 - <a name="2">The Language</a></h1><p>This section describes the lexis, the syntax, and the semantics of Lua.In other words,this section describeswhich tokens are valid,how they can be combined,and what their combinations mean.<p>The language constructs will be explained using the usual extended BNF notation,in which{<em>a</em>} means 0 or more <em>a</em>'s, and[<em>a</em>] means an optional <em>a</em>.Non-terminals are shown like non-terminal,keywords are shown like <b>kword</b>,and other terminal symbols are shown like `<b>=</b>´.The complete syntax of Lua can be found at the end of this manual.<h2>2.1 - <a name="2.1">Lexical Conventions</a></h2><p><em>Names</em>(also called <em>identifiers</em>)in Lua can be any string of letters,digits, and underscores,not beginning with a digit.This coincides with the definition of names in most languages.(The definition of letter depends on the current locale:any character considered alphabetic by the current localecan be used in an identifier.)Identifiers are used to name variables and table fields.<p>The following <em>keywords</em> are reservedand cannot be used as names:<pre> and break do else elseif end false for function if in local nil not or repeat return then true until while</pre><p>Lua is a case-sensitive language:<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>are two different, valid names.As a convention, names starting with an underscore followed byuppercase letters (such as <code>_VERSION</code>)are reserved for internal global variables used by Lua.<p>The following strings denote other tokens:<pre> + - * / % ^ # == ~= <= >= < > = ( ) { } [ ] ; : , . .. ...</pre><p><em>Literal strings</em>can be delimited by matching single or double quotes,and can contain the following C-like escape sequences:'<code>\a</code>' (bell),'<code>\b</code>' (backspace),'<code>\f</code>' (form feed),'<code>\n</code>' (newline),'<code>\r</code>' (carriage return),'<code>\t</code>' (horizontal tab),'<code>\v</code>' (vertical tab),'<code>\\</code>' (backslash),'<code>\"</code>' (quotation mark [double quote]),and '<code>\'</code>' (apostrophe [single quote]).Moreover, a backslash followed by a real newlineresults in a newline in the string.A character in a string may also be specified by its numerical valueusing the escape sequence <code>\<em>ddd</em></code>,where <em>ddd</em> is a sequence of up to three decimal digits.(Note that if a numerical escape is to be followed by a digit,it must be expressed using exactly three digits.)Strings in Lua may contain any 8-bit value, including embedded zeros,which can be specified as '<code>\0</code>'.<p>To put a double (single) quote, a newline, a backslash,a carriage return,or an embedded zeroinside a literal string enclosed by double (single) quotesyou must use an escape sequence.Any other character may be directly inserted into the literal.(Some control characters may cause problems for the file system,but Lua has no problem with them.)<p>Literal strings can also be defined using a long formatenclosed by <em>long brackets</em>.We define an <em>opening long bracket of level <em>n</em></em> as an openingsquare bracket followed by <em>n</em> equal signs followed by anotheropening square bracket.So, an opening long bracket of level 0 is written as <code>[[</code>,an opening long bracket of level 1 is written as <code>[=[</code>,and so on.A <em>closing long bracket</em> is defined similarly;for instance, a closing long bracket of level 4 is written as <code>]====]</code>.A long string starts with an opening long bracket of any level andends at the first closing long bracket of the same level.Literals in this bracketed form may run for several lines,do not interpret any escape sequences,and ignore long brackets of any other level.They may contain anything except a closing bracket of the proper level.<p>For convenience,when the opening long bracket is immediately followed by a newline,the newline is not included in the string.As an example, in a system using ASCII(in which '<code>a</code>' is coded as 97,newline is coded as 10, and '<code>1</code>' is coded as 49),the five literals below denote the same string:<pre> a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==]</pre><p>A <em>numerical constant</em> may be written with an optional decimal partand an optional decimal exponent.Lua also accepts integer hexadecimal constants,by prefixing them with <code>0x</code>.Examples of valid numerical constants are<pre> 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56</pre><p>A <em>comment</em> starts with a double hyphen (<code>--</code>)anywhere outside a string.If the text immediately after <code>--</code> is not an opening long bracket,the comment is a <em>short comment</em>,which runs until the end of the line.Otherwise, it is a <em>long comment</em>,which runs until the corresponding closing long bracket.Long comments are frequently used to disable code temporarily.<h2>2.2 - <a name="2.2">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.(It is easy to build Lua interpreters that use otherinternal representations for numbers,such as single-precision float or long integers;see file <code>luaconf.h</code>.)<em>String</em> represents arrays of characters.Lua is 8-bit clean:strings may contain any 8-bit character,including embedded zeros ('<code>\0</code>') (see <a href="#2.1">§2.1</a>).<p>Lua can call (and manipulate) functions written in Lua andfunctions written in C(see <a href="#2.5.8">§2.5.8</a>).<p>The type <em>userdata</em> is provided to allow arbitrary C data tobe stored in Lua variables.This type corresponds to a block of raw memoryand has no pre-defined operations in Lua,except assignment and identity test.However, by using <em>metatables</em>,the programmer can define operations for userdata values(see <a href="#2.8">§2.8</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.11">§2.11</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 value (except <b>nil</b>).Tables can be <em>heterogeneous</em>;that is, they can contain values of all types (except <b>nil</b>).Tables are the sole data structuring mechanism in Lua;they may be used to represent ordinary arrays,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="#2.5.7">§2.5.7</a>).<p>Like indices,the value of a table field can be of any type (except <b>nil</b>).In particular,because functions are first-class values,table fields may contain functions.Thus tables may also carry <em>methods</em> (see <a href="#2.5.9">§2.5.9</a>).<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.<h3>2.2.1 - <a name="2.2.1">Coercion</a></h3><p>Lua provides automatic conversion betweenstring and number values at run time.Any arithmetic operation applied to a string tries to convertthis string to a number, following the usual conversion rules.Conversely, whenever a number is used where a string is expected,the number is converted to a string, in a reasonable format.For complete control over how numbers are converted to strings,use the <code>format</code> function from the string library(see <a href="#pdf-string.format"><code>string.format</code></a>).<h2>2.3 - <a name="2.3">Variables</a></h2><p>Variables are places that store values.There are three kinds of variables in Lua:global variables, local variables, and table fields.<p>A single name can denote a global variable or a local variable(or a function's formal parameter,which is a particular kind of local variable):<pre> var ::= Name</pre><p>Name denotes identifiers, as defined in <a href="#2.1">§2.1</a>.<p>Any variable is assumed to be global unless explicitly declaredas a local (see <a href="#2.4.7">§2.4.7</a>).Local variables are <em>lexically scoped</em>:local variables can be freely accessed by functionsdefined inside their scope (see <a href="#2.6">§2.6</a>).<p>Before the first assignment to a variable, its value is <b>nil</b>.<p>Square brackets are used to index a table:<pre> var ::= prefixexp `<b>[</b>´ exp `<b>]</b>´</pre><p>The meaning of accesses to global variables and table fields can be changed via metatables.An access to an indexed variable <code>t[i]</code> is equivalent toa call <code>gettable_event(t,i)</code>.(See <a href="#2.8">§2.8</a> for a complete description of the<code>gettable_event</code> function.This function is not defined or callable in Lua.We use it here only for explanatory purposes.)<p>The syntax <code>var.Name</code> is just syntactic sugar for<code>var["Name"]</code>:<pre> var ::= prefixexp `<b>.</b>´ Name</pre>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -