diff options
| author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1997-03-06 19:19:08 -0300 |
|---|---|---|
| committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1997-03-06 19:19:08 -0300 |
| commit | a82ab0852eaca43cb56be5134833c97e6bb7ac98 (patch) | |
| tree | 6ec6e0957542be19eebf84818ab4142d9855d549 | |
| parent | b8af9c56c95722e7a3289f02568b9e2a7495c484 (diff) | |
| download | lua-a82ab0852eaca43cb56be5134833c97e6bb7ac98.tar.gz lua-a82ab0852eaca43cb56be5134833c97e6bb7ac98.tar.bz2 lua-a82ab0852eaca43cb56be5134833c97e6bb7ac98.zip | |
new explanation about communication between Lua and C.
| -rw-r--r-- | manual.tex | 704 |
1 files changed, 158 insertions, 546 deletions
| @@ -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 | |||
| 48 | as a configuration language for any program that needs one. | 48 | as a configuration language for any program that needs one. |
| 49 | This document describes version \Version\ of the Lua programming language and | 49 | This document describes version \Version\ of the Lua programming language and |
| 50 | the API that allows interaction between Lua programs and their host C programs. | 50 | the API that allows interaction between Lua programs and their host C programs. |
| 51 | The document also presents some examples of using the main | ||
| 52 | features of the system. | ||
| 53 | \end{abstract} | 51 | \end{abstract} |
| 54 | 52 | ||
| 55 | \vspace{4ex} | 53 | \vspace{4ex} |
| @@ -64,8 +62,6 @@ uma. | |||
| 64 | Este documento descreve a vers\~ao \Version\ da linguagem de | 62 | Este documento descreve a vers\~ao \Version\ da linguagem de |
| 65 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite | 63 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite |
| 66 | a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | 64 | a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. |
| 67 | O documento tamb\'em apresenta alguns exemplos de uso das principais | ||
| 68 | ca\-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, | |||
| 770 | and the second argument is the new function to be called. | 766 | and the second argument is the new function to be called. |
| 771 | It returns the old handler function for the given fallback. | 767 | It returns the old handler function for the given fallback. |
| 772 | 768 | ||
| 773 | Section~\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 | |||
| 811 | with the library. | 805 | with the library. |
| 812 | The API functions can be classified in the following categories: | 806 | The 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: | |||
| 821 | All API functions and related types and constants | 815 | All API functions and related types and constants |
| 822 | are declared in the header file \verb'lua.h'. | 816 | are 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} |
| 825 | A host program can execute Lua chunks written in a file or in a string | ||
| 826 | using the following functions: | ||
| 827 | \Deffunc{lua_dofile}\Deffunc{lua_dostring} | ||
| 828 | \begin{verbatim} | ||
| 829 | int lua_dofile (char *filename); | ||
| 830 | int lua_dostring (char *string); | ||
| 831 | \end{verbatim} | ||
| 832 | Both functions return an error code: | ||
| 833 | 0, in case of success; non zero, in case of errors. | ||
| 834 | More specifically, \verb'lua_dofile' returns 2 if for any reason | ||
| 835 | it could not open the file. | ||
| 836 | The function \verb'lua_dofile', if called with argument \verb'NULL', | ||
| 837 | executes the \verb|stdin| stream. | ||
| 838 | Function \verb'lua_dofile' is also able to execute pre-compiled chunks. | ||
| 839 | It automatically detects whether the file is text or binary, | ||
| 840 | and loads it accordingly (see program \IndexVerb{luac}). | ||
| 841 | |||
| 842 | \subsection{Converting Values between C and Lua} \label{valuesCLua} | ||
| 843 | Because Lua has no static type system, | 819 | Because Lua has no static type system, |
| 844 | all values passed between Lua and C have type | 820 | all 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; | |||
| 848 | for instance, | 824 | for instance, |
| 849 | the comparisson of two \verb"lua_Object's" is undefined. | 825 | the comparisson of two \verb"lua_Object's" is undefined. |
| 850 | 826 | ||
| 851 | Because Lua has automatic memory management and garbage collection, | ||
| 852 | a \verb'lua_Object' has a limited scope, | ||
| 853 | and is only valid inside the {\em block\/} where it was created. | ||
| 854 | A C function called from Lua is a block, | ||
| 855 | and its parameters are valid only until its end. | ||
| 856 | It is good programming practice to convert Lua objects to C values | ||
| 857 | as soon as they are available, | ||
| 858 | and never to store \verb'lua_Object's in C global variables. | ||
| 859 | |||
| 860 | When C code calls Lua repeatedly, as in a loop, | ||
| 861 | objects returned by these calls accumulate, | ||
| 862 | and may create a memory problem. | ||
| 863 | To avoid this, | ||
| 864 | nested blocks can be defined with the functions: | ||
| 865 | \begin{verbatim} | ||
| 866 | void lua_beginblock (void); | ||
| 867 | void lua_endblock (void); | ||
| 868 | \end{verbatim} | ||
| 869 | After the end of the block, | ||
| 870 | all \verb'lua_Object''s created inside it are released. | ||
| 871 | The use of explicit nested blocks is encouraged. | ||
| 872 | |||
| 873 | To check the type of a \verb'lua_Object', | 827 | To check the type of a \verb'lua_Object', |
| 874 | the following function is available: | 828 | the following function is available: |
| 875 | \Deffunc{lua_type} | 829 | \Deffunc{lua_type} |
| 876 | \begin{verbatim} | 830 | \begin{verbatim} |
| 877 | int lua_type (lua_Object object); | 831 | int lua_type (lua_Object object); |
| 878 | \end{verbatim} | 832 | \end{verbatim} |
| 879 | plus the following macros and functions: | 833 | plus 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}. | |||
| 929 | This \verb'lua_Object' must have type {\em userdata\/}; | 883 | This \verb'lua_Object' must have type {\em userdata\/}; |
| 930 | otherwise, the function returns 0 (the \verb|NULL| pointer). | 884 | otherwise, the function returns 0 (the \verb|NULL| pointer). |
| 931 | 885 | ||
| 932 | The reverse process, that is, passing a specific C value to Lua, | 886 | Because Lua has automatic memory management and garbage collection, |
| 887 | a \verb'lua_Object' has a limited scope, | ||
| 888 | and is only valid inside the {\em block\/} where it was created. | ||
| 889 | A C function called from Lua is a block, | ||
| 890 | and its parameters are valid only until its end. | ||
| 891 | It is good programming practice to convert Lua objects to C values | ||
| 892 | as soon as they are available, | ||
| 893 | and never to store \verb'lua_Object's in C global variables. | ||
| 894 | |||
| 895 | |||
| 896 | All comunication between Lua and C is done through two | ||
| 897 | abstract data types, called \Def{lua2C} and \Def{C2lua}. | ||
| 898 | The first one, as the name implies, is used to pass values | ||
| 899 | from Lua to C: parameters when Lua calls C and results when C calls Lua. | ||
| 900 | The structure C2lua is used in the reverse direction: | ||
| 901 | parameters when C calls Lua and results when Lua calls C. | ||
| 902 | Notice that the structure lua2C cannot be directly modified by C code, | ||
| 903 | while the structure C2lua cannot be ``read'' by C code. | ||
| 904 | |||
| 905 | The structure lua2C is an abstract array, | ||
| 906 | which can be indexed with the function: | ||
| 907 | \Deffunc{lua_lua2C} | ||
| 908 | \begin{verbatim} | ||
| 909 | lua_Object lua_lua2C (int number); | ||
| 910 | \end{verbatim} | ||
| 911 | where \verb'number' starts with 1. | ||
| 912 | When called with a number larger than the array size, | ||
| 913 | this function returns | ||
| 914 | \verb'LUA_NOOBJECT'\Deffunc{LUA_NOOBJECT}. | ||
| 915 | In this way, it is possible to write C functions that receive | ||
| 916 | a variable number of parameters, | ||
| 917 | and to call Lua functions that return a variable number of results. | ||
| 918 | |||
| 919 | The second structure, C2lua, is a stack. | ||
| 920 | Pushing elements into this stack | ||
| 933 | is done by using the following functions: | 921 | is 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} |
| 938 | void lua_pushnumber (double n); | 927 | void lua_pushnumber (double n); |
| 939 | void lua_pushstring (char *s); | 928 | void lua_pushstring (char *s); |
| 940 | void lua_pushcfunction (lua_CFunction f); | 929 | void lua_pushcfunction (lua_CFunction f); |
| 941 | void lua_pushusertag (void *u, int tag); | 930 | void lua_pushusertag (void *u, int tag); |
| 931 | void lua_pushnil (void); | ||
| 932 | void lua_pushobject (lua_Object object); | ||
| 942 | \end{verbatim} | 933 | \end{verbatim} |
| 943 | plus the macro: | 934 | plus the macro: |
| 944 | \begin{verbatim} | 935 | \begin{verbatim} |
| @@ -946,9 +937,7 @@ void lua_pushuserdata (void *u); | |||
| 946 | \end{verbatim} | 937 | \end{verbatim} |
| 947 | All of them receive a C value, | 938 | All of them receive a C value, |
| 948 | convert it to a corresponding \verb'lua_Object', | 939 | convert it to a corresponding \verb'lua_Object', |
| 949 | and leave the result on the top of the Lua stack, | 940 | and leave the result on the top of C2lua. |
| 950 | where it can be assigned to a Lua variable, | ||
| 951 | passed as parameter to a Lua function, etc. \label{pushing} | ||
| 952 | 941 | ||
| 953 | User data can have different tags, | 942 | User data can have different tags, |
| 954 | whose semantics are only known to the host program. | 943 | whose semantics are only known to the host program. |
| @@ -956,14 +945,51 @@ Any positive integer can be used to tag a user datum. | |||
| 956 | When a user datum is retrieved, | 945 | When a user datum is retrieved, |
| 957 | the function \verb'lua_type' can be used to get its tag. | 946 | the function \verb'lua_type' can be used to get its tag. |
| 958 | 947 | ||
| 959 | To complete the set, | 948 | {\em Please note:} most functions in the Lua API |
| 960 | the value \nil\ or a \verb'lua_Object' can also be pushed onto the stack, | 949 | use the structures lua2C and C2lua, |
| 961 | with: | 950 | and therefore change their contents. |
| 962 | \Deffunc{lua_pushnil}\Deffunc{lua_pushobject} | 951 | Great care must be taken, |
| 952 | specially when pushing a sequence of objects into C2lua, | ||
| 953 | to avoid using those functions. | ||
| 954 | The family of functions \verb|lua_get*|, \verb|lua_is*|, | ||
| 955 | plus the function \verb|lua_lua2C|, | ||
| 956 | are safe to be called without modifying these structures; | ||
| 957 | the family \verb|lua_push*| does not modify lua2C. | ||
| 958 | All other functions may change lua2C and C2lua, | ||
| 959 | unless noticed otherwise. | ||
| 960 | |||
| 961 | When C code calls Lua repeatedly, as in a loop, | ||
| 962 | objects returned by these calls accumulate, | ||
| 963 | and may create a memory problem. | ||
| 964 | To avoid this, | ||
| 965 | nested blocks can be defined with the functions: | ||
| 963 | \begin{verbatim} | 966 | \begin{verbatim} |
| 964 | void lua_pushnil (void); | 967 | void lua_beginblock (void); |
| 965 | void lua_pushobject (lua_Object object); | 968 | void lua_endblock (void); |
| 966 | \end{verbatim} | 969 | \end{verbatim} |
| 970 | After the end of the block, | ||
| 971 | all \verb'lua_Object''s created inside it are released. | ||
| 972 | The use of explicit nested blocks is strongly encouraged. | ||
| 973 | |||
| 974 | \subsection{Executing Lua Code} | ||
| 975 | A host program can execute Lua chunks written in a file or in a string | ||
| 976 | using the following functions: | ||
| 977 | \Deffunc{lua_dofile}\Deffunc{lua_dostring} | ||
| 978 | \begin{verbatim} | ||
| 979 | int lua_dofile (char *filename); | ||
| 980 | int lua_dostring (char *string); | ||
| 981 | \end{verbatim} | ||
| 982 | Both functions return an error code: | ||
| 983 | 0, in case of success; non zero, in case of errors. | ||
| 984 | More specifically, \verb'lua_dofile' returns 2 if for any reason | ||
| 985 | it could not open the file. | ||
| 986 | The function \verb'lua_dofile', if called with argument \verb'NULL', | ||
| 987 | executes the \verb|stdin| stream. | ||
| 988 | Function \verb'lua_dofile' is also able to execute pre-compiled chunks. | ||
| 989 | It automatically detects whether the file is text or binary, | ||
| 990 | and loads it accordingly (see program \IndexVerb{luac}). | ||
| 991 | These functions also return, in structure lua2C, | ||
| 992 | any 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); | |||
| 976 | As in Lua, if the value of the global is \nil, | 1002 | As in Lua, if the value of the global is \nil, |
| 977 | then the ``getglobal'' fallback is called. | 1003 | then the ``getglobal'' fallback is called. |
| 978 | 1004 | ||
| 979 | To store a value previously pushed onto the stack in a global variable, | 1005 | To store a value previously pushed onto C2lua in a global variable, |
| 980 | there is the function: | 1006 | there 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} |
| 990 | lua_Object lua_getsubscript (void); | 1016 | lua_Object lua_getsubscript (void); |
| 991 | \end{verbatim} | 1017 | \end{verbatim} |
| 992 | expects on the stack a table and an index, | 1018 | expects on the stack C2lua a table and an index, |
| 993 | and returns the contents of the table at that index. | 1019 | and returns the contents of the table at that index. |
| 994 | As in Lua, if the first object is not a table, | 1020 | As in Lua, if the first object is not a table, |
| 995 | or the index is not present in the table, | 1021 | or the index is not present in the table, |
| 996 | the corresponding fallback is called. | 1022 | the corresponding fallback is called. |
| 997 | 1023 | ||
| 998 | To store a value in an index, | 1024 | To store a value in an index, |
| 999 | the program must push the table, the index, and the value onto the stack, | 1025 | the program must push the table, the index, |
| 1026 | and the value onto C2lua, | ||
| 1000 | and then call the function: | 1027 | and 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} |
| 1012 | creates and returns a new, empty table. | 1039 | creates and returns a new, empty table. |
| 1013 | 1040 | ||
| 1014 | \begin{quotation} | 1041 | As already noted, |
| 1015 | \noindent | 1042 | most functions from the Lua library receive parameters through C2lua. |
| 1016 | {\em Please note\/}: | ||
| 1017 | Most functions from the Lua library receive parameters through Lua's stack. | ||
| 1018 | Because other functions also use this stack, | 1043 | Because other functions also use this stack, |
| 1019 | it is important that these | 1044 | it is important that these |
| 1020 | parameters be pushed just before the corresponding call, | 1045 | parameters 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} |
| 1043 | The functions {\em lua\_getnumber}, {\em lua\_getstring}, | ||
| 1044 | {\em lua\_getuserdata}, and {\em lua\_getcfunction}, | ||
| 1045 | plus the family \verb|lua_is*|, | ||
| 1046 | are safe to be called without modifying the stack. | ||
| 1047 | \end{quotation} | ||
| 1048 | 1068 | ||
| 1049 | \subsection{Calling Lua Functions} | 1069 | \subsection{Calling Lua Functions} |
| 1050 | Functions defined in Lua by a chunk executed with | 1070 | Functions 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. |
| 1052 | This is done using the following protocol: | 1072 | This is done using the following protocol: |
| 1053 | first, the arguments to the function are pushed onto the Lua stack | 1073 | first, 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. |
| 1055 | Again, it is important to emphasize that, during this phase, | 1075 | Again, it is important to emphasize that, during this phase, |
| 1056 | no other Lua function can be called. | 1076 | most other Lua functions cannot be called. |
| 1057 | 1077 | ||
| 1058 | Then, the function is called using | 1078 | Then, 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} |
| 1067 | Both functions return an error code: | 1087 | Both functions return an error code: |
| 1068 | 0, in case of success; non zero, in case of errors. | 1088 | 0, in case of success; non zero, in case of errors. |
| 1069 | Finally, the returned values (a Lua function may return many values) | 1089 | Finally, the results (a Lua function may return many values) |
| 1070 | can be retrieved with the macro | 1090 | are returned in structure lua2C, |
| 1091 | and can be retrieved with the macro \verb|lua_getresult|, | ||
| 1071 | \Deffunc{lua_getresult} | 1092 | \Deffunc{lua_getresult} |
| 1093 | which is just another name to the function \verb|lua_lua2C|. | ||
| 1094 | |||
| 1095 | The 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} |
| 1073 | lua_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} |
| 1075 | where \verb'number' is the order of the result, starting with 1. | ||
| 1076 | When called with a number larger than the actual number of results, | ||
| 1077 | this function returns \verb'LUA_NOOBJECT'. | ||
| 1078 | 1105 | ||
| 1079 | Two special Lua functions have exclusive interfaces: | 1106 | Two 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, | |||
| 1102 | or \nil\ on failure (invalid fallback name). | 1129 | or \nil\ on failure (invalid fallback name). |
| 1103 | This old value can be used for chaining fallbacks. | 1130 | This old value can be used for chaining fallbacks. |
| 1104 | 1131 | ||
| 1105 | An example of C code calling a Lua function is shown in | ||
| 1106 | Section~\ref{exLuacall}. | ||
| 1107 | |||
| 1108 | 1132 | ||
| 1109 | \subsection{C Functions} \label{LuacallC} | 1133 | \subsection{C Functions} \label{LuacallC} |
| 1110 | To register a C function to Lua, | 1134 | To register a C function to Lua, |
| @@ -1129,27 +1153,48 @@ In order to communicate properly with Lua, | |||
| 1129 | a C function must follow a protocol, | 1153 | a C function must follow a protocol, |
| 1130 | which defines the way parameters and results are passed. | 1154 | which defines the way parameters and results are passed. |
| 1131 | 1155 | ||
| 1132 | To access its arguments, a C function calls: | 1156 | A C function receives its arguments in structure lua2C; |
| 1133 | \Deffunc{lua_getparam} | 1157 | to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} |
| 1134 | \begin{verbatim} | 1158 | again just another name to \verb|lua_lua2C|. |
| 1135 | lua_Object lua_getparam (int number); | 1159 | To return values, a C function just pushes them onto the stack C2lua, |
| 1136 | \end{verbatim} | ||
| 1137 | where \verb'number' starts with 1 to get the first argument. | ||
| 1138 | When called with a number larger than the actual number of arguments, | ||
| 1139 | this function returns | ||
| 1140 | \verb'LUA_NOOBJECT'\Deffunc{LUA_NOOBJECT}. | ||
| 1141 | In this way, it is possible to write functions that work with | ||
| 1142 | a variable number of parameters. | ||
| 1143 | The funcion \verb|lua_getparam| can be called in any order, | ||
| 1144 | and many times for the same index. | ||
| 1145 | |||
| 1146 | To return values, a C function just pushes them onto the stack, | ||
| 1147 | in direct order \see{valuesCLua}. | 1160 | in direct order \see{valuesCLua}. |
| 1148 | Like a Lua function, a C function called by Lua can also return | 1161 | Like a Lua function, a C function called by Lua can also return |
| 1149 | many results. | 1162 | many results. |
| 1150 | 1163 | ||
| 1151 | Section~\ref{exCFunction} presents an example of a CFunction. | 1164 | As an example, |
| 1165 | the code below shows a CFunction to compute the maximum of | ||
| 1166 | a variable number of arguments: | ||
| 1167 | \begin{verbatim} | ||
| 1168 | void 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} | ||
| 1191 | To be available in Lua, this function must be registered: | ||
| 1192 | \begin{verbatim} | ||
| 1193 | lua_register ("max", math_max); | ||
| 1194 | \end{verbatim} | ||
| 1152 | 1195 | ||
| 1196 | For 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. | |||
| 1183 | When a reference is no longer needed, | 1228 | When a reference is no longer needed, |
| 1184 | it can be freed with a call to \verb'lua_unref'. | 1229 | it can be freed with a call to \verb'lua_unref'. |
| 1185 | 1230 | ||
| 1231 | The function \verb|lua_pushref| does not corrupt the | ||
| 1232 | structures lua2C and C2lua, and therefore is safe to | ||
| 1233 | be 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, | |||
| 1252 | If the table is modified in any way during a traversal, | 1301 | If the table is modified in any way during a traversal, |
| 1253 | the semantics of \verb|next| is undefined. | 1302 | the semantics of \verb|next| is undefined. |
| 1254 | 1303 | ||
| 1255 | See Section~\ref{exnext} for an example of the use of this function. | ||
| 1256 | This function cannot be written with the standard API. | 1304 | This 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. | |||
| 1266 | There can be no assignments to global variables during the traversal; | 1314 | There can be no assignments to global variables during the traversal; |
| 1267 | otherwise the semantics of \verb|nextvar| is undefined. | 1315 | otherwise the semantics of \verb|nextvar| is undefined. |
| 1268 | 1316 | ||
| 1269 | See Section~\ref{exnext} for an example of the use of this function. | ||
| 1270 | This function cannot be written with the standard API. | 1317 | This 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, | |||
| 1342 | such as finding and extracting substrings and pattern matching. | 1389 | such as finding and extracting substrings and pattern matching. |
| 1343 | When indexing a string, the first character is at position 1, | 1390 | When indexing a string, the first character is at position 1, |
| 1344 | not 0, as in C. | 1391 | not 0, as in C. |
| 1345 | See page~\pageref{pm} for an explanation about patterns, | ||
| 1346 | and Section~\ref{exstring} for some examples on string manipulation | ||
| 1347 | in 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. | |||
| 1385 | All other characters are left unchanged. | 1429 | All 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} |
| 1388 | Returns a string which is the concatenation of \verb-n- copies of | 1432 | Returns a string which is the concatenation of \verb-n- copies of |
| 1389 | the string \verb-s-. | 1433 | the 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} |
| 1397 | This function returns a formated version of its variable number of arguments | 1441 | This function returns a formated version of its variable number of arguments |
| 1398 | following the description given in its first argument (which must be a string). | 1442 | following the description given in its first argument (which must be a string). |
| 1399 | The format string follows the same rules as the \verb'printf' family of | 1443 | The format string follows the same rules as the \verb'printf' family of |
| 1400 | standard C functions. | 1444 | standard C functions. |
| 1401 | The only differences are that the options/modifiers | 1445 | The only differences are that the options/modifiers |
| @@ -1446,7 +1490,7 @@ If the value returned by this function is a string, | |||
| 1446 | then it is used as the replacement string; | 1490 | then it is used as the replacement string; |
| 1447 | otherwise, the replacement string is the empty string. | 1491 | otherwise, the replacement string is the empty string. |
| 1448 | 1492 | ||
| 1449 | An optional parameter \verb-n- limits | 1493 | An optional parameter \verb-n- limits |
| 1450 | the maximum number of substitutions to occur. | 1494 | the maximum number of substitutions to occur. |
| 1451 | For instance, when \verb-n- is 1 only the first occurrence of | 1495 | For 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} |
| 1463 | may return the string: | 1507 | returns a string like: |
| 1464 | \begin{verbatim} | 1508 | \begin{verbatim} |
| 1465 | home = /home/roberto, user = roberto | 1509 | home = /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) --- |
| 1490 | represents the character {\em x}. | 1534 | represents the character {\em x}. |
| 1491 | This is the standard way to escape the magic characters \verb'()%.[*?'. | 1535 | This is the standard way to escape the magic characters \verb'()%.[*?'. |
| 1492 | \item[{\tt [char-set]}] --- | 1536 | \item[{\tt [char-set]}] --- |
| 1493 | Represents the class which is the union of all | 1537 | Represents the class which is the union of all |
| 1494 | characters in char-set. | 1538 | characters in char-set. |
| 1495 | To include a \verb']' in char-set, it must be the first character. | 1539 | To 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; |
| 1533 | such item mathes strings that start with $x$, end with $y$, | 1577 | such item mathes strings that start with $x$, end with $y$, |
| 1534 | and where the $x$ and $y$ are {\em balanced}. | 1578 | and where the $x$ and $y$ are {\em balanced}. |
| 1535 | That means that, if one reads the string from left to write, | 1579 | That means that, if one reads the string from left to write, |
| 1536 | counting plus 1 for an $x$ and minus 1 for a $y$, | 1580 | counting 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 | |||
| 1722 | the regular pattern matching behavior, | 1766 | the regular pattern matching behavior, |
| 1723 | where a \verb'*' expands to the maximum length {\em such that\/} | 1767 | where a \verb'*' expands to the maximum length {\em such that\/} |
| 1724 | the rest of the pattern does not fail. | 1768 | the rest of the pattern does not fail. |
| 1725 | With the read pattern behavior | 1769 | With the read pattern behavior |
| 1726 | there is no need for backtracking the reading. | 1770 | there 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|, | |||
| 1913 | which is the initial value of both hooks. | 1957 | which is the initial value of both hooks. |
| 1914 | 1958 | ||
| 1915 | 1959 | ||
| 1916 | \section{Some Examples} | ||
| 1917 | |||
| 1918 | This section gives examples showing some features of Lua. | ||
| 1919 | It does not intend to cover the whole language, | ||
| 1920 | but only to illustrate some interesting uses of the system. | ||
| 1921 | |||
| 1922 | |||
| 1923 | \subsection{\Index{Data Structures}} | ||
| 1924 | Tables are a strong unifying data constructor. | ||
| 1925 | They directly implement a multitude of data types, | ||
| 1926 | like ordinary arrays, records, sets, bags, and lists. | ||
| 1927 | |||
| 1928 | Arrays need no explanations. | ||
| 1929 | In Lua, it is conventional to start indices from 1, | ||
| 1930 | but this is only a convention. | ||
| 1931 | Arrays can be indexed by 0, negative numbers, or any other value (except \nil). | ||
| 1932 | Records are also trivially implemented by the syntactic sugar | ||
| 1933 | \verb'a.x'. | ||
| 1934 | |||
| 1935 | The best way to implement a set is to store | ||
| 1936 | its elements as indices of a table. | ||
| 1937 | The statement \verb's = {}' creates an empty set \verb's'. | ||
| 1938 | The statement \verb's[x] = 1' inserts the value of \verb'x' into | ||
| 1939 | the set \verb's'. | ||
| 1940 | The expression \verb's[x]' is true if and only if | ||
| 1941 | \verb'x' belongs to \verb's'. | ||
| 1942 | Finally, the statement \verb's[x] = nil' removes \verb'x' from \verb's'. | ||
| 1943 | |||
| 1944 | Bags can be implemented similarly to sets, | ||
| 1945 | but using the value associated to an element as its counter. | ||
| 1946 | So, to insert an element, | ||
| 1947 | the following code is enough: | ||
| 1948 | \begin{verbatim} | ||
| 1949 | if s[x] then s[x] = s[x]+1 else s[x] = 1 end | ||
| 1950 | \end{verbatim} | ||
| 1951 | and to remove an element: | ||
| 1952 | \begin{verbatim} | ||
| 1953 | if s[x] then s[x] = s[x]-1 end | ||
| 1954 | if s[x] == 0 then s[x] = nil end | ||
| 1955 | \end{verbatim} | ||
| 1956 | |||
| 1957 | Lisp-like lists also have an easy implementation. | ||
| 1958 | The ``cons'' of two elements \verb'x' and \verb'y' can be | ||
| 1959 | created with the code \verb'l = {car=x, cdr=y}'. | ||
| 1960 | The expression \verb'l.car' extracts the header, | ||
| 1961 | while \verb'l.cdr' extracts the tail. | ||
| 1962 | An alternative way is to create the list directly with \verb'l={x,y}', | ||
| 1963 | and then to extract the header with \verb'l[1]' and | ||
| 1964 | the tail with \verb'l[2]'. | ||
| 1965 | |||
| 1966 | \subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext} | ||
| 1967 | \Deffunc{next}\Deffunc{nextvar} | ||
| 1968 | This example shows how to use the function \verb'next' to iterate | ||
| 1969 | over the fields of a table. | ||
| 1970 | Function \IndexVerb{clone} receives any table and returns a clone of it. | ||
| 1971 | \begin{verbatim} | ||
| 1972 | function 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 | ||
| 1980 | end | ||
| 1981 | \end{verbatim} | ||
| 1982 | |||
| 1983 | The next example prints the names of all global variables | ||
| 1984 | in the system with non nil values. | ||
| 1985 | Notice that the traversal is made with local variables, | ||
| 1986 | to avoid changing a global variable: | ||
| 1987 | \begin{verbatim} | ||
| 1988 | function printGlobalVariables () | ||
| 1989 | local i, v = nextvar(nil) | ||
| 1990 | while i do | ||
| 1991 | print(i) | ||
| 1992 | i, v = nextvar(i) | ||
| 1993 | end | ||
| 1994 | end | ||
| 1995 | \end{verbatim} | ||
| 1996 | |||
| 1997 | |||
| 1998 | \subsection{String Manipulation} \label{exstring} | ||
| 1999 | |||
| 2000 | The first example is a function to trim extra white-spaces at the beginning | ||
| 2001 | and end of a string. | ||
| 2002 | \begin{verbatim} | ||
| 2003 | function trim(s) | ||
| 2004 | local _, i = strfind(s, '^ *') | ||
| 2005 | local f, __ = strfind(s, ' *$') | ||
| 2006 | return strsub(s, i+1, f-1) | ||
| 2007 | end | ||
| 2008 | \end{verbatim} | ||
| 2009 | |||
| 2010 | The second example shows a function that eliminates all spaces | ||
| 2011 | of a string. | ||
| 2012 | \begin{verbatim} | ||
| 2013 | function remove_blanks (s) | ||
| 2014 | return gsub(s, "%s%s*", "") | ||
| 2015 | end | ||
| 2016 | \end{verbatim} | ||
| 2017 | |||
| 2018 | |||
| 2019 | \subsection{\Index{Variable number of arguments}} | ||
| 2020 | Lua does not provide any explicit mechanism to deal with | ||
| 2021 | variable number of arguments in function calls. | ||
| 2022 | However, one can use table constructors to simulate this mechanism. | ||
| 2023 | As an example, suppose a function to concatenate all its arguments. | ||
| 2024 | It could be written like | ||
| 2025 | \begin{verbatim} | ||
| 2026 | function 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 | ||
| 2034 | end | ||
| 2035 | \end{verbatim} | ||
| 2036 | To 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}} | ||
| 2042 | Because of its reflexive facilities, | ||
| 2043 | persistence in Lua can be achieved within the language. | ||
| 2044 | This section shows some ways to store and retrieve values in Lua, | ||
| 2045 | using a text file written in the language itself as the storage media. | ||
| 2046 | |||
| 2047 | To store a single value with a name, | ||
| 2048 | the following code is enough: | ||
| 2049 | \begin{verbatim} | ||
| 2050 | function store (name, value) | ||
| 2051 | write(format('\n%s =', name)) | ||
| 2052 | write_value(value) | ||
| 2053 | end | ||
| 2054 | \end{verbatim} | ||
| 2055 | \begin{verbatim} | ||
| 2056 | function 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 | ||
| 2062 | end | ||
| 2063 | \end{verbatim} | ||
| 2064 | In order to restore this value, a \verb'lua_dofile' suffices. | ||
| 2065 | |||
| 2066 | Storing tables is a little more complex. | ||
| 2067 | Assuming that the table is a tree, | ||
| 2068 | and that all indices are identifiers | ||
| 2069 | (that is, the tables are being used as records), | ||
| 2070 | then its value can be written directly with table constructors. | ||
| 2071 | First, the function \verb'write_value' is changed to | ||
| 2072 | \begin{verbatim} | ||
| 2073 | function 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 | ||
| 2080 | end | ||
| 2081 | \end{verbatim} | ||
| 2082 | The function \verb'write_record' is: | ||
| 2083 | \begin{verbatim} | ||
| 2084 | function 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 | ||
| 2093 | end | ||
| 2094 | \end{verbatim} | ||
| 2095 | |||
| 2096 | |||
| 2097 | \subsection{Inheritance} \label{exfallback} | ||
| 2098 | The fallback for absent indices can be used to implement many | ||
| 2099 | kinds of \Index{inheritance} in Lua. | ||
| 2100 | As an example, | ||
| 2101 | the following code implements single inheritance: | ||
| 2102 | \begin{verbatim} | ||
| 2103 | function 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 | ||
| 2113 | end | ||
| 2114 | |||
| 2115 | OldIndex = setfallback("index", Index) | ||
| 2116 | \end{verbatim} | ||
| 2117 | Whenever Lua attempts to access an absent field in a table, | ||
| 2118 | it calls the fallback function \verb'Index'. | ||
| 2119 | If the table has a field \verb'parent' with a table value, | ||
| 2120 | then Lua attempts to access the desired field in this parent object. | ||
| 2121 | This process is repeated ``upwards'' until a value | ||
| 2122 | for the field is found or the object has no parent. | ||
| 2123 | In the latter case, the previous fallback is called to supply a value | ||
| 2124 | for the field. | ||
| 2125 | |||
| 2126 | When better performance is needed, | ||
| 2127 | the same fallback may be implemented in C, | ||
| 2128 | as illustrated in Figure~\ref{Cinher}. | ||
| 2129 | \begin{figure} | ||
| 2130 | \Line | ||
| 2131 | \begin{verbatim} | ||
| 2132 | #include "lua.h" | ||
| 2133 | |||
| 2134 | int lockedParentName; /* lock index for the string "parent" */ | ||
| 2135 | int lockedOldIndex; /* previous fallback function */ | ||
| 2136 | |||
| 2137 | void 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 | |||
| 2147 | void 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} | ||
| 2173 | This 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} | ||
| 2180 | Notice how the string \verb'"parent"' is kept | ||
| 2181 | locked in Lua for optimal performance. | ||
| 2182 | |||
| 2183 | \subsection{\Index{Programming with Classes}} | ||
| 2184 | There are many different ways to do object-oriented programming in Lua. | ||
| 2185 | This section presents one possible way to | ||
| 2186 | implement classes, | ||
| 2187 | using the inheritance mechanism presented above. | ||
| 2188 | {\em Please note: the following examples only work | ||
| 2189 | with the index fallback redefined according to | ||
| 2190 | Section~\ref{exfallback}}. | ||
| 2191 | |||
| 2192 | As one could expect, a good way to represent a class is | ||
| 2193 | with a table. | ||
| 2194 | This table will contain all instance methods of the class, | ||
| 2195 | plus optional default values for instance variables. | ||
| 2196 | An instance of a class has its \verb'parent' field pointing to | ||
| 2197 | the class, | ||
| 2198 | and so it ``inherits'' all methods. | ||
| 2199 | |||
| 2200 | For instance, a class \verb'Point' can be described as in | ||
| 2201 | Figure~\ref{Point}. | ||
| 2202 | Function \verb'create' helps the creation of new points, | ||
| 2203 | adding the parent field. | ||
| 2204 | Function \verb'move' is an example of an instance method. | ||
| 2205 | \begin{figure} | ||
| 2206 | \Line | ||
| 2207 | \begin{verbatim} | ||
| 2208 | Point = {x = 0, y = 0} | ||
| 2209 | |||
| 2210 | function Point:create (o) | ||
| 2211 | o.parent = self | ||
| 2212 | return o | ||
| 2213 | end | ||
| 2214 | |||
| 2215 | function Point:move (p) | ||
| 2216 | self.x = self.x + p.x | ||
| 2217 | self.y = self.y + p.y | ||
| 2218 | end | ||
| 2219 | |||
| 2220 | ... | ||
| 2221 | |||
| 2222 | -- | ||
| 2223 | -- creating points | ||
| 2224 | -- | ||
| 2225 | p1 = Point:create{x = 10, y = 20} | ||
| 2226 | p2 = Point:create{x = 10} -- y will be inherited until it is set | ||
| 2227 | |||
| 2228 | -- | ||
| 2229 | -- example of a method invocation | ||
| 2230 | -- | ||
| 2231 | p1:move(p2) | ||
| 2232 | \end{verbatim} | ||
| 2233 | \caption{A Class {\tt Point}.\label{Point}} | ||
| 2234 | \Line | ||
| 2235 | \end{figure} | ||
| 2236 | Finally, a subclass can be created as a new table, | ||
| 2237 | with the \verb'parent' field pointing to its superclass. | ||
| 2238 | It is interesting to notice how the use of \verb'self' in | ||
| 2239 | method \verb'create' allows this method to work properly even | ||
| 2240 | when inherited by a subclass. | ||
| 2241 | As usual, a subclass may overwrite any inherited method with | ||
| 2242 | its own version. | ||
| 2243 | |||
| 2244 | \subsection{\Index{Modules}} | ||
| 2245 | Here we explain one possible way to simulate modules in Lua. | ||
| 2246 | The main idea is to use a table to store the module functions. | ||
| 2247 | |||
| 2248 | A module should be written as a separate chunk, starting with: | ||
| 2249 | \begin{verbatim} | ||
| 2250 | if modulename then return end -- avoid loading twice the same module | ||
| 2251 | modulename = {} -- create a table to represent the module | ||
| 2252 | \end{verbatim} | ||
| 2253 | After that, functions can be directly defined with the syntax | ||
| 2254 | \begin{verbatim} | ||
| 2255 | function modulename.foo (...) | ||
| 2256 | ... | ||
| 2257 | end | ||
| 2258 | \end{verbatim} | ||
| 2259 | |||
| 2260 | Any code that needs this module has only to execute | ||
| 2261 | \verb'dofile("filename")', where \verb'filename' is the file | ||
| 2262 | where the module is written. | ||
| 2263 | After this, any function can be called with | ||
| 2264 | \begin{verbatim} | ||
| 2265 | modulename.foo(...) | ||
| 2266 | \end{verbatim} | ||
| 2267 | |||
| 2268 | If a module function is going to be used many times, | ||
| 2269 | the program can give a local name to it. | ||
| 2270 | Because functions are values, it is enough to write | ||
| 2271 | \begin{verbatim} | ||
| 2272 | localname = modulename.foo | ||
| 2273 | \end{verbatim} | ||
| 2274 | Finally, a module may be {\em opened}, | ||
| 2275 | giving direct access to all its functions, | ||
| 2276 | as shown in the code in Figure~\ref{openmod}. | ||
| 2277 | \begin{figure} | ||
| 2278 | \Line | ||
| 2279 | \begin{verbatim} | ||
| 2280 | function 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 | ||
| 2286 | end | ||
| 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} | ||
| 2293 | A CFunction to compute the maximum of a variable number of arguments | ||
| 2294 | is shown in Figure~\ref{Cmax}. | ||
| 2295 | \begin{figure} | ||
| 2296 | \Line | ||
| 2297 | \begin{verbatim} | ||
| 2298 | void 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} | ||
| 2325 | After registered with | ||
| 2326 | \begin{verbatim} | ||
| 2327 | lua_register ("max", math_max); | ||
| 2328 | \end{verbatim} | ||
| 2329 | this function is available in Lua, as follows: | ||
| 2330 | \begin{verbatim} | ||
| 2331 | i = max(4, 5, 10, -34) -- i receives 10 | ||
| 2332 | \end{verbatim} | ||
| 2333 | |||
| 2334 | |||
| 2335 | \subsection{Calling Lua Functions} \label{exLuacall} | ||
| 2336 | |||
| 2337 | This example illustrates how a C function can call the Lua function | ||
| 2338 | \verb'remove_blanks' presented in Section~\ref{exstring}. | ||
| 2339 | \begin{verbatim} | ||
| 2340 | void 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, | |||
| 2484 | since it could lead to strange behavior. | 2096 | since it could lead to strange behavior. |
| 2485 | In particular, | 2097 | In particular, |
| 2486 | to access results returned from a Lua function, | 2098 | to access results returned from a Lua function, |
| 2487 | the new macro \verb'lua_getresult' should be used. | 2099 | the new macro \verb|lua_getresult| should be used. |
| 2488 | \item | 2100 | \item |
| 2489 | The old functions \verb'lua_storefield' and \verb'lua_storeindexed' | 2101 | The old functions \verb'lua_storefield' and \verb'lua_storeindexed' |
| 2490 | have been replaced by | 2102 | have been replaced by |
