[Script]-learn Lua through examples

Source: Internet
Author: User

Source: http://www.cppblog.com/Leaf/archive/2009/05/16/83145.html

 

It is said that the author of this article is ogdev's hack master.

Use examples to learn about Lua (1) ---- Hello World

1. Preface
The scripting language is indispensable in the game. Lua is a very closely-integrated scripting language with C/C ++, with extremely high efficiency.
Generally, C ++ is used to write the time requirements, while Lua is often used to write the changes.

I have recently learned about Lua, so I will share my experiences with you. Lua is a completely free scripting language,
Its official website is onHttp://www.lua.org. You can download the Lua source code from the website.
Run the version, but don't worry, because the Lua source code can be compiled on any C/C ++ compiler.

If you want to learn about Lua, the reference on the official website is essential and has the usage of each command on it, which is very detailed.
Fine.
Reference manualHttp://www.lua.org/manual/5.0/
Programming in Lua written by the authorHttp://www.lua.org/pil/

2. Compile
If you use the VC, you can download the required project file
Http://sourceforge.net/project/showfiles.php? Group_id = 32250 & package_id = 115604
Cygwin and Linux are used. Just run the following command,
Tar-zxvf lua-5.0.2.tar.gz
CD lua-5.0.2
Sh./configure
Make
In this case, OK.
For future convenience, it is best to add the bin directory to the path.

3. "Hello, world! "
Now let's start with our first smallProgram"Hello, world! "
Put the following program into the file e01.lua

Example 1: e01.lua
-- Hello world in Lua
Print ("Hello world .")

Lua can be embedded into a C program for execution, or directly executed from the command line.
Line.
To facilitate debugging, run the command Lua e01.lua In the second way.

The output result should be:
Hello world.

4. program description
The first line -- Hello world in Lua
This sentence is a comment, where -- and the // in C ++ mean the same
Print ("Hello world .")
Call the Lua Internal Command print to output the "Hello world." string to the screen. All strings in Lua are
Enclosed.
This command is a function call. Print is a Lua function, while "Hello world." is a print parameter.
Number.

5. Try it.
There are a lot of string processing operations in Lua. After this lesson, try to find the link between the two strings.
,
And print it out.
--

Use examples to learn about Lua (2) --- Lua Basics

1. Use of functions
The following program demonstrates how to use functions and local variables in Lua.
Example e02.lua
-- Functions
Function Pythagorean (A, B)
Local C2 = a ^ 2 + B ^ 2
Return SQRT (C2)
End
Print (Pythagorean (3, 4 ))

Running result
5

Program description
In Lua, The Function Definition Format is:
Function Name (parameter)
...
End
Unlike Pascal, end does not need to be paired with begin. You only need to end the function.
In this example, the function is used to obtain the diagonal side of a right triangle and obtain the length of the oblique side. parameters a and B indicate the length of the right side, respectively,
The local variable is defined in the function to store the square of the oblique edge. It is the same as the C language and defined in the function.
The code will not be executed directly, and will be executed only when the main program is called.
Local indicates defining a local variable. If the local variable is not added, C2 is a global variable, and the local scope
Is between the end of the innermost layer and the matched keywords, such as if... end, while... end. Global Variables
Of
The scope is the whole program.

2. Loop statements
Example e03.lua
-- Loops
For I = 1, 5 do
Print ("I is now" .. I)
End

Running result
I is now 1
I is now 2
I is now 3
I is now 4
I is now 5

Program description
Here we use the for statement.
For variable = parameter 1, parameter 2, parameter 3 do
Loop body
End
The variable takes parameter 3 as the step, and changes from parameter 1 to parameter 2.
For example:
For I = 1, F (x) Do print (I) End
For I = 10, 1,-1 do print (I) End

In Print ("I is now" .. I), we use..., which is used to connect two strings,
Even if I try to see what I mentioned in (1), I don't know if you have answered correctly.
Although I is an integer here, Lua will automatically convert it into a string type during processing, without worrying about it.

3. condition branch statement
example e04.lua
-- loops and conditionals
for I = DO
Print ("I is now" .. i)
If I <2 then
Print ("small")
elseif I <4 then
Print ("medium ")
else
Print ("big")
end

Running result
I is now 1
Small
I is now 2
Medium
I is now 3
Medium
I is now 4
Big
I is now 5
Big

Program description
If else is easy to use, similar to the C language, but note that the entire if only needs an end,
Even if multiple elseif are used, it is also an end.
For example
If op = "+" then
R = a + B
Elseif op = "-" then
R = A-B
Elseif op = "*" then
R = a * B
Elseif op = "/" then
R = A/B
Else
Error ("invalid operation ")
End

4. Try again
In addition to the for loop, Lua also supports multiple loops. Use while... do and repeat... Until to rewrite this article.
For program

--
Learning Lua (3) through examples ---- Data Structure

1. Introduction
Lua has only one basic data structure, that is, table. All other data structures, such as arrays,
Can be implemented by table.

2. Table subscript
Example e05.lua
-- Arrays
Mydata = {}
Mydata [0] = "Foo"
Mydata [1] = 42

-- Hash tables
Mydata ["BAR"] = "BAZ"

-- Iterate through
-- Structure
For key, value in mydata do
Print (key .. "=" .. value)
End

Output result
0 = foo
1 = 42
Bar = Baz

Program description
First define a table mydata = {}, and then use a number as the subscript to assign two values to it.
The definition method is similar to the array in C, but unlike the array, each array element does not need to be of the same type,
In this example, one is an integer and the other is a string.

The second part of the program uses the string as the subscript and adds an element to the table.
The map. Table subscript in STL can be any basic type supported by Lua, except for the nil value.

Lua automatically processes table memory usage, as shown in the following section.Code
A = {}
A ["X"] = 10
B = A -- 'B' refers to the same table as 'A'
Print (B ["X"]) --> 10
B ["X"] = 20
Print (A ["X"]) --> 20
A = Nil -- now only 'B' still refers to the table
B = Nil -- now there are no references left to the table
Both B and a point to the same table and only occupy one piece of memory. When a = NIL is executed, B still points to table,
When B = NIL is executed, Lua Automatically releases the memory occupied by the table because it does not point to the table variable.

3. Table nesting
Table can also be nested, as shown in the following example.
Example e06.lua
-- Table 'constructor'
Mypolygon = {
Color = "blue ",
Thickness = 2,
Npoints = 4;
{X = 0, y = 0 },
{X =-10, y = 0 },
{X =-5, y = 4 },
{X = 0, y = 4}
}

-- Print the color
Print (mypolygon ["color"])

-- Print it again using dot
-- Notation
Print (mypolygon. color)

-- The points are accessible
-- In mypolygon [1] to mypolygon [4]

-- Print the second point's x
-- Coordinate
Print (mypolygon [2]. X)

Program description
First, create a table. Different from the previous example, In the constructor of the table, there are {x = 0, y = 0 },
What does this mean? This is actually a small table, defined in the big table, the small table
The table name is omitted.
The last line of mypolygon [2]. X is the access method for small tables in large tables.

--
Use examples to learn about Lua (4) -- function call

1. Indefinite Parameters
Example e07.lua
-- Functions can take
-- Variable number
-- Arguments.
Function funky_print (...)
For I = 1, Arg. n do
Print ("Funky:" .. Arg)
End
End

Funky_print ("one", "two ")

Running result
Funky: One
Funky: Two

Program description
* If the parameter "..." is used, the number of parameters is not fixed.
* Parameters are automatically stored in an ARG table.
* The number of parameters in Arg. N. Arg [] can be traversed by adding a subscript.

2. Use table as the parameter
Example e08.lua
-- Functions with table
-- Parameters
Function print_contents (t)
For K, V in t do
Print (K .. "=" .. V)
End
End
Print_contents {x = 10, y = 20}

Running result
X = 10
Y = 20

Program description
* Print_contents {x = 10, y = 20} is not enclosed in parentheses because when a single table is used as a parameter,
Parentheses are not required
* For K, V in t do: This statement traverses all values in the table, stores names in K, and stores values in v.

3. Convert Lua into a data description language similar to XML.
Example e09.lua
Function contact (t)
-- Add the contact 'T', which is
-- Stored as a table, to a database
End

Contact {
Name = "game developer ",
Email = "hack@ogdev.net ",
Url = "http://www.ogdev.net,
Quote = [[
There are
10 types of people
Who can understand binary.]
}

Contact {
-- Some other contact
}

Program description
* The combination of function and table makes Lua a Data Description Language similar to XML.
* Contact {...} In e09 is a function call method. Do not confuse it.
* [[...] Indicates a multi-line string.
* When Using c api, this method has more obvious advantages. The contact {...} section can be saved as a configuration file.
Parts

4. Try again
Think about where the configuration method mentioned in e09 can be used?

--

Use examples to learn about the interaction between Lua (5) and Lua and C

 

1. Introduction

Lua is closely integrated with C/C ++. The interaction between Lua and C ++ is based on Lua and C.
Let's start with Lua and C.

As mentioned in the first lecture, there are two main methods to run the Lua program or call Lua:
* Run the "Lua" command through the command line
* Use the Lua C library
Although we have been using the first method before, I want to tell you that executing through Lua's C library is in the game.
Common methods.

2. Lua's C library

The C library of Lua can be called as the shared library, but generally all the source programs of Lua are called during game development.
It does not compile Lua into a shared library because the Lua program only has more than 100 k, and almost
You can clean compile in any compiler. When there is another benefit of the Lua source program, you can always
Expand itself to add the functions required by our colleagues.

Lua's C Library provides a series of Apis:
* Manage global variables
* Manage tables
* Call a function
* Define a new function, which can be fully implemented by C.
* The Garbage Collector garbage collector can be automatically executed by Lua, but it is often not executed immediately,
Therefore, programs with high real-time requirements will call the Garbage Collector by themselves.
* Load and execute the Lua program, which can also be implemented by Lua itself
* Any functions that Lua can implement can be implemented through Lua's c API, which improves the program running speed.
It is helpful. Shared Lua program fragments that are often called can be converted into C programs to improve efficiency. Even Lua is written in C.
What other types of C cannot be implemented?

3. Example of integration of Lua and C
Example e10.c
/* A simple Lua interpreter .*/
# Include <stdio. h>
# Include <Lua. h>
Int main (INT argc, char * argv []) {
Char line [bufsiz];
Lua_state * l = lua_open (0 );
While (fgets (line, sizeof (line), stdin )! = 0)
Lua_dostring (L, line );
Lua_close (L );
Return 0;
}

Compile
Linux/cygwin
* Compile Lua first and put the header file into the include path.
* GCC e10.c-llua-llualib-O E10

Vc6/vc2003
* Compile Lua first and set the header file and library file path in option.
* Create a project and add the additional libraries Lua. lib and lualib. lib to the project configuration.
* Compile to exe

Running result
The function of this program is to implement a Lua interpreter. Each line of input characters will be interpreted as Lua and executed.

Program description
* # Include <Lua. h> contains the Lua header file before you can use the API
* Lua_state * l = lua_open (0) open a Lua Actuator
* Fgets (line, sizeof (line), stdin) reads a row from the standard input
* Lua_dostring (L, line) executes this line.
* Lua_close (l) disables the Lua Actuator

Example e11.c
/* Another simple Lua interpreter .*/
# Include <stdio. h>
# Include <Lua. h>
# Include <lualib. h>
Int main (INT argc, char * argv []) {
Char line [bufsiz];
Lua_state * l = lua_open (0 );
Lua_baselibopen (L );
Lua_iolibopen (L );
Lua_strlibopen (L );
Lua_mathlibopen (L );
While (fgets (line, sizeof (line), stdin )! = 0)
Lua_dostring (L, line );
Lua_close (L );
Return 0;
}

Running result
The function of this program is to implement a Lua interpreter. Each line of input characters will be interpreted as Lua and executed.
Different from the previous example, this example calls some standard libraries of Lua.

Program description
* # Include <lualib. h> standard library containing Lua
* The following lines are used to read some Lua libraries, so that our Lua program can have more functions.
Lua_baselibopen (L );
Lua_iolibopen (L );
Lua_strlibopen (L );
Lua_mathlibopen (L );

4. Try again
Compile and execute the above two small examples in the compiler that you are familiar with, and try to compile with the Lua source code tree.

--
Use examples to learn how to use the Lua function in Lua (6) ---- C/C ++

Reference English document http://tonyandpaige.com/tutorials/lua2.html

1. Introduction
Let's talk about how to define a function by Lua and then call it in C or C ++.
Currently, the C ++ object is not involved. We only discuss the use of function parameters, return values, and global variables.

2.
Here, we first define a simple add (), X, and y in e12.lua as two parameters for addition,
Return directly returns the result after addition.

Example: e12.lua
-- Add two numbers
Function add (x, y)
Return x + y
End

In the previous time, we mentioned that lua_dofile () can directly execute the Lua file in C.
Only one add () function is defined in this program, so the result is not directly returned after the program is executed.
It is the same as defining a function in C.

Lua functions can have multiple parameters or return values, which are implemented by stacks.
When a function needs to be called, the function is pushed to the stack, and all parameters are pushed to the stack in sequence.
Lua_call () calls this function. After the function returns, the return value is stored in the stack. This process and
The process of calling the Assembly execution function is the same.

For example, e13.cpp is an example of calling the above Lua function.
# Include <stdio. h>

Extern "C" {// This is a C ++ program, so extern "C ",
// Because the Lua header files are in the C format
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}

/* The Lua interpreter */
Lua_state * l;

Int luaadd (int x, int y)
{
Int sum;

/* The function name */
Lua_getglobal (L, "add ");

/* The first argument */
Lua_pushnumber (L, X );

/* The second argument */
Lua_pushnumber (L, y );

/* Call the function with 2
Arguments, return 1 result */
Lua_call (l, 2, 1 );

/* Get the result */
Sum = (INT) lua_tonumber (L,-1 );
Lua_pop (L, 1 );

Return sum;
}

Int main (INT argc, char * argv [])
{
Int sum;

/* Initialize Lua */
L = lua_open ();

/* Load Lua base libraries */
Lua_baselibopen (L );

/* Load the script */
Lua_dofile (L, "e12.lua ");

/* Call the Add function */
Sum = luaadd (10, 15 );

/* Print the result */
Printf ("the sum is % d \ n", sum );

/* Cleanup Lua */
Lua_close (L );

Return 0;
}

Program description:
The process in main has been said last time, so this time we will only talk about the process of luaadd.
* Use lua_getglobal () to apply the Add function to the stack.
* Use lua_pushnumber () to sequentially press the X and Y stacks.
* Then call lua_call () and tell the program that two parameters return a value.
* Then we retrieve the returned value from the top of the stack and use lua_tonumber ()
* Finally, we use lua_pop () to clear the returned values.

Running result:
The sum is 25

Compilation Method
Save the program as e13.cpp in Linux
G ++ e13.cpp-llua-llualib-O E13
./E13

Compile method in VC
* First, create an empty Win32 console application project.
* Add e13.cpp to the Project
* Click "project setting", set the link option, and add two additional libraries: Lua. Lib lualib. Lib.
* Final compilation

You can download the created project here.
VC http://tonyandpaige.com/tutorials/luaadd.zip
Linux http://tonyandpaige.com/tutorials/luaadd.tar.gz

3. Global Variables
We used lua_getglobal () but didn't elaborate on it. Here we will give two more small examples to illustrate the global
Variable
Lua_getglobal () is used to push the value of global variables in Lua to the stack.
Lua_getglobal (L, "Z ");
Z = (INT) lua_tonumber (L, 1 );
Lua_pop (L, 1 );
Assume that the Lua program defines a global variable z, which is to extract the value of Z and put it into the variable Z of C.

In addition, Lua has a corresponding function lua_setglobal (), which is used to fill in the specified global variables with the value at the top of the stack.
Quantity
Lua_pushnumber (L, 10 );
Lua_setglobal (L, "Z ");
For example, this small program sets the global variable Z in Lua to 10. If Z is not defined in Lua
Create one
Set global variable Z to 10.

4. Try again
Write a function and use C/C ++ to call it.

--
Use examples to learn how to call the C/C ++ function in Lua (7) ---- Lua

1. Preface
The last time I talked about calling the Lua function from C/C ++, some friends asked me how to call the C/C ++ function from Lua.
Function, so we will discuss this issue this time. First, we will create a function in C ++, and then
Tell Lua to have this function and then execute it. In addition, because the function is not defined in Lua
The correctness of the function cannot be determined, and errors may occur during the call process, so we will also talk about the Lua error.
Problems.

2. Call the C function in Lua
In Lua, a function is called as a function pointer, and all function pointers must meet the following requirements:
Type:
Typedef int (* lua_cfunction) (lua_state * l );

That is to say, when defining a function in C ++, we must take lua_state as the parameter and use int as the return value.
It is called by Lua, but don't forget that our lua_state supports stacks, so we can
Infinite parameters are passed, and the size is limited by the memory size. The returned int value only refers to the number of returned values.
The real return values are stored in the lua_state stack. Even the common practice is to make a wrapper
All the functions that need to be called are wrap, so that any function can be called.

The following example shows a C ++ average () function. It shows how to use multiple parameters and return multiple values.

Example: e14.cpp
# Include <stdio. h>

Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}

/* The Lua interpreter */
Lua_state * l;

Static int average (lua_state * l)
{
/* Get number of arguments */
Int n = lua_gettop (L );
Double sum = 0;
Int I;

/* Loop through each argument */
For (I = 1; I <= N; I ++)
{
/* Total the arguments */
Sum + = lua_tonumber (L, I );
}

/* Push the average */
Lua_pushnumber (L, sum/N );

/* Push the sum */
Lua_pushnumber (L, sum );

/* Return the number of results */
Return 2;
}

Int main (INT argc, char * argv [])
{
/* Initialize Lua */
L = lua_open ();

/* Load Lua base libraries */
Lua_baselibopen (L );

/* Register our function */
Lua_register (L, "average", average );

/* Run the script */
Lua_dofile (L, "e15.lua ");

/* Cleanup Lua */
Lua_close (L );

Return 0;
}

Example: e15.lua
-- Call a C ++ Function

AVG, sum = average (10, 20, 30, 40, 50)

Print ("the average is", avg)
Print ("the sum is", sum)

Program description:
* Lua_gettop () is used to return the serial number of the element at the top of the stack. Because the stack of Lua is numbered from 1,
Therefore, the number of elements at the top of the stack is equivalent to the number of elements in the stack. Here, the number of elements in the stack is
Is the number of input parameters.
* The for loop calculates the sum of all input parameters. Here the value conversion lua_tonumber () is used ().
* Then we use lua_pushnumber () to push the average value and sum to the stack.
* Finally, we return 2, which indicates two return values.
* Even though we have defined the average () function in C ++, our Lua program does not know it, so we need
To add

/* Register our function */
Lua_register (L, "average", average );

The role of these two rows is to tell e15.lua that there is a function like average.
* This program can be saved as CPP or C. If the extension is. C, you do not need to add extern "C"

The compilation method is the same as we mentioned last time.
The execution method of e15.lua can only be executed in C ++ in the preceding example, but cannot be executed using the command line method.

3. handle errors
In the preceding example, we did not check whether the input parameter is a number.
Add the error handling fragments.

Add this section to the For Loop:
If (! Lua_isnumber (L, I )){
Lua_pushstring (L, "Incorrect argument to 'average '");
Lua_error (L );
}
This section is used to check whether the input is a number.

After this section is added, even debugging will be much simpler. for programming in combination with the two languages
It is very important to check the correctness of Inter-transmission data.

Here are examples written by others:
Http://tonyandpaige.com/tutorials/luaavg.zip of VC
Http://tonyandpaige.com/tutorials/luaavg.tar.gz for Linux

At this point, the combination of Lua and C is basically over. Next time, let's talk about Lua and object-oriented.
But I haven't finished learning it yet, so you may have to wait for two more days. Sorry!

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.