aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--manual.tex704
1 files changed, 158 insertions, 546 deletions
diff --git a/manual.tex b/manual.tex
index 6e3779d7..15a9b1b4 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.27 1997/02/21 15:19:37 roberto Exp roberto $ 1% $Id: manual.tex,v 1.29 1997/03/06 21:13:34 roberto Exp $
2 2
3\documentstyle[fullpage,11pt,bnf]{article} 3\documentstyle[fullpage,11pt,bnf]{article}
4 4
@@ -35,7 +35,7 @@ Waldemar Celes
35\tecgraf\ --- Departamento de Inform\'atica --- PUC-Rio 35\tecgraf\ --- Departamento de Inform\'atica --- PUC-Rio
36} 36}
37 37
38\date{\small \verb$Date: 1997/02/21 15:19:37 $} 38\date{\small \verb$Date: 1997/03/06 21:13:34 $}
39 39
40\maketitle 40\maketitle
41 41
@@ -48,8 +48,6 @@ Lua is an extension programming language designed to be used
48as a configuration language for any program that needs one. 48as a configuration language for any program that needs one.
49This document describes version \Version\ of the Lua programming language and 49This document describes version \Version\ of the Lua programming language and
50the API that allows interaction between Lua programs and their host C programs. 50the API that allows interaction between Lua programs and their host C programs.
51The document also presents some examples of using the main
52features of the system.
53\end{abstract} 51\end{abstract}
54 52
55\vspace{4ex} 53\vspace{4ex}
@@ -64,8 +62,6 @@ uma.
64Este documento descreve a vers\~ao \Version\ da linguagem de 62Este documento descreve a vers\~ao \Version\ da linguagem de
65programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite 63programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
66a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. 64a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
67O documento tamb\'em apresenta alguns exemplos de uso das principais
68ca\-racte\-r\'{\i}sticas do sistema.
69\end{quotation} 65\end{quotation}
70 66
71 67
@@ -770,8 +766,6 @@ Its first argument is the name of a fallback condition,
770and the second argument is the new function to be called. 766and the second argument is the new function to be called.
771It returns the old handler function for the given fallback. 767It returns the old handler function for the given fallback.
772 768
773Section~\ref{exfallback} shows an example of the use of fallbacks.
774
775 769
776\subsection{Error Handling} \label{error} 770\subsection{Error Handling} \label{error}
777 771
@@ -811,8 +805,8 @@ the set of C functions available to the host program to communicate
811with the library. 805with the library.
812The API functions can be classified in the following categories: 806The API functions can be classified in the following categories:
813\begin{enumerate} 807\begin{enumerate}
808\item exchanging values between C and Lua;
814\item executing Lua code; 809\item executing Lua code;
815\item converting values between C and Lua;
816\item manipulating (reading and writing) Lua objects; 810\item manipulating (reading and writing) Lua objects;
817\item calling Lua functions; 811\item calling Lua functions;
818\item C functions to be called by Lua; 812\item C functions to be called by Lua;
@@ -821,25 +815,7 @@ The API functions can be classified in the following categories:
821All API functions and related types and constants 815All API functions and related types and constants
822are declared in the header file \verb'lua.h'. 816are declared in the header file \verb'lua.h'.
823 817
824\subsection{Executing Lua Code} 818\subsection{Exchanging Values between C and Lua} \label{valuesCLua}
825A host program can execute Lua chunks written in a file or in a string
826using the following functions:
827\Deffunc{lua_dofile}\Deffunc{lua_dostring}
828\begin{verbatim}
829int lua_dofile (char *filename);
830int lua_dostring (char *string);
831\end{verbatim}
832Both functions return an error code:
8330, in case of success; non zero, in case of errors.
834More specifically, \verb'lua_dofile' returns 2 if for any reason
835it could not open the file.
836The function \verb'lua_dofile', if called with argument \verb'NULL',
837executes the \verb|stdin| stream.
838Function \verb'lua_dofile' is also able to execute pre-compiled chunks.
839It automatically detects whether the file is text or binary,
840and loads it accordingly (see program \IndexVerb{luac}).
841
842\subsection{Converting Values between C and Lua} \label{valuesCLua}
843Because Lua has no static type system, 819Because Lua has no static type system,
844all values passed between Lua and C have type 820all values passed between Lua and C have type
845\verb'lua_Object'\Deffunc{lua_Object}, 821\verb'lua_Object'\Deffunc{lua_Object},
@@ -848,35 +824,13 @@ Values of type \verb'lua_Object' have no meaning outside Lua;
848for instance, 824for instance,
849the comparisson of two \verb"lua_Object's" is undefined. 825the comparisson of two \verb"lua_Object's" is undefined.
850 826
851Because Lua has automatic memory management and garbage collection,
852a \verb'lua_Object' has a limited scope,
853and is only valid inside the {\em block\/} where it was created.
854A C function called from Lua is a block,
855and its parameters are valid only until its end.
856It is good programming practice to convert Lua objects to C values
857as soon as they are available,
858and never to store \verb'lua_Object's in C global variables.
859
860When C code calls Lua repeatedly, as in a loop,
861objects returned by these calls accumulate,
862and may create a memory problem.
863To avoid this,
864nested blocks can be defined with the functions:
865\begin{verbatim}
866void lua_beginblock (void);
867void lua_endblock (void);
868\end{verbatim}
869After the end of the block,
870all \verb'lua_Object''s created inside it are released.
871The use of explicit nested blocks is encouraged.
872
873To check the type of a \verb'lua_Object', 827To check the type of a \verb'lua_Object',
874the following function is available: 828the following function is available:
875\Deffunc{lua_type} 829\Deffunc{lua_type}
876\begin{verbatim} 830\begin{verbatim}
877int lua_type (lua_Object object); 831int lua_type (lua_Object object);
878\end{verbatim} 832\end{verbatim}
879plus the following macros and functions: 833plus the following functions:
880\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} 834\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring}
881\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} 835\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata}
882\Deffunc{lua_isfunction} 836\Deffunc{lua_isfunction}
@@ -929,16 +883,53 @@ The type \verb'lua_CFunction' is explained in Section~\ref{LuacallC}.
929This \verb'lua_Object' must have type {\em userdata\/}; 883This \verb'lua_Object' must have type {\em userdata\/};
930otherwise, the function returns 0 (the \verb|NULL| pointer). 884otherwise, the function returns 0 (the \verb|NULL| pointer).
931 885
932The reverse process, that is, passing a specific C value to Lua, 886Because Lua has automatic memory management and garbage collection,
887a \verb'lua_Object' has a limited scope,
888and is only valid inside the {\em block\/} where it was created.
889A C function called from Lua is a block,
890and its parameters are valid only until its end.
891It is good programming practice to convert Lua objects to C values
892as soon as they are available,
893and never to store \verb'lua_Object's in C global variables.
894
895
896All comunication between Lua and C is done through two
897abstract data types, called \Def{lua2C} and \Def{C2lua}.
898The first one, as the name implies, is used to pass values
899from Lua to C: parameters when Lua calls C and results when C calls Lua.
900The structure C2lua is used in the reverse direction:
901parameters when C calls Lua and results when Lua calls C.
902Notice that the structure lua2C cannot be directly modified by C code,
903while the structure C2lua cannot be ``read'' by C code.
904
905The structure lua2C is an abstract array,
906which can be indexed with the function:
907\Deffunc{lua_lua2C}
908\begin{verbatim}
909lua_Object lua_lua2C (int number);
910\end{verbatim}
911where \verb'number' starts with 1.
912When called with a number larger than the array size,
913this function returns
914\verb'LUA_NOOBJECT'\Deffunc{LUA_NOOBJECT}.
915In this way, it is possible to write C functions that receive
916a variable number of parameters,
917and to call Lua functions that return a variable number of results.
918
919The second structure, C2lua, is a stack.
920Pushing elements into this stack
933is done by using the following functions: 921is done by using the following functions:
934\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring} 922\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring}
935\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} 923\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}
936\Deffunc{lua_pushuserdata} 924\Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
925\Deffunc{lua_pushuserdata}\label{pushing}
937\begin{verbatim} 926\begin{verbatim}
938void lua_pushnumber (double n); 927void lua_pushnumber (double n);
939void lua_pushstring (char *s); 928void lua_pushstring (char *s);
940void lua_pushcfunction (lua_CFunction f); 929void lua_pushcfunction (lua_CFunction f);
941void lua_pushusertag (void *u, int tag); 930void lua_pushusertag (void *u, int tag);
931void lua_pushnil (void);
932void lua_pushobject (lua_Object object);
942\end{verbatim} 933\end{verbatim}
943plus the macro: 934plus the macro:
944\begin{verbatim} 935\begin{verbatim}
@@ -946,9 +937,7 @@ void lua_pushuserdata (void *u);
946\end{verbatim} 937\end{verbatim}
947All of them receive a C value, 938All of them receive a C value,
948convert it to a corresponding \verb'lua_Object', 939convert it to a corresponding \verb'lua_Object',
949and leave the result on the top of the Lua stack, 940and leave the result on the top of C2lua.
950where it can be assigned to a Lua variable,
951passed as parameter to a Lua function, etc. \label{pushing}
952 941
953User data can have different tags, 942User data can have different tags,
954whose semantics are only known to the host program. 943whose semantics are only known to the host program.
@@ -956,14 +945,51 @@ Any positive integer can be used to tag a user datum.
956When a user datum is retrieved, 945When a user datum is retrieved,
957the function \verb'lua_type' can be used to get its tag. 946the function \verb'lua_type' can be used to get its tag.
958 947
959To complete the set, 948{\em Please note:} most functions in the Lua API
960the value \nil\ or a \verb'lua_Object' can also be pushed onto the stack, 949use the structures lua2C and C2lua,
961with: 950and therefore change their contents.
962\Deffunc{lua_pushnil}\Deffunc{lua_pushobject} 951Great care must be taken,
952specially when pushing a sequence of objects into C2lua,
953to avoid using those functions.
954The family of functions \verb|lua_get*|, \verb|lua_is*|,
955plus the function \verb|lua_lua2C|,
956are safe to be called without modifying these structures;
957the family \verb|lua_push*| does not modify lua2C.
958All other functions may change lua2C and C2lua,
959unless noticed otherwise.
960
961When C code calls Lua repeatedly, as in a loop,
962objects returned by these calls accumulate,
963and may create a memory problem.
964To avoid this,
965nested blocks can be defined with the functions:
963\begin{verbatim} 966\begin{verbatim}
964void lua_pushnil (void); 967void lua_beginblock (void);
965void lua_pushobject (lua_Object object); 968void lua_endblock (void);
966\end{verbatim} 969\end{verbatim}
970After the end of the block,
971all \verb'lua_Object''s created inside it are released.
972The use of explicit nested blocks is strongly encouraged.
973
974\subsection{Executing Lua Code}
975A host program can execute Lua chunks written in a file or in a string
976using the following functions:
977\Deffunc{lua_dofile}\Deffunc{lua_dostring}
978\begin{verbatim}
979int lua_dofile (char *filename);
980int lua_dostring (char *string);
981\end{verbatim}
982Both functions return an error code:
9830, in case of success; non zero, in case of errors.
984More specifically, \verb'lua_dofile' returns 2 if for any reason
985it could not open the file.
986The function \verb'lua_dofile', if called with argument \verb'NULL',
987executes the \verb|stdin| stream.
988Function \verb'lua_dofile' is also able to execute pre-compiled chunks.
989It automatically detects whether the file is text or binary,
990and loads it accordingly (see program \IndexVerb{luac}).
991These functions also return, in structure lua2C,
992any values eventually returned by the chunks.
967 993
968 994
969\subsection{Manipulating Lua Objects} 995\subsection{Manipulating Lua Objects}
@@ -976,7 +1002,7 @@ lua_Object lua_getglobal (char *varname);
976As in Lua, if the value of the global is \nil, 1002As in Lua, if the value of the global is \nil,
977then the ``getglobal'' fallback is called. 1003then the ``getglobal'' fallback is called.
978 1004
979To store a value previously pushed onto the stack in a global variable, 1005To store a value previously pushed onto C2lua in a global variable,
980there is the function: 1006there is the function:
981\Deffunc{lua_storeglobal} 1007\Deffunc{lua_storeglobal}
982\begin{verbatim} 1008\begin{verbatim}
@@ -989,14 +1015,15 @@ The function
989\begin{verbatim} 1015\begin{verbatim}
990lua_Object lua_getsubscript (void); 1016lua_Object lua_getsubscript (void);
991\end{verbatim} 1017\end{verbatim}
992expects on the stack a table and an index, 1018expects on the stack C2lua a table and an index,
993and returns the contents of the table at that index. 1019and returns the contents of the table at that index.
994As in Lua, if the first object is not a table, 1020As in Lua, if the first object is not a table,
995or the index is not present in the table, 1021or the index is not present in the table,
996the corresponding fallback is called. 1022the corresponding fallback is called.
997 1023
998To store a value in an index, 1024To store a value in an index,
999the program must push the table, the index, and the value onto the stack, 1025the program must push the table, the index,
1026and the value onto C2lua,
1000and then call the function: 1027and then call the function:
1001\Deffunc{lua_storesubscript} 1028\Deffunc{lua_storesubscript}
1002\begin{verbatim} 1029\begin{verbatim}
@@ -1011,10 +1038,8 @@ lua_Object lua_createtable (void);
1011\end{verbatim} 1038\end{verbatim}
1012creates and returns a new, empty table. 1039creates and returns a new, empty table.
1013 1040
1014\begin{quotation} 1041As already noted,
1015\noindent 1042most functions from the Lua library receive parameters through C2lua.
1016{\em Please note\/}:
1017Most functions from the Lua library receive parameters through Lua's stack.
1018Because other functions also use this stack, 1043Because other functions also use this stack,
1019it is important that these 1044it is important that these
1020parameters be pushed just before the corresponding call, 1045parameters be pushed just before the corresponding call,
@@ -1040,20 +1065,15 @@ A correct solution could be:
1040 lua_pushobject(index); /* push index */ 1065 lua_pushobject(index); /* push index */
1041 result = lua_getsubscript(); 1066 result = lua_getsubscript();
1042\end{verbatim} 1067\end{verbatim}
1043The functions {\em lua\_getnumber}, {\em lua\_getstring},
1044{\em lua\_getuserdata}, and {\em lua\_getcfunction},
1045plus the family \verb|lua_is*|,
1046are safe to be called without modifying the stack.
1047\end{quotation}
1048 1068
1049\subsection{Calling Lua Functions} 1069\subsection{Calling Lua Functions}
1050Functions defined in Lua by a chunk executed with 1070Functions defined in Lua by a chunk executed with
1051\verb'dofile' or \verb'dostring' can be called from the host program. 1071\verb'dofile' or \verb'dostring' can be called from the host program.
1052This is done using the following protocol: 1072This is done using the following protocol:
1053first, the arguments to the function are pushed onto the Lua stack 1073first, the arguments to the function are pushed onto C2lua
1054\see{pushing}, in direct order, i.e., the first argument is pushed first. 1074\see{pushing}, in direct order, i.e., the first argument is pushed first.
1055Again, it is important to emphasize that, during this phase, 1075Again, it is important to emphasize that, during this phase,
1056no other Lua function can be called. 1076most other Lua functions cannot be called.
1057 1077
1058Then, the function is called using 1078Then, the function is called using
1059\Deffunc{lua_call}\Deffunc{lua_callfunction} 1079\Deffunc{lua_call}\Deffunc{lua_callfunction}
@@ -1066,15 +1086,22 @@ int lua_callfunction (lua_Object function);
1066\end{verbatim} 1086\end{verbatim}
1067Both functions return an error code: 1087Both functions return an error code:
10680, in case of success; non zero, in case of errors. 10880, in case of success; non zero, in case of errors.
1069Finally, the returned values (a Lua function may return many values) 1089Finally, the results (a Lua function may return many values)
1070can be retrieved with the macro 1090are returned in structure lua2C,
1091and can be retrieved with the macro \verb|lua_getresult|,
1071\Deffunc{lua_getresult} 1092\Deffunc{lua_getresult}
1093which is just another name to the function \verb|lua_lua2C|.
1094
1095The following example shows how a C program may call the
1096\verb|strsub| function in Lua to extract a piece of a string:
1072\begin{verbatim} 1097\begin{verbatim}
1073lua_Object lua_getresult (int number); 1098 /* assume that 's' and 'r' are strings (char *), 'i' and 'j' integers */
1099 lua_pushstring(s); /* 1st argument */
1100 lua_pushnumber(i); /* 2nd argument */
1101 lua_pushnumber(j); /* 3rd argument */
1102 lua_call("strsub"); /* call Lua function */
1103 r = lua_getstring(lua_getresult(1)); /* r = strsub(s, i, j) */
1074\end{verbatim} 1104\end{verbatim}
1075where \verb'number' is the order of the result, starting with 1.
1076When called with a number larger than the actual number of results,
1077this function returns \verb'LUA_NOOBJECT'.
1078 1105
1079Two special Lua functions have exclusive interfaces: 1106Two special Lua functions have exclusive interfaces:
1080\verb'error' and \verb'setfallback'. 1107\verb'error' and \verb'setfallback'.
@@ -1102,9 +1129,6 @@ which is the old fallback value,
1102or \nil\ on failure (invalid fallback name). 1129or \nil\ on failure (invalid fallback name).
1103This old value can be used for chaining fallbacks. 1130This old value can be used for chaining fallbacks.
1104 1131
1105An example of C code calling a Lua function is shown in
1106Section~\ref{exLuacall}.
1107
1108 1132
1109\subsection{C Functions} \label{LuacallC} 1133\subsection{C Functions} \label{LuacallC}
1110To register a C function to Lua, 1134To register a C function to Lua,
@@ -1129,27 +1153,48 @@ In order to communicate properly with Lua,
1129a C function must follow a protocol, 1153a C function must follow a protocol,
1130which defines the way parameters and results are passed. 1154which defines the way parameters and results are passed.
1131 1155
1132To access its arguments, a C function calls: 1156A C function receives its arguments in structure lua2C;
1133\Deffunc{lua_getparam} 1157to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam}
1134\begin{verbatim} 1158again just another name to \verb|lua_lua2C|.
1135lua_Object lua_getparam (int number); 1159To return values, a C function just pushes them onto the stack C2lua,
1136\end{verbatim}
1137where \verb'number' starts with 1 to get the first argument.
1138When called with a number larger than the actual number of arguments,
1139this function returns
1140\verb'LUA_NOOBJECT'\Deffunc{LUA_NOOBJECT}.
1141In this way, it is possible to write functions that work with
1142a variable number of parameters.
1143The funcion \verb|lua_getparam| can be called in any order,
1144and many times for the same index.
1145
1146To return values, a C function just pushes them onto the stack,
1147in direct order \see{valuesCLua}. 1160in direct order \see{valuesCLua}.
1148Like a Lua function, a C function called by Lua can also return 1161Like a Lua function, a C function called by Lua can also return
1149many results. 1162many results.
1150 1163
1151Section~\ref{exCFunction} presents an example of a CFunction. 1164As an example,
1165the code below shows a CFunction to compute the maximum of
1166a variable number of arguments:
1167\begin{verbatim}
1168void math_max (void)
1169{
1170 int i=1; /* argument count */
1171 double d, dmax;
1172 lua_Object o;
1173 /* the function must get at least one argument */
1174 if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
1175 lua_error("too few arguments to function `max'");
1176 /* and this argument must be a number */
1177 if (!lua_isnumber(o))
1178 lua_error("incorrect argument to function `max'");
1179 dmax = lua_getnumber(o);
1180 /* loops until there is no more arguments */
1181 while ((o = lua_getparam(i++)) != LUA_NOOBJECT) {
1182 if (!lua_isnumber(o))
1183 lua_error("incorrect argument to function `max'");
1184 d = lua_getnumber(o);
1185 if (d > dmax) dmax = d;
1186 }
1187 /* push the result to be returned */
1188 lua_pushnumber(dmax);
1189}
1190\end{verbatim}
1191To be available in Lua, this function must be registered:
1192\begin{verbatim}
1193lua_register ("max", math_max);
1194\end{verbatim}
1152 1195
1196For more examples, see files \verb|strlib.c|,
1197\verb|iolib.c| and \verb|mathlib.c| in Lua distribution.
1153 1198
1154\subsection{References to Lua Objects} 1199\subsection{References to Lua Objects}
1155 1200
@@ -1183,6 +1228,10 @@ and \verb'lua_pushobject' issues an error.
1183When a reference is no longer needed, 1228When a reference is no longer needed,
1184it can be freed with a call to \verb'lua_unref'. 1229it can be freed with a call to \verb'lua_unref'.
1185 1230
1231The function \verb|lua_pushref| does not corrupt the
1232structures lua2C and C2lua, and therefore is safe to
1233be called when pushing parameters onto C2lua.
1234
1186 1235
1187 1236
1188\section{Predefined Functions and Libraries} 1237\section{Predefined Functions and Libraries}
@@ -1252,7 +1301,6 @@ The order in which the indices are enumerated is not specified,
1252If the table is modified in any way during a traversal, 1301If the table is modified in any way during a traversal,
1253the semantics of \verb|next| is undefined. 1302the semantics of \verb|next| is undefined.
1254 1303
1255See Section~\ref{exnext} for an example of the use of this function.
1256This function cannot be written with the standard API. 1304This function cannot be written with the standard API.
1257 1305
1258\subsubsection*{\ff{\tt nextvar (name)}}\Deffunc{nextvar} 1306\subsubsection*{\ff{\tt nextvar (name)}}\Deffunc{nextvar}
@@ -1266,7 +1314,6 @@ or \nil\ if there are no more variables.
1266There can be no assignments to global variables during the traversal; 1314There can be no assignments to global variables during the traversal;
1267otherwise the semantics of \verb|nextvar| is undefined. 1315otherwise the semantics of \verb|nextvar| is undefined.
1268 1316
1269See Section~\ref{exnext} for an example of the use of this function.
1270This function cannot be written with the standard API. 1317This function cannot be written with the standard API.
1271 1318
1272\subsubsection*{\ff{\tt tostring (e)}}\Deffunc{tostring} 1319\subsubsection*{\ff{\tt tostring (e)}}\Deffunc{tostring}
@@ -1342,9 +1389,6 @@ This library provides generic functions for string manipulation,
1342such as finding and extracting substrings and pattern matching. 1389such as finding and extracting substrings and pattern matching.
1343When indexing a string, the first character is at position 1, 1390When indexing a string, the first character is at position 1,
1344not 0, as in C. 1391not 0, as in C.
1345See page~\pageref{pm} for an explanation about patterns,
1346and Section~\ref{exstring} for some examples on string manipulation
1347in Lua.
1348 1392
1349\subsubsection*{\ff{\tt strfind (str, pattern [, init [, plain]])}} 1393\subsubsection*{\ff{\tt strfind (str, pattern [, init [, plain]])}}
1350\Deffunc{strfind} 1394\Deffunc{strfind}
@@ -1385,7 +1429,7 @@ lower case letters changed to upper case.
1385All other characters are left unchanged. 1429All other characters are left unchanged.
1386 1430
1387\subsubsection*{\ff{\tt strrep (s, n)}}\Deffunc{strrep} 1431\subsubsection*{\ff{\tt strrep (s, n)}}\Deffunc{strrep}
1388Returns a string which is the concatenation of \verb-n- copies of 1432Returns a string which is the concatenation of \verb-n- copies of
1389the string \verb-s-. 1433the string \verb-s-.
1390 1434
1391\subsubsection*{\ff{\tt ascii (s [, i])}}\Deffunc{ascii} 1435\subsubsection*{\ff{\tt ascii (s [, i])}}\Deffunc{ascii}
@@ -1395,7 +1439,7 @@ If \verb'i' is absent, then it is assumed to be 1.
1395\subsubsection*{\ff{\tt format (formatstring, e1, e2, \ldots)}}\Deffunc{format} 1439\subsubsection*{\ff{\tt format (formatstring, e1, e2, \ldots)}}\Deffunc{format}
1396\label{format} 1440\label{format}
1397This function returns a formated version of its variable number of arguments 1441This function returns a formated version of its variable number of arguments
1398following the description given in its first argument (which must be a string). 1442following the description given in its first argument (which must be a string).
1399The format string follows the same rules as the \verb'printf' family of 1443The format string follows the same rules as the \verb'printf' family of
1400standard C functions. 1444standard C functions.
1401The only differences are that the options/modifiers 1445The only differences are that the options/modifiers
@@ -1446,7 +1490,7 @@ If the value returned by this function is a string,
1446then it is used as the replacement string; 1490then it is used as the replacement string;
1447otherwise, the replacement string is the empty string. 1491otherwise, the replacement string is the empty string.
1448 1492
1449An optional parameter \verb-n- limits 1493An optional parameter \verb-n- limits
1450the maximum number of substitutions to occur. 1494the maximum number of substitutions to occur.
1451For instance, when \verb-n- is 1 only the first occurrence of 1495For instance, when \verb-n- is 1 only the first occurrence of
1452\verb-pat- is replaced. 1496\verb-pat- is replaced.
@@ -1460,7 +1504,7 @@ Therefore, the whole expression:
1460\begin{verbatim} 1504\begin{verbatim}
1461 gsub("home = $HOME, user = $USER", "$(%w%w*)", getenv) 1505 gsub("home = $HOME, user = $USER", "$(%w%w*)", getenv)
1462\end{verbatim} 1506\end{verbatim}
1463may return the string: 1507returns a string like:
1464\begin{verbatim} 1508\begin{verbatim}
1465home = /home/roberto, user = roberto 1509home = /home/roberto, user = roberto
1466\end{verbatim} 1510\end{verbatim}
@@ -1489,7 +1533,7 @@ The following combinations are allowed in describing a character class:
1489\item[{\tt \%\em x}] (where {\em x} is any non alphanumeric character) --- 1533\item[{\tt \%\em x}] (where {\em x} is any non alphanumeric character) ---
1490represents the character {\em x}. 1534represents the character {\em x}.
1491This is the standard way to escape the magic characters \verb'()%.[*?'. 1535This is the standard way to escape the magic characters \verb'()%.[*?'.
1492\item[{\tt [char-set]}] --- 1536\item[{\tt [char-set]}] ---
1493Represents the class which is the union of all 1537Represents the class which is the union of all
1494characters in char-set. 1538characters in char-set.
1495To include a \verb']' in char-set, it must be the first character. 1539To include a \verb']' in char-set, it must be the first character.
@@ -1530,7 +1574,7 @@ such item matches a sub-string equal to the n-th captured string
1530(see below); 1574(see below);
1531\item 1575\item
1532{\tt \%b$xy$}, where $x$ and $y$ are two distinct characters; 1576{\tt \%b$xy$}, where $x$ and $y$ are two distinct characters;
1533such item mathes strings that start with $x$, end with $y$, 1577such item mathes strings that start with $x$, end with $y$,
1534and where the $x$ and $y$ are {\em balanced}. 1578and where the $x$ and $y$ are {\em balanced}.
1535That means that, if one reads the string from left to write, 1579That means that, if one reads the string from left to write,
1536counting plus 1 for an $x$ and minus 1 for a $y$, 1580counting plus 1 for an $x$ and minus 1 for a $y$,
@@ -1722,7 +1766,7 @@ Notice that the behavior of read patterns is different from
1722the regular pattern matching behavior, 1766the regular pattern matching behavior,
1723where a \verb'*' expands to the maximum length {\em such that\/} 1767where a \verb'*' expands to the maximum length {\em such that\/}
1724the rest of the pattern does not fail. 1768the rest of the pattern does not fail.
1725With the read pattern behavior 1769With the read pattern behavior
1726there is no need for backtracking the reading. 1770there is no need for backtracking the reading.
1727} 1771}
1728 1772
@@ -1913,438 +1957,6 @@ A hook is disabled when its value is \verb|NULL|,
1913which is the initial value of both hooks. 1957which is the initial value of both hooks.
1914 1958
1915 1959
1916\section{Some Examples}
1917
1918This section gives examples showing some features of Lua.
1919It does not intend to cover the whole language,
1920but only to illustrate some interesting uses of the system.
1921
1922
1923\subsection{\Index{Data Structures}}
1924Tables are a strong unifying data constructor.
1925They directly implement a multitude of data types,
1926like ordinary arrays, records, sets, bags, and lists.
1927
1928Arrays need no explanations.
1929In Lua, it is conventional to start indices from 1,
1930but this is only a convention.
1931Arrays can be indexed by 0, negative numbers, or any other value (except \nil).
1932Records are also trivially implemented by the syntactic sugar
1933\verb'a.x'.
1934
1935The best way to implement a set is to store
1936its elements as indices of a table.
1937The statement \verb's = {}' creates an empty set \verb's'.
1938The statement \verb's[x] = 1' inserts the value of \verb'x' into
1939the set \verb's'.
1940The expression \verb's[x]' is true if and only if
1941\verb'x' belongs to \verb's'.
1942Finally, the statement \verb's[x] = nil' removes \verb'x' from \verb's'.
1943
1944Bags can be implemented similarly to sets,
1945but using the value associated to an element as its counter.
1946So, to insert an element,
1947the following code is enough:
1948\begin{verbatim}
1949if s[x] then s[x] = s[x]+1 else s[x] = 1 end
1950\end{verbatim}
1951and to remove an element:
1952\begin{verbatim}
1953if s[x] then s[x] = s[x]-1 end
1954if s[x] == 0 then s[x] = nil end
1955\end{verbatim}
1956
1957Lisp-like lists also have an easy implementation.
1958The ``cons'' of two elements \verb'x' and \verb'y' can be
1959created with the code \verb'l = {car=x, cdr=y}'.
1960The expression \verb'l.car' extracts the header,
1961while \verb'l.cdr' extracts the tail.
1962An alternative way is to create the list directly with \verb'l={x,y}',
1963and then to extract the header with \verb'l[1]' and
1964the tail with \verb'l[2]'.
1965
1966\subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext}
1967\Deffunc{next}\Deffunc{nextvar}
1968This example shows how to use the function \verb'next' to iterate
1969over the fields of a table.
1970Function \IndexVerb{clone} receives any table and returns a clone of it.
1971\begin{verbatim}
1972function clone (t) -- t is a table
1973 local new_t = {} -- create a new table
1974 local i, v = next(t, nil) -- i is an index of t, v = t[i]
1975 while i do
1976 new_t[i] = v
1977 i, v = next(t, i) -- get next index
1978 end
1979 return new_t
1980end
1981\end{verbatim}
1982
1983The next example prints the names of all global variables
1984in the system with non nil values.
1985Notice that the traversal is made with local variables,
1986to avoid changing a global variable:
1987\begin{verbatim}
1988function printGlobalVariables ()
1989 local i, v = nextvar(nil)
1990 while i do
1991 print(i)
1992 i, v = nextvar(i)
1993 end
1994end
1995\end{verbatim}
1996
1997
1998\subsection{String Manipulation} \label{exstring}
1999
2000The first example is a function to trim extra white-spaces at the beginning
2001and end of a string.
2002\begin{verbatim}
2003function trim(s)
2004 local _, i = strfind(s, '^ *')
2005 local f, __ = strfind(s, ' *$')
2006 return strsub(s, i+1, f-1)
2007end
2008\end{verbatim}
2009
2010The second example shows a function that eliminates all spaces
2011of a string.
2012\begin{verbatim}
2013function remove_blanks (s)
2014 return gsub(s, "%s%s*", "")
2015end
2016\end{verbatim}
2017
2018
2019\subsection{\Index{Variable number of arguments}}
2020Lua does not provide any explicit mechanism to deal with
2021variable number of arguments in function calls.
2022However, one can use table constructors to simulate this mechanism.
2023As an example, suppose a function to concatenate all its arguments.
2024It could be written like
2025\begin{verbatim}
2026function concat (o)
2027 local i = 1
2028 local s = ''
2029 while o[i] do
2030 s = s .. o[i]
2031 i = i+1
2032 end
2033 return s
2034end
2035\end{verbatim}
2036To call it, one uses a table constructor to join all arguments:
2037\begin{verbatim}
2038 x = concat{"hello ", "john", " and ", "mary"}
2039\end{verbatim}
2040
2041\subsection{\Index{Persistence}}
2042Because of its reflexive facilities,
2043persistence in Lua can be achieved within the language.
2044This section shows some ways to store and retrieve values in Lua,
2045using a text file written in the language itself as the storage media.
2046
2047To store a single value with a name,
2048the following code is enough:
2049\begin{verbatim}
2050function store (name, value)
2051 write(format('\n%s =', name))
2052 write_value(value)
2053end
2054\end{verbatim}
2055\begin{verbatim}
2056function write_value (value)
2057 local t = type(value)
2058 if t == 'nil' then write('nil')
2059 elseif t == 'number' then write(value)
2060 elseif t == 'string' then write(value, 'q')
2061 end
2062end
2063\end{verbatim}
2064In order to restore this value, a \verb'lua_dofile' suffices.
2065
2066Storing tables is a little more complex.
2067Assuming that the table is a tree,
2068and that all indices are identifiers
2069(that is, the tables are being used as records),
2070then its value can be written directly with table constructors.
2071First, the function \verb'write_value' is changed to
2072\begin{verbatim}
2073function write_value (value)
2074 local t = type(value)
2075 if t == 'nil' then write('nil')
2076 elseif t == 'number' then write(value)
2077 elseif t == 'string' then write(value, 'q')
2078 elseif t == 'table' then write_record(value)
2079 end
2080end
2081\end{verbatim}
2082The function \verb'write_record' is:
2083\begin{verbatim}
2084function write_record(t)
2085 local i, v = next(t, nil)
2086 write('{') -- starts constructor
2087 while i do
2088 store(i, v)
2089 write(', ')
2090 i, v = next(t, i)
2091 end
2092 write('}') -- closes constructor
2093end
2094\end{verbatim}
2095
2096
2097\subsection{Inheritance} \label{exfallback}
2098The fallback for absent indices can be used to implement many
2099kinds of \Index{inheritance} in Lua.
2100As an example,
2101the following code implements single inheritance:
2102\begin{verbatim}
2103function Index (t,f)
2104 if f == 'parent' then -- to avoid loop
2105 return OldIndex(t,f)
2106 end
2107 local p = t.parent
2108 if type(p) == 'table' then
2109 return p[f]
2110 else
2111 return OldIndex(t,f)
2112 end
2113end
2114
2115OldIndex = setfallback("index", Index)
2116\end{verbatim}
2117Whenever Lua attempts to access an absent field in a table,
2118it calls the fallback function \verb'Index'.
2119If the table has a field \verb'parent' with a table value,
2120then Lua attempts to access the desired field in this parent object.
2121This process is repeated ``upwards'' until a value
2122for the field is found or the object has no parent.
2123In the latter case, the previous fallback is called to supply a value
2124for the field.
2125
2126When better performance is needed,
2127the same fallback may be implemented in C,
2128as illustrated in Figure~\ref{Cinher}.
2129\begin{figure}
2130\Line
2131\begin{verbatim}
2132#include "lua.h"
2133
2134int lockedParentName; /* lock index for the string "parent" */
2135int lockedOldIndex; /* previous fallback function */
2136
2137void callOldFallback (lua_Object table, lua_Object index)
2138{
2139 lua_Object oldIndex = lua_getref(lockedOldIndex);
2140 lua_pushobject(table);
2141 lua_pushobject(index);
2142 lua_callfunction(oldIndex);
2143 if (lua_getresult(1) != LUA_NOOBJECT)
2144 lua_pushobject(lua_getresult(1)); /* return result */
2145}
2146
2147void Index (void)
2148{
2149 lua_Object table = lua_getparam(1);
2150 lua_Object index = lua_getparam(2);
2151 lua_Object parent;
2152 if (lua_isstring(index) && strcmp(lua_getstring(index), "parent") == 0)
2153 {
2154 callOldFallback(table, index);
2155 return;
2156 }
2157 lua_pushobject(table);
2158 lua_pushref(lockedParentName);
2159 parent = lua_getsubscript();
2160 if (lua_istable(parent))
2161 {
2162 lua_pushobject(parent);
2163 lua_pushobject(index);
2164 lua_pushobject(lua_getsubscript()); /* return result from getsubscript */
2165 }
2166 else
2167 callOldFallback(table, index);
2168}
2169\end{verbatim}
2170\caption{Inheritance in C.\label{Cinher}}
2171\Line
2172\end{figure}
2173This code must be registered with:
2174\begin{verbatim}
2175 lua_pushstring("parent");
2176 lockedParentName = lua_ref(1);
2177 lua_pushobject(lua_setfallback("index", Index));
2178 lockedOldIndex = lua_ref(1);
2179\end{verbatim}
2180Notice how the string \verb'"parent"' is kept
2181locked in Lua for optimal performance.
2182
2183\subsection{\Index{Programming with Classes}}
2184There are many different ways to do object-oriented programming in Lua.
2185This section presents one possible way to
2186implement classes,
2187using the inheritance mechanism presented above.
2188{\em Please note: the following examples only work
2189with the index fallback redefined according to
2190Section~\ref{exfallback}}.
2191
2192As one could expect, a good way to represent a class is
2193with a table.
2194This table will contain all instance methods of the class,
2195plus optional default values for instance variables.
2196An instance of a class has its \verb'parent' field pointing to
2197the class,
2198and so it ``inherits'' all methods.
2199
2200For instance, a class \verb'Point' can be described as in
2201Figure~\ref{Point}.
2202Function \verb'create' helps the creation of new points,
2203adding the parent field.
2204Function \verb'move' is an example of an instance method.
2205\begin{figure}
2206\Line
2207\begin{verbatim}
2208Point = {x = 0, y = 0}
2209
2210function Point:create (o)
2211 o.parent = self
2212 return o
2213end
2214
2215function Point:move (p)
2216 self.x = self.x + p.x
2217 self.y = self.y + p.y
2218end
2219
2220...
2221
2222--
2223-- creating points
2224--
2225p1 = Point:create{x = 10, y = 20}
2226p2 = Point:create{x = 10} -- y will be inherited until it is set
2227
2228--
2229-- example of a method invocation
2230--
2231p1:move(p2)
2232\end{verbatim}
2233\caption{A Class {\tt Point}.\label{Point}}
2234\Line
2235\end{figure}
2236Finally, a subclass can be created as a new table,
2237with the \verb'parent' field pointing to its superclass.
2238It is interesting to notice how the use of \verb'self' in
2239method \verb'create' allows this method to work properly even
2240when inherited by a subclass.
2241As usual, a subclass may overwrite any inherited method with
2242its own version.
2243
2244\subsection{\Index{Modules}}
2245Here we explain one possible way to simulate modules in Lua.
2246The main idea is to use a table to store the module functions.
2247
2248A module should be written as a separate chunk, starting with:
2249\begin{verbatim}
2250if modulename then return end -- avoid loading twice the same module
2251modulename = {} -- create a table to represent the module
2252\end{verbatim}
2253After that, functions can be directly defined with the syntax
2254\begin{verbatim}
2255function modulename.foo (...)
2256 ...
2257end
2258\end{verbatim}
2259
2260Any code that needs this module has only to execute
2261\verb'dofile("filename")', where \verb'filename' is the file
2262where the module is written.
2263After this, any function can be called with
2264\begin{verbatim}
2265modulename.foo(...)
2266\end{verbatim}
2267
2268If a module function is going to be used many times,
2269the program can give a local name to it.
2270Because functions are values, it is enough to write
2271\begin{verbatim}
2272localname = modulename.foo
2273\end{verbatim}
2274Finally, a module may be {\em opened},
2275giving direct access to all its functions,
2276as shown in the code in Figure~\ref{openmod}.
2277\begin{figure}
2278\Line
2279\begin{verbatim}
2280function open (mod)
2281 local n, f = next(mod, nil)
2282 while n do
2283 setglobal(n, f)
2284 n, f = next(mod, n)
2285 end
2286end
2287\end{verbatim}
2288\caption{Opening a module.\label{openmod}}
2289\Line
2290\end{figure}
2291
2292\subsection{A CFunction} \label{exCFunction}\index{functions in C}
2293A CFunction to compute the maximum of a variable number of arguments
2294is shown in Figure~\ref{Cmax}.
2295\begin{figure}
2296\Line
2297\begin{verbatim}
2298void math_max (void)
2299{
2300 int i=1; /* number of arguments */
2301 double d, dmax;
2302 lua_Object o;
2303 /* the function must get at least one argument */
2304 if ((o = lua_getparam(i++)) == LUA_NOOBJECT)
2305 lua_error ("too few arguments to function `max'");
2306 /* and this argument must be a number */
2307 if (!lua_isnumber(o))
2308 lua_error ("incorrect argument to function `max'");
2309 dmax = lua_getnumber (o);
2310 /* loops until there is no more arguments */
2311 while ((o = lua_getparam(i++)) != LUA_NOOBJECT)
2312 {
2313 if (!lua_isnumber(o))
2314 lua_error ("incorrect argument to function `max'");
2315 d = lua_getnumber (o);
2316 if (d > dmax) dmax = d;
2317 }
2318 /* push the result to be returned */
2319 lua_pushnumber (dmax);
2320}
2321\end{verbatim}
2322\caption{C function {\tt math\_max}.\label{Cmax}}
2323\Line
2324\end{figure}
2325After registered with
2326\begin{verbatim}
2327lua_register ("max", math_max);
2328\end{verbatim}
2329this function is available in Lua, as follows:
2330\begin{verbatim}
2331i = max(4, 5, 10, -34) -- i receives 10
2332\end{verbatim}
2333
2334
2335\subsection{Calling Lua Functions} \label{exLuacall}
2336
2337This example illustrates how a C function can call the Lua function
2338\verb'remove_blanks' presented in Section~\ref{exstring}.
2339\begin{verbatim}
2340void remove_blanks (char *s)
2341{
2342 lua_pushstring(s); /* prepare parameter */
2343 lua_call("remove_blanks"); /* call Lua function */
2344 strcpy(s, lua_getstring(lua_getresult(1))); /* copy result back to 's' */
2345}
2346\end{verbatim}
2347
2348 1960
2349\section{\Index{Lua Stand-alone}} \label{lua-sa} 1961\section{\Index{Lua Stand-alone}} \label{lua-sa}
2350 1962
@@ -2484,7 +2096,7 @@ The function \verb'lua_pop' is no longer available,
2484since it could lead to strange behavior. 2096since it could lead to strange behavior.
2485In particular, 2097In particular,
2486to access results returned from a Lua function, 2098to access results returned from a Lua function,
2487the new macro \verb'lua_getresult' should be used. 2099the new macro \verb|lua_getresult| should be used.
2488\item 2100\item
2489The old functions \verb'lua_storefield' and \verb'lua_storeindexed' 2101The old functions \verb'lua_storefield' and \verb'lua_storeindexed'
2490have been replaced by 2102have been replaced by