aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-11-18 12:39:34 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-11-18 12:39:34 -0200
commitf4d3bc52f486bb1f0d32c6240faffb0e63bbb8fe (patch)
treea3ee309c1a748c31ad096426ce2807a5fbb73f3a
parent18765d900e759713d9501e6434191c641f508e58 (diff)
downloadlua-f4d3bc52f486bb1f0d32c6240faffb0e63bbb8fe.tar.gz
lua-f4d3bc52f486bb1f0d32c6240faffb0e63bbb8fe.tar.bz2
lua-f4d3bc52f486bb1f0d32c6240faffb0e63bbb8fe.zip
towards 5.0 beta
-rw-r--r--manual.tex456
1 files changed, 293 insertions, 163 deletions
diff --git a/manual.tex b/manual.tex
index bd1f9464..0ae9459b 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.61 2002/08/13 20:00:51 roberto Exp roberto $ 1% $Id: manual.tex,v 1.63 2002/11/18 14:37:57 roberto Exp $
2%{[( 2%{[(
3 3
4\documentclass[11pt,twoside]{article} 4\documentclass[11pt,twoside]{article}
@@ -26,7 +26,7 @@
26\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} 26\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
27\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} 27\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
28\newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}} 28\newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}}
29\newcommand{\IndexTM}[1]{\index{#1 event@{``#1'' event}}\index{tag method!#1}} 29\newcommand{\IndexTM}[1]{\index{#1 event@{``#1'' event}}\index{metamethod!#1}}
30\newcommand{\Def}[1]{\emph{#1}\index{#1}} 30\newcommand{\Def}[1]{\emph{#1}\index{#1}}
31\newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}} 31\newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}}
32\newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}} 32\newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}}
@@ -36,7 +36,7 @@
36 36
37\newcommand{\ff}{$\bullet$\ } 37\newcommand{\ff}{$\bullet$\ }
38 38
39\newcommand{\Version}{5.0 (alpha)} 39\newcommand{\Version}{5.0 (beta)}
40 40
41% changes to bnf.sty by LHF 41% changes to bnf.sty by LHF
42\renewcommand{\Or}{$|$ } 42\renewcommand{\Or}{$|$ }
@@ -58,7 +58,7 @@
58\parindent=0pt 58\parindent=0pt
59\vglue1.5in 59\vglue1.5in
60{\LARGE\bf 60{\LARGE\bf
61The Programming Language Lua} 61The Lua Programming Language}
62\hfill 62\hfill
63\vskip4pt \hrule height 4pt width \hsize \vskip4pt 63\vskip4pt \hrule height 4pt width \hsize \vskip4pt
64\hfill 64\hfill
@@ -134,7 +134,7 @@ Waldemar Celes
134\tecgraf\ --- Computer Science Department --- PUC-Rio 134\tecgraf\ --- Computer Science Department --- PUC-Rio
135} 135}
136 136
137%\date{{\small \tt\$Date: 2002/08/13 20:00:51 $ $}} 137%\date{{\small \tt\$Date: 2002/11/18 14:37:57 $ $}}
138 138
139\maketitle 139\maketitle
140 140
@@ -272,8 +272,7 @@ This environment is initialized with a call from the embedding program to
272\verb|lua_open| and 272\verb|lua_open| and
273persists until a call to \verb|lua_close| 273persists until a call to \verb|lua_close|
274or the end of the embedding program. 274or the end of the embedding program.
275If necessary, 275The host program can create multiple independent global
276the host programmer can create multiple independent global
277environments, and freely switch between them \see{mangstate}. 276environments, and freely switch between them \see{mangstate}.
278 277
279The unit of execution of Lua is called a \Def{chunk}. 278The unit of execution of Lua is called a \Def{chunk}.
@@ -285,13 +284,12 @@ When a chunk is executed, first it is pre-compiled into opcodes for
285a virtual machine, 284a virtual machine,
286and then the compiled statements are executed 285and then the compiled statements are executed
287by an interpreter for the virtual machine. 286by an interpreter for the virtual machine.
288All modifications a chunk effects on the global environment persist 287All modifications a chunk makes to the global environment persist
289after the chunk ends. 288after the chunk ends.
290 289
291Chunks may also be pre-compiled into binary form and stored in files; 290Chunks may also be pre-compiled into binary form and stored in files;
292see program \IndexVerb{luac} for details. 291see program \IndexVerb{luac} for details.
293Text files with chunks and their binary pre-compiled forms 292Programs in source and compiled forms are interchangeable;
294are interchangeable;
295Lua automatically detects the file type and acts accordingly. 293Lua automatically detects the file type and acts accordingly.
296\index{pre-compilation} 294\index{pre-compilation}
297 295
@@ -315,8 +313,8 @@ There are seven \Index{basic types} in Lua:
315whose main property is to be different from any other value; 313whose main property is to be different from any other value;
316usually it represents the absence of a useful value. 314usually it represents the absence of a useful value.
317\emph{Boolean} is the type of the values \False{} and \True. 315\emph{Boolean} is the type of the values \False{} and \True.
318In Lua, both \nil{} and \False{} make a condition fails, 316In Lua, both \nil{} and \False{} make a condition false,
319and any other value makes it succeeds. 317and any other value makes it true.
320\emph{Number} represents real (double-precision floating-point) numbers. 318\emph{Number} represents real (double-precision floating-point) numbers.
321\emph{String} represents arrays of characters. 319\emph{String} represents arrays of characters.
322\index{eight-bit clean} 320\index{eight-bit clean}
@@ -331,8 +329,8 @@ Lua can call (and manipulate) functions written in Lua and
331functions written in C 329functions written in C
332\see{functioncall}. 330\see{functioncall}.
333 331
334The type \emph{userdata} is provided to allow the store of 332The type \emph{userdata} is provided to allow arbitrary C data to
335arbitrary C data in Lua variables. 333be stored in Lua variables.
336This type corresponds to a block of raw memory 334This type corresponds to a block of raw memory
337and has no pre-defined operations in Lua, 335and has no pre-defined operations in Lua,
338except assignment and identity test. 336except assignment and identity test.
@@ -367,7 +365,7 @@ So, tables may also carry \emph{methods} \see{func-def}.
367Tables, functions, and userdata values are \emph{objects}: 365Tables, functions, and userdata values are \emph{objects}:
368variables do not actually \emph{contain} these values, 366variables do not actually \emph{contain} these values,
369only \emph{references} to them. 367only \emph{references} to them.
370Assignment, parameter passing, and returns from functions 368Assignment, parameter passing, and function returns
371always manipulate references to these values, 369always manipulate references to these values,
372and do not imply any kind of copy. 370and do not imply any kind of copy.
373 371
@@ -377,7 +375,7 @@ of a given value \see{pdf-type}.
377 375
378\subsubsection{Metatables} 376\subsubsection{Metatables}
379 377
380Each table or userdata object in Lua may have a \Index{metatable}. 378Each table and userdata object in Lua may have a \Index{metatable}.
381 379
382You can change several aspects of the behavior 380You can change several aspects of the behavior
383of an object by setting specific fields in its metatable. 381of an object by setting specific fields in its metatable.
@@ -389,11 +387,11 @@ Lua calls that function to perform the addition.
389We call the keys in a metatable \Index{events}, 387We call the keys in a metatable \Index{events},
390and the values \Index{metamethods}. 388and the values \Index{metamethods}.
391In the previous example, \verb|"add"| is the event, 389In the previous example, \verb|"add"| is the event,
392and the metamethod is the function that performs the addition. 390and the function is the metamethod that performs the addition.
393 391
394A metatable controls how an object behaves in arithmetic operations, 392A metatable controls how an object behaves in arithmetic operations,
395order comparisons, concatenation, and indexing. 393order comparisons, concatenation, and indexing.
396A metatable can also defines a function to be called when a userdata 394A metatable can also define a function to be called when a userdata
397is garbage collected. 395is garbage collected.
398\See{metatable} gives a detailed description of which events you 396\See{metatable} gives a detailed description of which events you
399can control with metatables. 397can control with metatables.
@@ -499,7 +497,12 @@ A table with both weak keys and weak values allows the collection of
499both keys and values. 497both keys and values.
500In any case, if either the key or the value is collected, 498In any case, if either the key or the value is collected,
501the whole pair is removed from the table. 499the whole pair is removed from the table.
502The weakness of a table is set with the \verb|setmode| function. 500The weakness of a table is controled by the value of the
501\verb|__mode| field of its metatable.
502If the \verb|__mode| field is a string containing the \verb|k| character,
503the keys in the table are weak.
504If \verb|__mode| contains \verb|v|,
505the values in the table are weak.
503 506
504 507
505%------------------------------------------------------------------------------ 508%------------------------------------------------------------------------------
@@ -527,10 +530,10 @@ and cannot be used as identifiers:
527\index{reserved words} 530\index{reserved words}
528\begin{verbatim} 531\begin{verbatim}
529 and break do else elseif 532 and break do else elseif
530 end false for function global 533 end false for function if
531 if in local nil not 534 in local nil not or
532 or repeat return then true 535 repeat return then true until
533 until while 536 while
534\end{verbatim} 537\end{verbatim}
535 538
536Lua is a case-sensitive language: 539Lua is a case-sensitive language:
@@ -542,8 +545,8 @@ are reserved for internal variables.
542 545
543The following strings denote other \Index{tokens}: 546The following strings denote other \Index{tokens}:
544\begin{verbatim} 547\begin{verbatim}
545 + - * / ^ % 548 + - * / ^ =
546 ~= <= >= < > == = 549 ~= <= >= < > ==
547 ( ) { } [ ] 550 ( ) { } [ ]
548 ; : , . .. ... 551 ; : , . .. ...
549\end{verbatim} 552\end{verbatim}
@@ -1048,17 +1051,9 @@ from lower to higher priority:
1048 not - (unary) 1051 not - (unary)
1049 ^ 1052 ^
1050\end{verbatim} 1053\end{verbatim}
1051All binary operators are left associative, 1054The \verb|..| (concatenation) and \verb|^| (exponentiation)
1052except for \verb|^| (exponentiation), 1055operators are right associative.
1053which is right associative. 1056All other binary operators are left associative.
1054\NOTE
1055The pre-compiler may rearrange the order of evaluation of
1056associative operators,
1057and may exchange the operands of commutative operators,
1058as long as these optimizations do not change normal results.
1059However, these optimizations may change some results
1060if you define non-associative (or non-commutative)
1061metamethods for those operators.
1062 1057
1063\subsubsection{Table Constructors} \label{tableconstructor} 1058\subsubsection{Table Constructors} \label{tableconstructor}
1064Table \Index{constructors} are expressions that create tables; 1059Table \Index{constructors} are expressions that create tables;
@@ -1561,12 +1556,7 @@ the \verb|..| (concatenation) operation.
1561\end{verbatim} 1556\end{verbatim}
1562 1557
1563\item[``index'':]\IndexTM{index} 1558\item[``index'':]\IndexTM{index}
1564This handler is called when Lua tries to retrieve the value of an index 1559The ``gettable'' operation \verb|table[key]|.
1565not present in a table.
1566See the ``gettable'' operation for its semantics.
1567
1568\item[``gettable'':]\IndexTM{gettable}
1569called whenever Lua accesses an indexed variable.
1570\begin{verbatim} 1560\begin{verbatim}
1571 function gettable_event (table, key) 1561 function gettable_event (table, key)
1572 local h 1562 local h
@@ -1576,7 +1566,7 @@ called whenever Lua accesses an indexed variable.
1576 h = metatable(table).__index 1566 h = metatable(table).__index
1577 if h == nil then return nil end 1567 if h == nil then return nil end
1578 else 1568 else
1579 h = metatable(table).__gettable 1569 h = metatable(table).__index
1580 if h == nil then 1570 if h == nil then
1581 error("indexed expression not a table"); 1571 error("indexed expression not a table");
1582 end 1572 end
@@ -1588,12 +1578,7 @@ called whenever Lua accesses an indexed variable.
1588\end{verbatim} 1578\end{verbatim}
1589 1579
1590\item[``newindex'':]\IndexTM{index} 1580\item[``newindex'':]\IndexTM{index}
1591This handler is called when Lua tries to insert the value of an index 1581The ``settable'' operation \verb|table[key] = value|.
1592not present in a table.
1593See the ``settable'' operation for its semantics.
1594
1595\item[``settable'':]\IndexTM{settable}
1596called when Lua assigns to an indexed variable.
1597\begin{verbatim} 1582\begin{verbatim}
1598 function settable_event (table, key, value) 1583 function settable_event (table, key, value)
1599 local h 1584 local h
@@ -1603,7 +1588,7 @@ called when Lua assigns to an indexed variable.
1603 h = metatable(table).__newindex 1588 h = metatable(table).__newindex
1604 if h == nil then rawset(table, key, value); return end 1589 if h == nil then rawset(table, key, value); return end
1605 else 1590 else
1606 h = metatable(table).__settable 1591 h = metatable(table).__newindex
1607 if h == nil then 1592 if h == nil then
1608 error("indexed expression not a table"); 1593 error("indexed expression not a table");
1609 end 1594 end
@@ -1658,6 +1643,56 @@ with the last userdata created in the program
1658 1643
1659 1644
1660 1645
1646\subsection{Coroutines}
1647
1648Lua supports coroutines,
1649also called \emph{semi-coroutines}, \emph{generators},
1650or \emph{colaborative multithreading}.
1651A coroutine in Lua represents an independent thread of execution.
1652Unlike ``real'' threads, however,
1653a coroutine only suspends its execution by explicitly calling
1654an yield function.
1655
1656You create a coroutine with a call to \verb|coroutine.create|.
1657Its sole argument is a function,
1658which is the main function of the coroutine.
1659The \verb|coroutine.create| only creates a new coroutine and
1660returns a handle to it (an object of type \emph{thread}).
1661It does not start the coroutine execution.
1662
1663When you first call \verb|coroutine.resume|,
1664passing as argument the thread returned by \verb|coroutine.create|,
1665the coroutine starts its execution,
1666at the first line of its main function.
1667Extra arguments passed to \verb|coroutine.resume| are given as
1668parameters for the coroutine main function.
1669After the coroutine starts running,
1670it runs until it terminates or it \emph{yields}.
1671
1672A coroutine can terminate its execution in two ways:
1673Normally, when its main function returns
1674(explicitly or implicitly, after the last instruction);
1675and abnormally, if there is an unprotected error.
1676In the first case, \verb|coroutine.resume| returns \True,
1677plus any values returned by the coroutine main function.
1678In case of errors, \verb|coroutine.resume| returns \False
1679plus an error message.
1680
1681A coroutine yields calling \verb|coroutine.yield|.
1682When a coroutine yields,
1683the corresponding \verb|coroutine.resume| returns immediately,
1684even if the yield happens inside nested function calls
1685(that is, not in the main function,
1686but in a function directly or indirectly called by the main function).
1687In the case of a yield, \verb|coroutine.resume| also returns \True,
1688plus any values passed to \verb|coroutine.yield|.
1689The next time you resume the same coroutine,
1690it continues its execution from the point where it yielded,
1691with the call to \verb|coroutine.yield| returning any extra
1692arguments passed to \verb|coroutine.resume|.
1693
1694
1695
1661%------------------------------------------------------------------------------ 1696%------------------------------------------------------------------------------
1662\section{The Application Program Interface}\label{API} 1697\section{The Application Program Interface}\label{API}
1663\index{C API} 1698\index{C API}
@@ -1682,7 +1717,7 @@ The Lua library is fully reentrant:
1682it has no global variables. 1717it has no global variables.
1683\index{state} 1718\index{state}
1684The whole state of the Lua interpreter 1719The whole state of the Lua interpreter
1685(global variables, stack, tag methods, etc.)\ 1720(global variables, stack, etc.)
1686is stored in a dynamically allocated structure of type \verb|lua_State|; 1721is stored in a dynamically allocated structure of type \verb|lua_State|;
1687\DefAPI{lua_State} 1722\DefAPI{lua_State}
1688this state must be passed as the first argument to 1723this state must be passed as the first argument to
@@ -1703,8 +1738,8 @@ To release a state created with \verb|lua_open|, call
1703This function destroys all objects in the given Lua environment 1738This function destroys all objects in the given Lua environment
1704(calling the corresponding garbage-collection metamethods, if any) 1739(calling the corresponding garbage-collection metamethods, if any)
1705and frees all dynamic memory used by that state. 1740and frees all dynamic memory used by that state.
1706Usually, you do not need to call this function, 1741On several platforms, you may not need to call this function,
1707because all resources are naturally released when your program ends. 1742because all resources are naturally released when the host program ends.
1708On the other hand, 1743On the other hand,
1709long-running programs --- 1744long-running programs ---
1710like a daemon or a web server --- 1745like a daemon or a web server ---
@@ -1727,7 +1762,7 @@ The following function creates a new ``thread'' in Lua:
1727\end{verbatim} 1762\end{verbatim}
1728\DefAPI{lua_newthread} 1763\DefAPI{lua_newthread}
1729The new state returned by this function shares with the original state 1764The new state returned by this function shares with the original state
1730all global environment (such as tables, tag methods, etc.), 1765all global environment (such as tables),
1731but has an independent run-time stack. 1766but has an independent run-time stack.
1732(The use of these multiple stacks must be ``syncronized'' with C. 1767(The use of these multiple stacks must be ``syncronized'' with C.
1733How to explain that? TO BE WRITTEN.) 1768How to explain that? TO BE WRITTEN.)
@@ -1754,6 +1789,8 @@ Each C invocation has its own stack.
1754Whenever Lua calls C, the called function gets a new stack, 1789Whenever Lua calls C, the called function gets a new stack,
1755which is independent of previous stacks or of stacks of still 1790which is independent of previous stacks or of stacks of still
1756active C functions. 1791active C functions.
1792That stack contains initially any arguments to the C function,
1793and it is where the C function pushes its results \see{LuacallC}.
1757 1794
1758For convenience, 1795For convenience,
1759most query operations in the API do not follow a strict stack discipline. 1796most query operations in the API do not follow a strict stack discipline.
@@ -1872,8 +1909,8 @@ then
1872 lua_insert(L, 1) --> 30 10 20 30 40* 1909 lua_insert(L, 1) --> 30 10 20 30 40*
1873 lua_insert(L, -1) --> 30 10 20 30 40* (no effect) 1910 lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
1874 lua_replace(L, 2) --> 30 40 20 30* 1911 lua_replace(L, 2) --> 30 40 20 30*
1875 lua_settop(L, -3) --> 30 40 20* 1912 lua_settop(L, -3) --> 30 40*
1876 lua_settop(L, 6) --> 30 40 20 nil nil nil* 1913 lua_settop(L, 6) --> 30 40 nil nil nil nil*
1877\end{verbatim} 1914\end{verbatim}
1878 1915
1879 1916
@@ -1883,22 +1920,22 @@ then
1883To check the type of a stack element, 1920To check the type of a stack element,
1884the following functions are available: 1921the following functions are available:
1885\begin{verbatim} 1922\begin{verbatim}
1886 int lua_type (lua_State *L, int index); 1923 int lua_type (lua_State *L, int index);
1887 int lua_isnil (lua_State *L, int index); 1924 int lua_isnil (lua_State *L, int index);
1888 int lua_isboolean (lua_State *L, int index); 1925 int lua_isboolean (lua_State *L, int index);
1889 int lua_isnumber (lua_State *L, int index); 1926 int lua_isnumber (lua_State *L, int index);
1890 int lua_isstring (lua_State *L, int index); 1927 int lua_isstring (lua_State *L, int index);
1891 int lua_istable (lua_State *L, int index); 1928 int lua_istable (lua_State *L, int index);
1892 int lua_isfunction (lua_State *L, int index); 1929 int lua_isfunction (lua_State *L, int index);
1893 int lua_iscfunction (lua_State *L, int index); 1930 int lua_iscfunction (lua_State *L, int index);
1894 int lua_isuserdata (lua_State *L, int index); 1931 int lua_isuserdata (lua_State *L, int index);
1895 int lua_isdataval (lua_State *L, int index); 1932 int lua_islightuserdata (lua_State *L, int index);
1896\end{verbatim} 1933\end{verbatim}
1897\DefAPI{lua_type} 1934\DefAPI{lua_type}
1898\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} 1935\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
1899\DefAPI{lua_istable}\DefAPI{lua_isboolean} 1936\DefAPI{lua_istable}\DefAPI{lua_isboolean}
1900\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction} 1937\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}
1901\DefAPI{lua_isuserdata}\DefAPI{lua_isdataval} 1938\DefAPI{lua_isuserdata}\DefAPI{lua_islightuserdata}
1902These functions can be called with any acceptable index. 1939These functions can be called with any acceptable index.
1903 1940
1904\verb|lua_type| returns the type of a value in the stack, 1941\verb|lua_type| returns the type of a value in the stack,
@@ -1925,13 +1962,16 @@ with the given type, and 0 otherwise.
1925\verb|lua_isboolean| is an exception to this rule, 1962\verb|lua_isboolean| is an exception to this rule,
1926and it succeeds only for boolean values 1963and it succeeds only for boolean values
1927(otherwise it would be useless, 1964(otherwise it would be useless,
1928as any value is compatible with a boolean). 1965as any value has a boolean value).
1929They always return 0 for a non-valid index. 1966They always return 0 for a non-valid index.
1930\verb|lua_isnumber| accepts numbers and numerical strings, 1967\verb|lua_isnumber| accepts numbers and numerical strings,
1931\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1968\verb|lua_isstring| accepts strings and numbers \see{coercion},
1932and \verb|lua_isfunction| accepts both Lua functions and C~functions. 1969\verb|lua_isfunction| accepts both Lua functions and C~functions,
1970and \verb|lua_isuserdata| accepts both full and ligth userdata.
1933To distinguish between Lua functions and C~functions, 1971To distinguish between Lua functions and C~functions,
1934you should use \verb|lua_iscfunction|. 1972you should use \verb|lua_iscfunction|.
1973To distinguish between full and ligth userdata,
1974you can use \verb|lua_islightuserdata|.
1935To distinguish between numbers and numerical strings, 1975To distinguish between numbers and numerical strings,
1936you can use \verb|lua_type|. 1976you can use \verb|lua_type|.
1937 1977
@@ -2178,6 +2218,22 @@ You can load a Lua chunk with
2178 const char *chunkname); 2218 const char *chunkname);
2179\end{verbatim} 2219\end{verbatim}
2180\DefAPI{Chunkreader}\DefAPI{lua_load} 2220\DefAPI{Chunkreader}\DefAPI{lua_load}
2221The return values of \verb|lua_load| are:
2222\begin{itemize}
2223\item 0 --- no errors;
2224\item \IndexAPI{LUA_ERRSYNTAX} ---
2225syntax error during pre-compilation.
2226\item \IndexAPI{LUA_ERRMEM} ---
2227memory allocation error.
2228\end{itemize}
2229If there are no errors,
2230\verb|lua_load| pushes the compiled chunk as a Lua
2231function on top of the stack.
2232Otherwise, it pushes an error message.
2233
2234\verb|lua_load| automatically detects whether the chunk is text or binary,
2235and loads it accordingly (see program \IndexVerb{luac}).
2236
2181\verb|lua_load| uses the \emph{reader} to read the chunk. 2237\verb|lua_load| uses the \emph{reader} to read the chunk.
2182Everytime it needs another piece of the chunk, 2238Everytime it needs another piece of the chunk,
2183it calls the reader, 2239it calls the reader,
@@ -2192,21 +2248,6 @@ In the current implementation,
2192the reader function cannot call any Lua function; 2248the reader function cannot call any Lua function;
2193to ensure that, it always receives \verb|NULL| as the Lua state. 2249to ensure that, it always receives \verb|NULL| as the Lua state.
2194 2250
2195\verb|lua_load| automatically detects whether the chunk is text or binary,
2196and loads it accordingly (see program \IndexVerb{luac}).
2197
2198The return values of \verb|lua_load| are:
2199\begin{itemize}
2200\item 0 --- no errors;
2201\item \IndexAPI{LUA_ERRSYNTAX} ---
2202syntax error during pre-compilation.
2203\item \IndexAPI{LUA_ERRMEM} ---
2204memory allocation error.
2205\end{itemize}
2206If there are no errors,
2207the compiled chunk is pushed as a Lua function on top of the stack.
2208Otherwise, an error message is pushed.
2209
2210The \emph{chunkname} is used for error messages 2251The \emph{chunkname} is used for error messages
2211and debug information \see{debugI}. 2252and debug information \see{debugI}.
2212 2253
@@ -2446,20 +2487,19 @@ error while running the error handler function.
2446Some special Lua functions have their own C~interfaces. 2487Some special Lua functions have their own C~interfaces.
2447The host program can generate a Lua error calling the function 2488The host program can generate a Lua error calling the function
2448\begin{verbatim} 2489\begin{verbatim}
2449 void lua_error (lua_State *L, const char *message); 2490 void lua_error (lua_State *L);
2450\end{verbatim} 2491\end{verbatim}
2451\DefAPI{lua_error} 2492\DefAPI{lua_error}
2493The error message (which actually can be any type of object)
2494is popped from the stack.
2452This function never returns. 2495This function never returns.
2453If \verb|lua_error| is called from a C~function that has been called from Lua, 2496If \verb|lua_error| is called from a C~function that
2497has been called from Lua,
2454then the corresponding Lua execution terminates, 2498then the corresponding Lua execution terminates,
2455as if an error had occurred inside Lua code. 2499as if an error had occurred inside Lua code.
2456Otherwise, the whole host program terminates with a call to 2500Otherwise, the whole host program terminates with a call to
2457\verb|exit(EXIT_FAILURE)|. 2501\verb|exit(EXIT_FAILURE)|.
2458Before terminating execution, 2502%% TODO: at_panic
2459the \verb|message| is passed to the error handler function,
2460\verb|_ERRORMESSAGE| \see{error}.
2461If \verb|message| is \verb|NULL|,
2462then \verb|_ERRORMESSAGE| is not called.
2463 2503
2464The function 2504The function
2465\begin{verbatim} 2505\begin{verbatim}
@@ -2476,6 +2516,7 @@ Concatenation is done following the usual semantics of Lua
2476 2516
2477 2517
2478\subsection{Defining C Functions} \label{LuacallC} 2518\subsection{Defining C Functions} \label{LuacallC}
2519
2479Lua can be extended with functions written in~C. 2520Lua can be extended with functions written in~C.
2480These functions must be of type \verb|lua_CFunction|, 2521These functions must be of type \verb|lua_CFunction|,
2481which is defined as 2522which is defined as
@@ -2489,8 +2530,10 @@ the number of values it has returned to Lua.
2489In order to communicate properly with Lua, 2530In order to communicate properly with Lua,
2490a C~function must follow the following protocol, 2531a C~function must follow the following protocol,
2491which defines the way parameters and results are passed: 2532which defines the way parameters and results are passed:
2492A C~function receives its arguments from Lua in the stack, 2533A C~function receives its arguments from Lua in its stack,
2493in direct order (the first argument is pushed first). 2534in direct order (the first argument is pushed first).
2535So, when the function starts,
2536its first argument (if any) is at index 1.
2494To return values to Lua, a C~function just pushes them onto the stack, 2537To return values to Lua, a C~function just pushes them onto the stack,
2495in direct order (the first result is pushed first), 2538in direct order (the first result is pushed first),
2496and returns the number of results. 2539and returns the number of results.
@@ -2617,7 +2660,7 @@ The structure \verb|lua_Debug| is used to carry different pieces of
2617information about an active function: 2660information about an active function:
2618\begin{verbatim} 2661\begin{verbatim}
2619 typedef struct lua_Debug { 2662 typedef struct lua_Debug {
2620 lua_Hookevent event; 2663 int event;
2621 const char *name; /* (n) */ 2664 const char *name; /* (n) */
2622 const char *namewhat; /* (n) `global', `local', `field', `method' */ 2665 const char *namewhat; /* (n) `global', `local', `field', `method' */
2623 const char *what; /* (S) `Lua' function, `C' function, Lua `main' */ 2666 const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
@@ -2768,11 +2811,9 @@ a \emph{call} event, when Lua calls a function;
2768a \emph{return} event, when Lua returns from a function; 2811a \emph{return} event, when Lua returns from a function;
2769a \emph{line} event, when Lua starts executing a new line of code; 2812a \emph{line} event, when Lua starts executing a new line of code;
2770and a \emph{count} event, that happens every ``count'' instructions. 2813and a \emph{count} event, that happens every ``count'' instructions.
2771Lua identifies them with the following enumeration: 2814Lua identifies them with the following constants:
2772\begin{verbatim} 2815\DefAPI{LUA_HOOKCALL}, \DefAPI{LUA_HOOKRET},
2773typedef enum lua_Hookevent { 2816\DefAPI{LUA_HOOKLINE}, and \DefAPI{LUA_HOOKCOUNT}.
2774 LUA_HOOKCALL, LUA_HOOKRET, LUA_HOOKLINE, LUA_HOOKCOUNT
2775} lua_Hookevent;
2776\end{verbatim} 2817\end{verbatim}
2777 2818
2778A hook has type \verb|lua_Hook|, defined as follows: 2819A hook has type \verb|lua_Hook|, defined as follows:
@@ -2792,7 +2833,22 @@ It is formed by a disjunction of the constants
2792\verb|LUA_MASKRET|, 2833\verb|LUA_MASKRET|,
2793\verb|LUA_MASKLINE|, 2834\verb|LUA_MASKLINE|,
2794plus the macro \verb|LUA_MASKCOUNT(count)|. 2835plus the macro \verb|LUA_MASKCOUNT(count)|.
2795%TODO explicar melhor... 2836For each event, the hook is called as explained below:
2837\begin{description}
2838\item{call hook} called when the interpreter calls a function.
2839The hook is called just after Lua ``enters'' the new function.
2840\item{return hook} called when the interpreter returns from a function.
2841The hook is called just before Lua ``leaves'' the function.
2842\item{line hook} called when the interpreter is about to
2843start the execution of a new line of code,
2844or when it jumps back (even for the same line).
2845(For obvious reasons, this event does not happens while Lua is executing
2846a C function.)
2847\item{count hook} called after the interpreter executes every
2848\verb|count| instructions.
2849(For obvious reasons, this event does not happens while Lua is executing
2850a C function.)
2851\end{description}
2796 2852
2797A hook is disabled with the mask zero. 2853A hook is disabled with the mask zero.
2798 2854
@@ -2811,7 +2867,7 @@ For the value of any other field, the hook must call \verb|lua_getinfo|.
2811 2867
2812While Lua is running a hook, it disables other calls to hooks. 2868While Lua is running a hook, it disables other calls to hooks.
2813Therefore, if a hook calls Lua to execute a function or a chunk, 2869Therefore, if a hook calls Lua to execute a function or a chunk,
2814this execution ocurrs without any calls to hooks. 2870that execution ocurrs without any calls to hooks.
2815 2871
2816 2872
2817%------------------------------------------------------------------------------ 2873%------------------------------------------------------------------------------
@@ -2844,16 +2900,19 @@ or as methods of its objects.
2844 2900
2845To have access to these libraries, 2901To have access to these libraries,
2846the C~host program must call the functions 2902the C~host program must call the functions
2847\verb|lua_baselibopen|, 2903\verb|lua_baselibopen| (for the basic library),
2848\verb|lua_strlibopen|, 2904\verb|lua_strlibopen| (for the string library),
2849\verb|lua_tablibopen|, 2905\verb|lua_tablibopen| (for the table library),
2850\verb|lua_mathlibopen|, 2906\verb|lua_mathlibopen| (for the mathematical library),
2851and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|. 2907\verb|lua_iolibopen| (for the I/O and the Operating System libraries),
2908and \verb|lua_dblibopen| (for the debug library),
2909which are declared in \verb|lualib.h|.
2852\DefAPI{lua_baselibopen} 2910\DefAPI{lua_baselibopen}
2853\DefAPI{lua_strlibopen} 2911\DefAPI{lua_strlibopen}
2854\DefAPI{lua_tablibopen} 2912\DefAPI{lua_tablibopen}
2855\DefAPI{lua_mathlibopen} 2913\DefAPI{lua_mathlibopen}
2856\DefAPI{lua_iolibopen} 2914\DefAPI{lua_iolibopen}
2915\DefAPI{lua_dblibopen}
2857 2916
2858 2917
2859\subsection{Basic Functions} \label{predefined} 2918\subsection{Basic Functions} \label{predefined}
@@ -2863,7 +2922,7 @@ If you do not include this library in your application,
2863you should check carefully whether you need to provide some alternative 2922you should check carefully whether you need to provide some alternative
2864implementation for some facilities. 2923implementation for some facilities.
2865 2924
2866The basic library also defines a global variable \IndexAPI{_VERSION} 2925The basic library also defines a global variable \IndexLIB{_VERSION}
2867with a string containing the current interpreter version. 2926with a string containing the current interpreter version.
2868The current content of this string is {\tt "Lua \Version"}. 2927The current content of this string is {\tt "Lua \Version"}.
2869 2928
@@ -2897,11 +2956,19 @@ When called without arguments,
2897\verb|dofile| executes the contents of the standard input (\verb|stdin|). 2956\verb|dofile| executes the contents of the standard input (\verb|stdin|).
2898Returns any value returned by the chunk. 2957Returns any value returned by the chunk.
2899 2958
2900\subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error} 2959\subsubsection*{\ff \T{error (message [, level])}}
2960DefLIB{error}\label{pdf-error}
2901Terminates the last protected function called, 2961Terminates the last protected function called,
2902and returns \verb|message| as the error message. 2962and returns \verb|message| as the error message.
2903Function \verb|error| never returns. 2963Function \verb|error| never returns.
2904 2964
2965The \verb|level| argument affects to where the error
2966message points the error.
2967With level 1 (the default), the error position is where the
2968\verb|error| function was called.
2969Level 2 points the error to where the function
2970that called \verb|error| was called; and so on.
2971
2905\subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals} 2972\subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals}
2906Returns the current table of globals in use by the function. 2973Returns the current table of globals in use by the function.
2907\verb|function| can be a Lua function or a number, 2974\verb|function| can be a Lua function or a number,
@@ -2917,13 +2984,6 @@ The default for \verb|function| is 1.
2917Returns the metatable of the given object. 2984Returns the metatable of the given object.
2918If the object does not have a metatable, returns \nil. 2985If the object does not have a metatable, returns \nil.
2919 2986
2920\subsubsection*{\ff \T{getmode (table)}}\DefLIB{getmode}
2921
2922Returns the weak mode of a table, as a string.
2923Valid values for this string are \verb|""| for regular (non-weak) tables,
2924\verb|"k"| for weak keys, \verb|"v"| for weak values,
2925and \verb|"kv"| for both.
2926
2927\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo} 2987\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
2928Returns the number of Kbytes of dynamic memory Lua is using, 2988Returns the number of Kbytes of dynamic memory Lua is using,
2929and (as a second result) the 2989and (as a second result) the
@@ -2931,7 +2991,7 @@ current garbage collector threshold (also in Kbytes).
2931 2991
2932\subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs} 2992\subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs}
2933 2993
2934Returns the table \verb|t| and a generator function 2994Returns a generator function and the table \verb|t|,
2935so that the construction 2995so that the construction
2936\begin{verbatim} 2996\begin{verbatim}
2937 for i,v in ipairs(t) do ... end 2997 for i,v in ipairs(t) do ... end
@@ -2988,7 +3048,7 @@ the table during the traversal.
2988 3048
2989\subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs} 3049\subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs}
2990 3050
2991Returns the table \verb|t| and the function \verb|next|, 3051Returns the function \verb|next| and the table \verb|t|,
2992so that the construction 3052so that the construction
2993\begin{verbatim} 3053\begin{verbatim}
2994 for k,v in pairs(t) do ... end 3054 for k,v in pairs(t) do ... end
@@ -2999,7 +3059,11 @@ will iterate over all pairs of key--value of table \verb|t|.
2999\label{pdf-pcall} 3059\label{pdf-pcall}
3000Calls function \verb|func| with 3060Calls function \verb|func| with
3001the given arguments in protected mode. 3061the given arguments in protected mode.
3002Its first result is a boolean, true if the call succeeds without errors. 3062That means that any error inside \verb|func| is not propagated;
3063instead, \verb|pcall| catches the error,
3064returning a status code.
3065Its first result is the status code (a boolean),
3066true if the call succeeds without errors.
3003In such case, \verb|pcall| also returns all results from the call, 3067In such case, \verb|pcall| also returns all results from the call,
3004after this first result. 3068after this first result.
3005In case of any error, \verb|pcall| returns false plus the error message. 3069In case of any error, \verb|pcall| returns false plus the error message.
@@ -3015,13 +3079,13 @@ For formatted output, see \verb|format| \see{format}.
3015 3079
3016\subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget} 3080\subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget}
3017Gets the real value of \verb|table[index]|, 3081Gets the real value of \verb|table[index]|,
3018without invoking any tag method. 3082without invoking any metamethod.
3019\verb|table| must be a table; 3083\verb|table| must be a table;
3020\verb|index| is any value different from \nil. 3084\verb|index| is any value different from \nil.
3021 3085
3022\subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset} 3086\subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset}
3023Sets the real value of \verb|table[index]| to \verb|value|, 3087Sets the real value of \verb|table[index]| to \verb|value|,
3024without invoking any tag method. 3088without invoking any metamethod.
3025\verb|table| must be a table; 3089\verb|table| must be a table;
3026\verb|index| is any value different from \nil; 3090\verb|index| is any value different from \nil;
3027and \verb|value| is any Lua value. 3091and \verb|value| is any Lua value.
@@ -3077,16 +3141,6 @@ Sets the metatable for the given table.
3077(You cannot change the metatable of a userdata from Lua.) 3141(You cannot change the metatable of a userdata from Lua.)
3078If \verb|metatable| is \nil, removes the metatable of the given table. 3142If \verb|metatable| is \nil, removes the metatable of the given table.
3079 3143
3080\subsubsection*{\ff \T{setmode (table, mode)}}\DefLIB{setmode}
3081
3082Set the weak mode of a table.
3083The new mode is described by the \verb|mode| string.
3084Valid values for this string are \verb|""| for regular (non-weak) tables,
3085\verb|"k"| for weak keys, \verb|"v"| for weak values,
3086and \verb|"kv"| for both.
3087
3088This function returns its first argument (\verb|table|).
3089
3090\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} 3144\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
3091Tries to convert its argument to a number. 3145Tries to convert its argument to a number.
3092If the argument is already a number or a string convertible 3146If the argument is already a number or a string convertible
@@ -3249,7 +3303,31 @@ String values to be formatted with
3249 3303
3250\subsubsection*{\ff \T{string.gfind (s, pat)}} 3304\subsubsection*{\ff \T{string.gfind (s, pat)}}
3251 3305
3252% TODO 3306Returns a generator function that,
3307each time it is called,
3308returns the next captures from pattern \verb|pat| over string \verb|s|.
3309
3310If \verb|pat| specifies no captures,
3311then the whole match is produced in each call.
3312
3313As an example, the following loop
3314\begin{verbatim}
3315 s = "hello world from Lua"
3316 for w in string.gfind(s, "%a+") do
3317 print(w)
3318 end
3319\end{verbatim}
3320will iterate over all the words from string \verb|s|,
3321printing each one in a line.
3322The next example collects all pairs \verb|key=value| from the
3323given string into a table:
3324\begin{verbatim}
3325 t = {}
3326 s = "from=world, to=Lua"
3327 for k, v in string.gfind(s, "(%w+)=(%w+)") do
3328 t[k] = v
3329 end
3330\end{verbatim}
3253 3331
3254\subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}} 3332\subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}}
3255\DefLIB{string.gsub} 3333\DefLIB{string.gsub}
@@ -3280,24 +3358,28 @@ For instance, when \verb|n| is 1 only the first occurrence of
3280 3358
3281Here are some examples: 3359Here are some examples:
3282\begin{verbatim} 3360\begin{verbatim}
3283 x = gsub("hello world", "(%w+)", "%1 %1") 3361 x = string.gsub("hello world", "(%w+)", "%1 %1")
3284 --> x="hello hello world world" 3362 --> x="hello hello world world"
3285 3363
3286 x = gsub("hello world", "(%w+)", "%1 %1", 1) 3364 x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
3287 --> x="hello hello world" 3365 --> x="hello hello world"
3288 3366
3289 x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") 3367 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
3290 --> x="world hello Lua from" 3368 --> x="world hello Lua from"
3291 3369
3292 x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv) 3370 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
3293 --> x="home = /home/roberto, user = roberto" (for instance) 3371 --> x="home = /home/roberto, user = roberto" (for instance)
3294 3372
3295 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) 3373 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
3374 return loadstring(s)()
3375 end)
3296 --> x="4+5 = 9" 3376 --> x="4+5 = 9"
3297 3377
3298 local t = {name="Lua", version="4.1"} 3378 local t = {name="Lua", version="5.0"}
3299 x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end) 3379 x = string.gsub("$name - $version", "%$(%w+)", function (v)
3300 --> x="Lua - 4.1" 3380 return t[v]
3381 end)
3382 --> x="Lua - 5.0"
3301\end{verbatim} 3383\end{verbatim}
3302 3384
3303 3385
@@ -3416,6 +3498,11 @@ stored as the first capture (and therefore has number~1);
3416the character matching \verb|.| is captured with number~2, 3498the character matching \verb|.| is captured with number~2,
3417and the part matching \verb|%s*| has number~3. 3499and the part matching \verb|%s*| has number~3.
3418 3500
3501As a special case, the empty capture \verb|()| captures
3502the current string position (a number).
3503For instance, if we apply the pattern \verb|"()aa()"| on the
3504string \verb|"flaaap"|, there will be two captures: 3 and 5.
3505
3419\NOTE 3506\NOTE
3420A pattern cannot contain embedded zeros. Use \verb|%z| instead. 3507A pattern cannot contain embedded zeros. Use \verb|%z| instead.
3421 3508
@@ -3442,6 +3529,14 @@ with a \nil{} value.
3442For more details, see the descriptions of the \verb|table.getn| and 3529For more details, see the descriptions of the \verb|table.getn| and
3443\verb|table.setn| functions. 3530\verb|table.setn| functions.
3444 3531
3532\subsubsection*{\ff \T{table.concat (table [, sep [, i [, j]]])}}
3533\DefLIB{table.concat}
3534Returns \verb|table[i]..sep..table[i+1] ... sep..table[j]|.
3535The default value for \verb|sep| is the empty string,
3536the default for \verb|i| is 1,
3537and the default for \verb|j| is the size of the table.
3538If \verb|i| is greater than \verb|j|, returns the empty string.
3539
3445\subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach} 3540\subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach}
3446Executes the given \verb|func| over all elements of \verb|table|. 3541Executes the given \verb|func| over all elements of \verb|table|.
3447For each element, \verb|func| is called with the index and 3542For each element, \verb|func| is called with the index and
@@ -3560,6 +3655,7 @@ The library provides the following functions:
3560plus a variable \IndexLIB{math.pi}. 3655plus a variable \IndexLIB{math.pi}.
3561Most of them 3656Most of them
3562are only interfaces to the homonymous functions in the C~library. 3657are only interfaces to the homonymous functions in the C~library.
3658All trigonometric functions work in radians.
3563The functions \verb|math.deg| and \verb|math.rad| convert 3659The functions \verb|math.deg| and \verb|math.rad| convert
3564between radians and degrees. 3660between radians and degrees.
3565 3661
@@ -3579,6 +3675,9 @@ When called with a number \Math{n},
3579\verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}. 3675\verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}.
3580When called with two arguments, \Math{l} and \Math{u}, 3676When called with two arguments, \Math{l} and \Math{u},
3581\verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}. 3677\verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}.
3678The \verb|math.randomseed| function sets a ``seed''
3679for the pseudo-random generator:
3680Equal seeds produce equal sequences of numbers.
3582 3681
3583 3682
3584\subsection{Input and Output Facilities} \label{libio} 3683\subsection{Input and Output Facilities} \label{libio}
@@ -3611,12 +3710,12 @@ and some value different from \nil{} on success.
3611 3710
3612\subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close} 3711\subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close}
3613 3712
3614Equivalent to \verb|handle:close()|. 3713Equivalent to \verb|file:close()|.
3615Without a \verb|handle|, closes the default output file. 3714Without a \verb|handle|, closes the default output file.
3616 3715
3617\subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush} 3716\subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush}
3618 3717
3619Equivalent to \verb|fh:flush| over the default output file. 3718Equivalent to \verb|file:flush| over the default output file.
3620 3719
3621\subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input} 3720\subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input}
3622 3721
@@ -3631,6 +3730,24 @@ it returns the current default input file.
3631In case of errors this function raises the error, 3730In case of errors this function raises the error,
3632instead of returning an error code. 3731instead of returning an error code.
3633 3732
3733\subsubsection*{\ff \T{io.lines ([filename])}}\DefLIB{io.lines}
3734
3735Opens the given file name in read mode,
3736and returns a generator function that,
3737each time it is called,
3738returns a new line from the file.
3739Therefore, the construction
3740\begin{verbatim}
3741 for lines in io.lines(filename) do ... end
3742\end{verbatim}
3743will iterate over all lines of the file.
3744When the generator function detects the end of file,
3745it returns nil (to finish the loop) and automatically closes the file.
3746
3747The call \verb|io.lines()| (without a file name) is equivalent
3748to \verb|io.input():lines()|, that is, it iterates over the
3749lines of the default input file.
3750
3634\subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open} 3751\subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open}
3635 3752
3636This function opens a file, 3753This function opens a file,
@@ -3658,7 +3775,7 @@ Similar to \verb|io.input|, but operates over the default output file.
3658 3775
3659\subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read} 3776\subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read}
3660 3777
3661Equivalent to \verb|fh:read| over the default input file. 3778Equivalent to \verb|file:read| over the default input file.
3662 3779
3663\subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile} 3780\subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile}
3664 3781
@@ -3668,21 +3785,34 @@ and it is automatically removed when the program ends.
3668 3785
3669\subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write} 3786\subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write}
3670 3787
3671Equivalent to \verb|fh:write| over the default output file. 3788Equivalent to \verb|file:write| over the default output file.
3789
3672 3790
3673 3791
3792\subsubsection*{\ff \T{file:close ()}}\DefLIB{file:close}
3674 3793
3675\subsubsection*{\ff \T{fh:close ([handle])}}\DefLIB{fh:close} 3794Closes the file \verb|file|.
3676 3795
3677Closes the file \verb|fh|. 3796\subsubsection*{\ff \T{file:flush ()}}\DefLIB{file:flush}
3678 3797
3679\subsubsection*{\ff \T{fh:flush ()}}\DefLIB{fh:flush} 3798Saves any written data to the file \verb|file|.
3680 3799
3681Saves any written data to the file \verb|fh|. 3800\subsubsection*{\ff \T{file:lines ()}}\DefLIB{file:lines}
3801
3802Returns a generator function that,
3803each time it is called,
3804returns a new line from the file.
3805Therefore, the construction
3806\begin{verbatim}
3807 for lines in file:lines() do ... end
3808\end{verbatim}
3809will iterate over all lines of the file.
3810(Unlike \verb|io.lines|, this function does not close the file
3811when the loop ends.)
3682 3812
3683\subsubsection*{\ff \T{fh:read (format1, ...)}}\DefLIB{fh:read} 3813\subsubsection*{\ff \T{file:read (format1, ...)}}\DefLIB{file:read}
3684 3814
3685Reads the file \verb|fh|, 3815Reads the file \verb|file|,
3686according to the given formats, which specify what to read. 3816according to the given formats, which specify what to read.
3687For each format, 3817For each format,
3688the function returns a string (or a number) with the characters read, 3818the function returns a string (or a number) with the characters read,
@@ -3707,7 +3837,7 @@ it reads nothing and returns an empty string,
3707or \nil{} on end of file. 3837or \nil{} on end of file.
3708\end{description} 3838\end{description}
3709 3839
3710\subsubsection*{\ff \T{fh:seek ([whence] [, offset])}}\DefLIB{fh:seek} 3840\subsubsection*{\ff \T{file:seek ([whence] [, offset])}}\DefLIB{file:seek}
3711 3841
3712Sets and gets the file position, 3842Sets and gets the file position,
3713measured in bytes from the beginning of the file, 3843measured in bytes from the beginning of the file,
@@ -3732,10 +3862,10 @@ beginning of the file (and returns 0);
3732and the call \verb|file:seek("end")| sets the position to the 3862and the call \verb|file:seek("end")| sets the position to the
3733end of the file, and returns its size. 3863end of the file, and returns its size.
3734 3864
3735\subsubsection*{\ff \T{fh:write (value1, ...)}}\DefLIB{fh:write} 3865\subsubsection*{\ff \T{file:write (value1, ...)}}\DefLIB{file:write}
3736 3866
3737Writes the value of each of its arguments to 3867Writes the value of each of its arguments to
3738the filehandle \verb|fh|. 3868the filehandle \verb|file|.
3739The arguments must be strings or numbers. 3869The arguments must be strings or numbers.
3740To write other values, 3870To write other values,
3741use \verb|tostring| or \verb|format| before \verb|write|. 3871use \verb|tostring| or \verb|format| before \verb|write|.
@@ -3929,7 +4059,7 @@ and raises an error when called with a \verb|level| out of range.
3929Sets the given function as a hook. 4059Sets the given function as a hook.
3930The string \verb|mask| and the number \verb|count| describe 4060The string \verb|mask| and the number \verb|count| describe
3931when the hook will be called. 4061when the hook will be called.
3932The string mask may have the following characteres, 4062The string mask may have the following characters,
3933with the given meaning: 4063with the given meaning:
3934\begin{description} 4064\begin{description}
3935\item[{\tt "c"}] The hook is called every time Lua calls a function; 4065\item[{\tt "c"}] The hook is called every time Lua calls a function;
@@ -3973,18 +4103,18 @@ The stand-alone interpreter includes
3973all standard libraries plus the reflexive debug interface. 4103all standard libraries plus the reflexive debug interface.
3974Its usage is: 4104Its usage is:
3975\begin{verbatim} 4105\begin{verbatim}
3976 lua [options] [prog [args]] 4106 lua [options] [script [args]]
3977\end{verbatim} 4107\end{verbatim}
3978The options are: 4108The options are:
3979\begin{description}\leftskip=20pt 4109\begin{description}\leftskip=20pt
3980\item[\T{-} ] executes \verb|stdin| as a file; 4110\item[\T{-} ] executes \verb|stdin| as a file;
3981\item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; 4111\item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
3982\item[\T{-l} \rm\emph{file}] executes file \emph{file}; 4112\item[\T{-l} \rm\emph{file}] executes file \emph{file};
3983\item[\T{-i}] enters interactive mode after running \emph{prog}; 4113\item[\T{-i}] enters interactive mode after running \emph{script};
3984\item[\T{-v}] prints version information; 4114\item[\T{-v}] prints version information;
3985\item[\T{--}] stop handling options. 4115\item[\T{--}] stop handling options.
3986\end{description} 4116\end{description}
3987After handling its options, \verb|lua| runs the given \emph{prog}, 4117After handling its options, \verb|lua| runs the given \emph{script},
3988passing to it the given \emph{args}. 4118passing to it the given \emph{args}.
3989When called without arguments, 4119When called without arguments,
3990\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, 4120\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
@@ -3999,20 +4129,20 @@ Otherwise, lua executes the string itself.
3999All options are handled in order, except \verb|-i|. 4129All options are handled in order, except \verb|-i|.
4000For instance, an invocation like 4130For instance, an invocation like
4001\begin{verbatim} 4131\begin{verbatim}
4002 $ lua -e'a=1' -e 'print(a)' prog.lua 4132 $ lua -e'a=1' -e 'print(a)' script.lua
4003\end{verbatim} 4133\end{verbatim}
4004will first set \verb|a| to 1, then print \verb|a|, 4134will first set \verb|a| to 1, then print \verb|a|,
4005and finally run the file \verb|prog.lua|. 4135and finally run the file \verb|script.lua|.
4006(Here, \verb|$| is the shell prompt. Your prompt may be different.) 4136(Here, \verb|$| is the shell prompt. Your prompt may be different.)
4007 4137
4008Before starting to run the program, 4138Before starting to run the script,
4009\verb|lua| collects all arguments in the command line 4139\verb|lua| collects all arguments in the command line
4010in a global table called \verb|arg|. 4140in a global table called \verb|arg|.
4011The program name is stored in index 0, 4141The script name is stored in index 0,
4012the first argument after the program goes to index 1, 4142the first argument after the script name goes to index 1,
4013and so on. 4143and so on.
4014The field \verb|n| gets the number of arguments after the program name. 4144The field \verb|n| gets the number of arguments after the script name.
4015Any arguments before the program name 4145Any arguments before the script name
4016(that is, the interpreter name plus the options) 4146(that is, the interpreter name plus the options)
4017go to negative indices. 4147go to negative indices.
4018For instance, in the call 4148For instance, in the call
@@ -4083,7 +4213,7 @@ Mark Ian Barlow,
4083Nick Trout, 4213Nick Trout,
4084Noemi Rodriguez, 4214Noemi Rodriguez,
4085Norman Ramsey, 4215Norman Ramsey,
4086Philippe Lhost, 4216Philippe Lhoste,
4087Renata Ratton, 4217Renata Ratton,
4088Renato Borges, 4218Renato Borges,
4089Renato Cerqueira, 4219Renato Cerqueira,