⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 manual.html

📁 Lua 语言解释器源码
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><html><head><TITLE>Lua: 5.0 reference manual</TITLE></head><body BGCOLOR="#FFFFFF"><hr><h1><A HREF="http://www.lua.org/home.html"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>Lua 5.0 Reference Manual</h1>by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes<p><small><a HREF="http://www.lua.org/copyright.html">Copyright</a>&copy; 2003 Tecgraf, PUC-Rio.  All rights reserved.</small><hr><p><p><!-- ====================================================================== --><a name="1"><h1>1 - Introduction</h1></a><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-weightconfiguration 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&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.<p>The Lua distribution includes a stand-alone embedding program,<code>lua</code>, that uses the Lua library to offer a complete Lua interpreter.<p>Lua is free software,and is provided as usual with no guarantees,as stated in its copyright notice.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 papers below,which are available at Lua's web site.<ul><li>R.&nbsp;Ierusalimschy, L.&nbsp;H.&nbsp;de Figueiredo, and W.&nbsp;Celes.Lua---an extensible extension language.<em>Software: Practice &#038; Experience</em> <b>26</b> #6 (1996) 635-652.<li>L.&nbsp;H.&nbsp;de Figueiredo, R.&nbsp;Ierusalimschy, and W.&nbsp;Celes.The design and implementation of a language for extending applications.<em>Proceedings of XXI Brazilian Seminar on Software and Hardware</em> (1994) 273-283.<li>L.&nbsp;H.&nbsp;de Figueiredo, R.&nbsp;Ierusalimschy, and W.&nbsp;Celes.Lua: an extensible embedded language.<em>Dr. Dobb's Journal</em> <b>21</b> #12 (Dec 1996) 26-33.<li>R.&nbsp;Ierusalimschy, L.&nbsp;H.&nbsp;de Figueiredo, and W.&nbsp;Celes.The evolution of an extension language: a history of Lua,<em>Proceedings of V Brazilian Symposium on Programming Languages</em> (2001) B-14-B-28.</ul><p>Lua means "moon" in Portuguese and is pronounced LOO-ah.<p><a name="language"><a name="2"><h1>2 - The Language</h1></a></a><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,in which{<em>a</em>}&nbsp;means 0 or more <em>a</em>'s, and[<em>a</em>]&nbsp;means an optional <em>a</em>.Non-terminals are shown in <em>italics</em>,keywords are shown in <b>bold</b>,and other terminal symbols are shown in <code>typewriter</code> font,enclosed in single quotes.<p><a name="lexical"><a name="2.1"><h2>2.1 - Lexical Conventions</h2></a></a><p><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 identifiers 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.)<p>The following <em>keywords</em> are reservedand cannot be used as identifiers:<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 identifiers.As a convention, identifiers starting with an underscore followed byuppercase letters (such as <code>_VERSION</code>)are reserved for internal variables used by Lua.<p>The following strings denote other tokens:<PRE>       +     -     *     /     ^     =       ~=    &#060;=    >=    &#060;     >     ==       (     )     {     }     [     ]       ;     :     ,     .     ..    ...</PRE><p><em>Literal strings</em>can be delimited by matching single or double quotes,and can contain the following C-like escape sequences:<ul><li><b><code>\a</code></b> --- bell<li><b><code>\b</code></b> --- backspace<li><b><code>\f</code></b> --- form feed<li><b><code>\n</code></b> --- newline<li><b><code>\r</code></b> --- carriage return<li><b><code>\t</code></b> --- horizontal tab<li><b><code>\v</code></b> --- vertical tab<li><b><code>\\</code></b> --- backslash<li><b><code>\"</code></b> --- quotation mark<li><b><code>\'</code></b> --- apostrophe<li><b><code>\[</code></b> --- left square bracket<li><b><code>\]</code></b> --- right square bracket</ul>Moreover, a `<code>\</code><em>newline</em>&acute;(that is, a backslash followed by a real newline)results in a newline in the string.A character in a string may also be specified by its numerical valueusing the escape sequence `<code>\</code><em>ddd</em>&acute;,where <em>ddd</em> is a sequence of up to three decimal digits.Strings in Lua may contain any 8-bit value, including embedded zeros,which can be specified as `<code>\0</code>&acute;.<p>Literal strings can also be delimited by matching double square brackets<code>[[</code> &middot; &middot; &middot; <code>]]</code>.Literals in this bracketed form may run for several lines,may contain nested <code>[[</code> &middot; &middot; &middot; <code>]]</code> pairs,and do not interpret any escape sequences.For convenience,when the opening `<code>[[</code>&acute; 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>&acute; is coded as&nbsp;97,newline is coded as&nbsp;10, and `<code>1</code>&acute; is coded as&nbsp;49),the four literals below denote the same string:<PRE>      (1)   "alo\n123\""      (2)   '\97lo\10\04923"'      (3)   [[alo            123"]]      (4)   [[            alo            123"]]</PRE><p><em>Numerical constants</em> may be written with an optional decimal partand an optional decimal exponent.Examples of valid numerical constants are<PRE>       3     3.0     3.1416  314.16e-2   0.31416E1</PRE><p><em>Comments</em> start anywhere outside a string with adouble hyphen (<code>--</code>).If the text immediately after <code>--</code> is different from <code>[[</code>,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 <code>]]</code>.Long comments may run for several linesand may contain nested <code>[[</code> &middot; &middot; &middot; <code>]]</code> pairs.<p>For convenience,the first line of a chunk is skipped if it starts with <code>#</code>.This facility allows the use of Lua as a script interpreterin Unix systems (see <a href="#lua-sa">6</a>).<p><a name="TypesSec"><a name="2.2"><h2>2.2 - Values and Types</h2></a></a><p>Lua is a <em>dynamically typed language</em>.That means thatvariables do not have types; only values do.There are no type definitions in the language.All values carry their own type.<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;usually it represents the absence of a useful value.<em>Boolean</em> is the type of the values <B>false</B> and <B>true</B>.In Lua, 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.)<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="#lexical">2.1</a>).<p>Functions are <em>first-class values</em> in Lua.That means that functions can be stored in variables,passed as arguments to other functions, and returned as results.Lua can call (and manipulate) functions written in Lua andfunctions written in C(see <a href="#functioncall">2.5.7</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="#metatable">2.8</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.<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>).Moreover,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="#tableconstructor">2.5.6</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="#func-def">2.5.8</a>).<p>Tables, functions, and 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 <code>type</code> returns a string describing the typeof a given value (see <a href="#pdf-type">5.1</a>).<p><a name="coercion"><a name="2.2.1"><h3>2.2.1 - Coercion</h3></a></a><p>Lua provides automatic conversion betweenstring and number values at run time.Any arithmetic operation applied to a string tries to convertthat string to a number, following the usual 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 of how numbers are converted to strings,use the <code>format</code> function from the string library (see <a href="#format">5.3</a>).<p><a name="variables"><a name="2.3"><h2>2.3 - Variables</h2></a></a><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 formal parameter of a function,which is a particular form of local variable):<pre>	var ::= Name</pre>Variables are assumed to be global unless explicitly declared local(see <a href="#localvar">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="#visibility">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>&acute; exp `<b>]</b>&acute;</pre>The first expression (<em>prefixexp</em>)should result in a table value;the second expression (<em>exp</em>)identifies a specific entry inside that table.The expression denoting the table to be indexed has a restricted syntax;see <a href="#expressions">2.5</a> for details.<p>The syntax <code>var.NAME</code> is just syntactic sugar for<code>var["NAME"]</code>:<pre>	var ::= prefixexp `<b>.</b>&acute; Name</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="#metatable">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>All global variables live as fields in ordinary Lua tables,called <em>environment tables</em> or simply <em>environments</em>.Functions written in C and exported to Lua (<em>C functions</em>)all share a common <em>global environment</em>.Each function written in Lua (a <em>Lua function</em>)has its own reference to an environment,so that all global variables in that functionwill refer to that environment table.When a function is created,it inherits the environment from the function that created it.To change or get the environment table of a Lua function,you call <code>setfenv</code> or <code>getfenv</code> (see <a href="#setfenv">5.1</a>).<p>An access to a global variable <code>x</code>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -