aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>1996-02-05 12:52:47 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>1996-02-05 12:52:47 -0200
commit15057aa0a42477a04d718270c9bc3303b4e9b613 (patch)
tree681b70790c669e2aac44a24a506c8a5c6593ec9b
parent1431b52e769d1dc5f05d9eef10f7ad56bb6c44e6 (diff)
downloadlua-15057aa0a42477a04d718270c9bc3303b4e9b613.tar.gz
lua-15057aa0a42477a04d718270c9bc3303b4e9b613.tar.bz2
lua-15057aa0a42477a04d718270c9bc3303b4e9b613.zip
new examples showing data structures and object-oriented programming.
generic improvements and corrections.
-rw-r--r--manual.tex183
1 files changed, 145 insertions, 38 deletions
diff --git a/manual.tex b/manual.tex
index d0556c02..d3aa89dc 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.3 1996/01/30 12:55:10 roberto Exp roberto $ 1% $Id: manual.tex,v 1.4 1996/01/30 15:24:49 roberto Exp roberto $
2 2
3\documentstyle[A4,11pt,bnf]{article} 3\documentstyle[A4,11pt,bnf]{article}
4 4
@@ -32,7 +32,7 @@ Waldemar Celes Filho
32Departamento de Inform\'atica --- PUC-Rio 32Departamento de Inform\'atica --- PUC-Rio
33} 33}
34 34
35\date{\small \verb$Date: 1996/01/30 12:55:10 $} 35\date{\small \verb$Date: 1996/01/30 15:24:49 $}
36 36
37\maketitle 37\maketitle
38 38
@@ -70,9 +70,9 @@ general procedural programming features with data description
70facilities. 70facilities.
71It is supposed to be used as a configuration language for any 71It is supposed to be used as a configuration language for any
72program that needs one. 72program that needs one.
73Its main extensions are related to object-oriented facilities, 73%Its main extensions are related to object-oriented facilities,
74and fallbacks, 74%and fallbacks,
75but it has some other minor contributions. 75%but it has some other minor contributions.
76Lua has been designed and implemented by 76Lua has been designed and implemented by
77W.~Celes~F., L.~H.~de Figueiredo and R.~Ierusalimschy. 77W.~Celes~F., L.~H.~de Figueiredo and R.~Ierusalimschy.
78 78
@@ -231,7 +231,7 @@ double hyphen (\verb'--') and run until the end of the line.
231and an optional decimal exponent. 231and an optional decimal exponent.
232Examples of valid numerical constants are: 232Examples of valid numerical constants are:
233\begin{verbatim} 233\begin{verbatim}
234 4 4. .4 4.57e-3 .3e12 234 4 4.0 0.4 4.57e-3 0.3e12
235\end{verbatim} 235\end{verbatim}
236 236
237 237
@@ -344,17 +344,14 @@ the syntax for a \Index{return statement} is:
344\produc{ret}{\rwd{return} explist} 344\produc{ret}{\rwd{return} explist}
345\end{Produc} 345\end{Produc}
346 346
347\subsubsection{Expressions as Statements} \label{statexp} 347\subsubsection{Function Calls as Statements} \label{funcstat}
348All expressions with possible side-effects can be 348Because of possible side-effects,
349executed as statements. 349function calls can be executed as statements.
350These include function calls and table constructors:
351\begin{Produc} 350\begin{Produc}
352\produc{stat}{functioncall} 351\produc{stat}{functioncall}
353\produc{stat}{tableconstructor}
354\end{Produc}% 352\end{Produc}%
355Eventual returned values are thrown away. 353Eventual returned values are thrown away.
356Function calls are explained in Section \ref{functioncall}; 354Function calls are explained in Section \ref{functioncall}.
357constructors are the subject of Section \ref{tableconstructor}.
358 355
359\subsubsection{Local Declarations} \label{localvar} 356\subsubsection{Local Declarations} \label{localvar}
360\Index{Local variables} can be declared anywhere inside a block. 357\Index{Local variables} can be declared anywhere inside a block.
@@ -405,7 +402,8 @@ Lua offers the following \Index{relational operators}:
405\begin{verbatim} 402\begin{verbatim}
406 < > <= >= ~= == 403 < > <= >= ~= ==
407\end{verbatim} 404\end{verbatim}
408All return \nil\ as false and 1 as true. 405All return \nil\ as false and a value different from \nil\
406(actually the number 1) as true.
409 407
410Equality first compares the types of its operands. 408Equality first compares the types of its operands.
411If they are different, the result is \nil. 409If they are different, the result is \nil.
@@ -546,7 +544,7 @@ the parameter list is a single new table.
546Because a function can return any number of results 544Because a function can return any number of results
547(\see{return}), 545(\see{return}),
548the number of results must be adjusted before used. 546the number of results must be adjusted before used.
549If the function is called as an statement (\see{statexp}), 547If the function is called as a statement (\see{funcstat}),
550its return list is adjusted to 0. 548its return list is adjusted to 0.
551If the function is called in a place that needs a single value 549If the function is called in a place that needs a single value
552(syntactically denoted by the non-terminal \verb'exp1'), 550(syntactically denoted by the non-terminal \verb'exp1'),
@@ -601,7 +599,7 @@ end
601\end{verbatim} 599\end{verbatim}
602that is, the function gets an extra formal parameter called \verb'self'. 600that is, the function gets an extra formal parameter called \verb'self'.
603Notice that 601Notice that
604the variable \verb'v' must be previously initialized with a table value. 602the variable \verb'v' must have been previously initialized with a table value.
605 603
606 604
607\subsection{Fallbacks} \label{fallback} 605\subsection{Fallbacks} \label{fallback}
@@ -704,18 +702,17 @@ and then the corresponding function from the library
704is terminated returning an error condition. 702is terminated returning an error condition.
705 703
706The only argument to the error fallback function is a string describing 704The only argument to the error fallback function is a string describing
707the error and some extra informations, 705the error.
708like current line (when the error is at compilation) 706The standard I/O library redefines this fallback,
709or current function (when the error is at execution). 707using the debug API, in order to print some extra informations,
708like the stack of calls.
710For more information about an error, 709For more information about an error,
711the Lua program can include the compilation pragma \verb'$debug'. 710the Lua program can include the compilation pragma \verb'$debug'.
712\index{debug pragma} 711\index{debug pragma}
713This pragma must be written in a line by itself. 712This pragma must be written in a line by itself.
714When an error occurs in a program compiled with this option, 713When an error occurs in a program compiled with this option,
715the error message includes extra information showing the stack of calls. 714the error routine is able to print also the lines where the calls
716 715(and the error) were made.
717The standard error routine only prints the error message
718to \verb'stderr'.
719If needed, it is possible to change the error fallback routine; 716If needed, it is possible to change the error fallback routine;
720\see{fallback}. 717\see{fallback}.
721 718
@@ -758,6 +755,9 @@ Because Lua has no static type system,
758all values passed between Lua and C have type 755all values passed between Lua and C have type
759\verb'lua_Object'\Deffunc{lua_Object}, 756\verb'lua_Object'\Deffunc{lua_Object},
760which works like an abstract type in C that can hold any Lua value. 757which works like an abstract type in C that can hold any Lua value.
758Values of type \verb'lua_Object' have no meaning outside Lua;
759for instance,
760the comparisson of two \verb"lua_Object's" is of no significance.
761 761
762Lua has automatic memory management, and garbage collection. 762Lua has automatic memory management, and garbage collection.
763Because of that, a \verb'lua_Object' has a limited scope, 763Because of that, a \verb'lua_Object' has a limited scope,
@@ -856,7 +856,7 @@ and leave the result on the top of the Lua stack,
856where it can be assigned to a Lua variable, 856where it can be assigned to a Lua variable,
857passed as paramenter to a Lua function, etc (see below). \label{pushing} 857passed as paramenter to a Lua function, etc (see below). \label{pushing}
858\verb'lua_pushliteral' is like \verb'lua_pushstring', 858\verb'lua_pushliteral' is like \verb'lua_pushstring',
859but also puts the string in the Lua literal table. 859but also puts the string in the Lua literal table and merges duplications.
860This avoids the string to be garbage collected, 860This avoids the string to be garbage collected,
861and therefore has a better overall performance. 861and therefore has a better overall performance.
862As a rule, when the string to be pushed is a literal, 862As a rule, when the string to be pushed is a literal,
@@ -885,6 +885,9 @@ one can use the function:
885\begin{verbatim} 885\begin{verbatim}
886lua_Object lua_getglobal (char *varname); 886lua_Object lua_getglobal (char *varname);
887\end{verbatim} 887\end{verbatim}
888As in Lua, if the value of the global is \nil,
889the \verb'"getglobal"' fallback is called.
890
888To store a value previously pushed onto the stack in a global variable, 891To store a value previously pushed onto the stack in a global variable,
889there is the function: 892there is the function:
890\Deffunc{lua_storeglobal} 893\Deffunc{lua_storeglobal}
@@ -904,15 +907,15 @@ As in Lua, if the first object is not a table,
904or the index is not present in the table, 907or the index is not present in the table,
905the correspondent fallback is called. 908the correspondent fallback is called.
906 909
907For compatibility with previous versions of the API, 910%For compatibility with previous versions of the API,
908the following macros are supported: 911%the following macros are supported:
909\Deffunc{lua_getindexed}\Deffunc{lua_getfield} 912%\Deffunc{lua_getindexed}\Deffunc{lua_getfield}
910\begin{verbatim} 913%\begin{verbatim}
911lua_Object lua_getindexed (lua_Object table, float index); 914%lua_Object lua_getindexed (lua_Object table, float index);
912lua_Object lua_getfield (lua_Object table, char *field); 915%lua_Object lua_getfield (lua_Object table, char *field);
913\end{verbatim} 916%\end{verbatim}
914The first one is used for numeric indices, 917%The first one is used for numeric indices,
915while the second can be used for any string index. 918%while the second can be used for any string index.
916 919
917To store a value in an index, 920To store a value in an index,
918the program must push onto the stack the table, the index, 921the program must push onto the stack the table, the index,
@@ -1009,7 +1012,7 @@ The first parameter is the fallback name,
1009and the second a CFunction to be used as the new fallback. 1012and the second a CFunction to be used as the new fallback.
1010This function returns a \verb'lua_Object', 1013This function returns a \verb'lua_Object',
1011which is the old fallback value, 1014which is the old fallback value,
1012or nil on fail (invalid fallback name). 1015or \nil\ on fail (invalid fallback name).
1013This old value can be used for chaining fallbacks. 1016This old value can be used for chaining fallbacks.
1014 1017
1015An example of C code calling a Lua function is shown in 1018An example of C code calling a Lua function is shown in
@@ -1331,8 +1334,8 @@ then a \Index{piped input} is open, via function \IndexVerb{popen}.
1331 1334
1332This function opens a file named \verb'filename' and sets it as the 1335This function opens a file named \verb'filename' and sets it as the
1333{\em current} output file. 1336{\em current} output file.
1334Notice that, if the file already exists, it is completely erased with this 1337Notice that, if the file already exists,
1335operation. 1338it will be {\em completely erased} with this operation.
1336When called without parameters, 1339When called without parameters,
1337this function closes the current output file, 1340this function closes the current output file,
1338and restores \verb'stdout' as the current output file. 1341and restores \verb'stdout' as the current output file.
@@ -1382,7 +1385,7 @@ Particularly, the format \verb'"s1"' reads a single character.
1382\subsubsection*{{\tt readuntil (char)}}\Deffunc{readuntil} 1385\subsubsection*{{\tt readuntil (char)}}\Deffunc{readuntil}
1383 1386
1384Reads the current input until the first ocurrence of the given character. 1387Reads the current input until the first ocurrence of the given character.
1385When called with no parameters or with nil, 1388When called with no parameters,
1386reads until the end of the current input file. 1389reads until the end of the current input file.
1387Returns the string read. 1390Returns the string read.
1388The character itself is not read. 1391The character itself is not read.
@@ -1453,6 +1456,49 @@ It does not intend to cover the whole language,
1453but only to illustrate some interesting uses of the system. 1456but only to illustrate some interesting uses of the system.
1454 1457
1455 1458
1459\subsection{\Index{Data Structures}}
1460Tables are a strong unifying data constructor.
1461They directly implement a multitude of data types,
1462like ordinary arrays, records, sets, bags, and lists.
1463
1464Arrays need no explanations.
1465In Lua, it is conventional to start indices from 1,
1466but this is only a convention.
1467Arrays can be indexed by 0, negative numbers, or any other value (but \nil).
1468Records are also trivially implemented by the syntactic sugar
1469\verb'a.x'.
1470
1471The best way to implement a set is to use the indices of a table.
1472The statement \verb's = {}' creates an empty set \verb's'.
1473The statement \verb's[x] = 1' inserts the value of \verb'x' into
1474the set \verb's'.
1475The expression \verb's[x]' is true if and only if
1476\verb'x' belongs to \verb's'.
1477Finally, the statement \verb's[x] = nil' erases \verb'x' from \verb's'.
1478
1479Bags can be implemented similarly to sets,
1480but using the value associated to an element as its counter.
1481So, to insert an element,
1482the following code is enough:
1483\begin{verbatim}
1484if s[x] then s[x] = s[x]+1
1485else s[x] = 1 end
1486\end{verbatim}
1487and to remove an element:
1488\begin{verbatim}
1489if s[x] then s[x] = s[x]-1 end
1490if s[x] == 0 then s[x] = nil end
1491\end{verbatim}
1492
1493Lisp-like lists also have an easy implementation.
1494The ``cons'' of two elements \verb'x' and \verb'y' can be
1495created with the code \verb'l = {car=x, cdr=y}'.
1496The expression \verb'l.car' extracts the header,
1497while \verb'l.cdr' extracts the tail.
1498An alternative way is to create the list directly with \verb'l={x,y}',
1499and then to extract the header with \verb'l[1]' and
1500the tail with \verb'l[2]'.
1501
1456\subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext} 1502\subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext}
1457\Deffunc{next}\Deffunc{nextvar} 1503\Deffunc{next}\Deffunc{nextvar}
1458This example shows how to use the function \verb'next' to iterate 1504This example shows how to use the function \verb'next' to iterate
@@ -1654,6 +1700,64 @@ This code must be registered with:
1654Notice how the string \verb'"parent"' is kept 1700Notice how the string \verb'"parent"' is kept
1655locked in Lua for optimal performance. 1701locked in Lua for optimal performance.
1656 1702
1703\subsection{\Index{Programming with Classes}}
1704There are many different ways to do object-oriented programming in Lua.
1705This section presents one possible way to
1706implement classes,
1707using the inheritance mechanism presented above.
1708
1709As one could expect, a good way to represent a class is
1710as a table.
1711This table will contain all instance methods of the class,
1712plus eventual default values for instance variables.
1713An instance of a class has its \verb'parent' field pointing to
1714the class,
1715and so it ``inherits'' all methods.
1716
1717For instance, a class \verb'Point' can be described as in
1718Figure~\ref{Point}.
1719Function \verb'create' helps the creation of new points,
1720adding the parent field.
1721Function \verb'move' is an example of an instance method.
1722\begin{figure}
1723\Line
1724\begin{verbatim}
1725Point = {x = 0, y = 0}
1726
1727function Point:create (o)
1728 o.parent = self
1729 return o
1730end
1731
1732function Point:move (p)
1733 self.x = self.x + p.x
1734 self.y = self.y + p.y
1735end
1736
1737...
1738
1739--
1740-- creating points
1741--
1742p1 = Point:create{x = 10, y = 20}
1743p2 = Point:create{x = 10} -- y will be inherited until it is set
1744
1745--
1746-- example of a method invocation
1747--
1748p1:move(p2)
1749\end{verbatim}
1750\caption{A Class Point.\label{Point}}
1751\Line
1752\end{figure}
1753Finally, a subclass can be created as a new table,
1754with the \verb'parent' field pointing to its superclass.
1755It is interesting to notice how the use of \verb'self' in
1756method \verb'create' allows this method to work properly even
1757when inherited by a subclass.
1758As usual, a subclass may overwrite any inherited method with
1759its own version.
1760
1657\subsection{\Index{Modules}} 1761\subsection{\Index{Modules}}
1658Here we explain one possible way to simulate modules in Lua. 1762Here we explain one possible way to simulate modules in Lua.
1659The main idea is to use a table to store the module functions. 1763The main idea is to use a table to store the module functions.
@@ -1673,7 +1777,10 @@ end
1673Any code that needs this module has only to execute 1777Any code that needs this module has only to execute
1674\verb'dofile("filename")', where \verb'filename' is the file 1778\verb'dofile("filename")', where \verb'filename' is the file
1675where the module is written. 1779where the module is written.
1676After this, any function can be called with \verb'modulename.foo(...)'. 1780After this, any function can be called with
1781\begin{verbatim}
1782modulename.foo(...)
1783\end{verbatim}
1677 1784
1678If a module function is going to be used many times, 1785If a module function is going to be used many times,
1679the program can give a local name to it. 1786the program can give a local name to it.