Lua2.4 Reference Manual (6)

Source: Internet
Author: User
Tags strfind

(Part 1)
--------------------------------------
8. Examples
--------------------------------------
This section provides examples of displaying the Lua feature. It does not intend to cover the complete language, but shows an interesting use.

-------------------
8.1 Data Structure
-------------------
A table is a unified data structure. It can implement multiple data types, such as common arrays, records, sets, packages, and lists.
No need to explain the array. In Lua, the index usually starts from 1, but this is just a convention. The array can be indexed with 0, negative, or any other value (except nil. The record is also implemented using the syntax sugar A. X as usual.
The best way to implement a set is to save its elements as table indexes. Statement S = {} creates an empty set S. Statement S [x] = 1 inserts the value of X into the set S. Expression s [x] is true if X belongs to S. Finally, Statement S [x] = nil deletes X from S.
The implementation method of the package is similar to that of the set, but the value related to the element is used as the counter. Therefore, to insert an element, you can use the following code:
If s [x] Then s [x] = s [x] + 1
Else s [x] = 1 end
You can use the following code to delete an element:
If s [x] Then s [x] = s [x]-1 end
If s [x] = 0 then s [x] = nil end
The list of Lisp styles also has a simple implementation. The "cons" of the two elements x and y can be created by code L = {car = x, cdr = y. Expression L. Car gets the header, and L. CDR gets the end. Another method is to directly create a list using L = {x, y}, then use L [1] to get the header, and use L [2] to get the end.

-------------------
8.2 functions: Next and nextvar
-------------------
This example shows how to use the next function to traverse a table field. Function clone accepts a table and returns a clone of it.
Function clone (t) -- T is a table
Local new_t ={} -- create a new table
Local I, V = next (T, nil) -- I is an index of T, V = T [I]
While I do
New_t [I] = V
I, V = next (t, I) -- get next Index
End
Return new_t
End
In this example, the names of all non-null global variables are printed.
Function printglobalvariables ()
Local I, V = nextvar (nil)
While I do
Print (I)
I, V = nextvar (I)
End
End
-------------------
8.3 string operations
-------------------
In this example, the leading and trailing spaces of the string are removed:
Function trim (s)
Local L = 1
While strsub (S, l, l) = ''do
L = L + 1
End
Local r = strlen (s)
While strsub (S, R, R) = ''do
R = R-1
End
Return strsub (S, L, R)
End
In this example, all the white spaces of the string are removed:
Function remove_blanks (s)
Local B = strfind (S ,'')
While B do
S = strsub (s, 1, B-1) .. strsub (S, B + 1)
B = strfind (S ,'')
End
Return s
End

-------------------
8.4 variable number Parameters
-------------------
Lua does not provide a significant mechanism to implement variable number parameters. However, you can use the table structure to simulate this mechanism. The following example assumes that the function wants to connect all its parameters. You can use the following code:
Function Concat (o)
Local I = 1
Local S =''
While o [I] Do
S = S.. O [I]
I = I + 1
End
Return s
End
To call it, you can use a table structure to connect all parameters:
X = Concat {"hello", "John", "and", "Mary "}

-------------------
8.5 persistence
-------------------
Because of Lua's self-resistance, the persistence can be implemented in Lua. This section describes how to store and restore values in Lua, and uses text files written in Lua as the storage media.
Save a key-Value Pair and use the following code:
Function store (name, value)
Write (format ('\ n % s =', name ))
Write_value (value)
End
Function write_value (value)
Local T = type (value)
If t = 'nil 'then write ('nil ')
Elseif T = 'number' then write (value)
Elseif T = 'string' then write (value, 'q ')
End
End
To restore these values, a lua_dofile is enough.
It is a bit complicated to store tables. Assume that the table is a tree, and all subscripts are Identifiers (that is, the table is used as a record). The table values can be written using the table constructor.
First, change the write_value function
Function write_value (value)
Local T = type (value)
If t = 'nil 'then write ('nil ')
Elseif T = 'number' then write (value)
Elseif T = 'string' then write (value, 'q ')
Elseif T = 'table' then write_record (value)
End
End
The write_record function is:
Function write_record (t)
Local I, V = next (T, nil)
Write ('{') -- starts Constructor
While I do
Store (I, V)
Write (',')
I, V = next (t, I)
End
Write ('}') -- closes Constructor
End
-------------------
8.6 inheritance
-------------------
Rollback without indexes can be used to implement multiple inheritance in Lua. For example, the following code implements a single inheritance:
Function Index (T, F)
If f = 'parent' then -- to avoid Loop
Return oldindex (T, F)
End
Local p = T. Parent
If type (p) = 'table' then
Return P [F]
Else
Return oldindex (T, F)
End
End

Oldindex = setfallback ("Index", index)
When Lua tries to obtain a field that does not exist in the table, it calls the return function index. If the table has a parent field that contains the table value, Lua tries to obtain the expected field from its parent object. This process repeats "Up" until a value is found for that field or the object does not have a parent. In later cases, the previous rollback will be called to provide a value for the corresponding field.
When a better performance is required, the same rollback can be implemented in C, as shown in the following code.
# Include "Lua. H"
Int lockedparentname;/* Lock index for the string "parent "*/
Int lockedoldindex;/* Previous fallback function */
Void calloldfallback (lua_object table, lua_object index)
{
Lua_object oldindex = lua_getref (lockedoldindex );
Lua_pushobject (table );
Lua_pushobject (INDEX );
Lua_callfunction (oldindex );
}
Void index (void)
{
Lua_object table = lua_getparam (1 );
Lua_object Index = lua_getparam (2 );
Lua_object parent;
If (lua_isstring (INDEX) & strcmp (lua_getstring (INDEX), "parent") = 0)
{
Calloldfallback (table, index );
Return;
}
Lua_pushobject (table );
Lua_pushref (lockedparentname );
Parent = lua_getsubscript ();
If (lua_istable (parent ))
{
Lua_pushobject (parent );
Lua_pushobject (INDEX );
/* Return result from getsubscript */
Lua_pushobject (lua_getsubscript ());
}
Else
Calloldfallback (table, index );
}

This code must be registered as follows:
Lua_pushstring ("parent ");
Lockedparentname = lua_ref (1 );
Lua_pushobject (lua_setfallback ("Index", index ));
Lockedoldindex = lua_ref (1 );
Note how to lock the "parent" string to improve performance.

-------------------
8.7 use class Programming
-------------------
There are multiple methods for Object-Oriented Programming in Lua. This shows a method that may implement classes, using the Inheritance Mechanism mentioned above. Note: The following example can only work after index rollback is defined according to 8.6.
As you expected, a good way to represent classes is to use tables. This table will contain all instance methods of the class, and may also implement the default values of variables. An example of a class is to point its parent field to that class, so it "inherits" all methods.
Point = {x = 0, y = 0}
Function Point: Create (o)
O. Parent = self
Return o
End
Function Point: Move (P)
Self. x = self. x + p. x
Self. Y = self. Y + P. Y
End
...
--
-- Creating points
--
P1 = point: Create {x = 10, y = 20}
P2 = point: Create {x = 10} -- y will be inherited until it is set
--
-- Example of a Method Invocation
--
P1: Move (P2)

For example, a point class can be as shown above. The create function is used to create a new point and add its parent field. The move function is an example of an instance method. Finally, a word class can be created as a new table, and its parent field points to its parent class. Note that the interesting thing is how self uses the create method to allow this method to work normally, even if it is inherited by a subclass. As usual, a word class can use its own method to override all its inherited methods.

-------------------
Module 8.8
-------------------
Here we will explain a method that can simulate modules in Lua. The main idea is to use a table to save the simulated functions.
A module should be written as a separate chunk starting from:
If modulename then return end -- avoid loading twice the same module
Modulename = {} -- create a table to represent the module
Then, the function can be defined directly by the following syntax:
Function modulename. Foo (...)
...
End
All code that requires these modules only needs to execute dofile ("FILENAME"). filename is the file defined by the module. Then, any function can be called as follows:
Modulename. Foo (...)
If a module method will be used many times, the program can give it a local name.
Because the function is a value, you can write it like this:
Localname = modulename. foo
Finally, a module can be opened to grant direct access permissions to all its functions, as shown in the following code:
Function open (MOD)
Local N, F = next (mod, nil)
While n do
Setglobal (n, F)
N, F = next (mod, n)
End
End

-------------------
8.9 A cfunction
-------------------
A cfunction can be used to calculate the maximum number of numeric parameters:
Void math_max (void)
{
Int I = 1;/* number of arguments */
Double D, dmax;
Lua_object O;
/* The function must get at least one argument */
If (O = lua_getparam (I ++) = lua_noobject)
Lua_error ("too few arguments to function 'max '");
/* And this argument must be a number */
If (! Lua_isnumber (o ))
Lua_error ("Incorrect argument to function 'max '");
Dmax = lua_getnumber (O );
/* Loops until there is no more arguments */
While (O = lua_getparam (I ++ ))! = Lua_noobject)
{
If (! Lua_isnumber (o ))
Lua_error ("Incorrect argument to function 'max '");
D = lua_getnumber (O );
If (D> dmax) dmax = D;
}
/* Push the result to be returned */
Lua_pushnumber (Dmax );
}
Use the following function registration:
Lua_register ("Max", math_max );
This function can be called by Lua as follows:
I = max (4, 5, 10,-34) -- I need ES 10

-------------------
8.5 call the Lua Function
-------------------
This example shows how a C function calls the Lua function remove_blanks shown in section 8.3.
Void remove_blanks (char * s)
{
Lua_pushstring (s);/* prepare parameter */
Lua_call ("remove_blanks");/* Call Lua function */
Strcpy (S, lua_getstring (lua_getresult (1);/* Copy result back to's '*/
}
--------------------------------------
Thanks
--------------------------------------
I would like to thank cenpes/petrobrobas and tecgraf for using the early versions of the system together and providing valuable comments. I would also like to thank Carlos Henrique levy for setting a name for this language. Lua means the moon in Portuguese.
--------------------------------------
Others (omitted)
--------------------------------------
Incompatible with earlier versions and indexes.

Lua2.4 Reference Manual (6)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.