Programming in Lua (basic)

Source: Internet
Author: User

2012-04-02 wcdj

$ LUA-V

Lua 5.2.0 copyright (c) 1994-2011 lua.org, pUC-Rio

Directory

0 What is Lua ?... 1

1 Lua brief introduction... 1

2 basic syntax... 3

3 functions... 4

4 practice code... 6

5 Reference:... 14

 

0 What is Lua?

Lua is based on simplicity and elegance and focuses on the tasks that C is not good;

Lua itself is fully written in accordance with ansi c. Lua can exert its power wherever there is a C compiler;

Lua can be used to adapt to changes more easily for those application directions that have changed a lot in the product lifecycle;

Lua has a high execution efficiency. Statistics show that Lua is currently the script language with the highest average efficiency;

Lua users are classified into three types: those that embed Lua into other applications, use Lua independently, and use Lua and C together;

1 Lua Introduction

N. Like other scripts, Lua can be executed in two ways.

(1) Interactive command line. That is, run without parameters. Use the file terminator to exit Ctrl-D in UNIX, Ctrl-Z in DOS/windows, or call OS. Exit () to exit.

(2) Call the script for execution (with the script file parameters ).

(3) During command line interaction, you can use the dofile function to call external script files to load the required library.

N Lua is a dynamic type language, and variables do not need to be defined by type.

Global variables do not need to be declared. After a variable is assigned a value, the global variable is created. Accessing a non-initialized global variable will not cause errors, but the result is nil. This variable exists only when it is not equal to nil.

Lua has eight basic types:

Nil, Boolean, number, String, userdata, function, thread, table

Note:

(1) function type can test the type of a given variable or value.

(2) variables do not have predefined types. Each variable may contain any type of value.

(3) functions can be used like other values (assign a function to a variable ).

(4) Nil is a special type in Lua. Before a global variable is assigned a value, the default value is nil. If a global variable is assigned a value of nil, this variable can be deleted.

(5) Boolean has two values: false and true. All values in Lua can be used as conditions. In the conditions of the control structure, except false and nil are false, all other values are true. Therefore, Lua considers 0 and null strings as true.

(6) number indicates the real number, and Lua does not contain an integer. The number of Lua can process any long integer without worrying about the error.

(7) string indicates the character sequence. Like other objects, Lua automatically allocates and releases memory. A string can contain only one letter or a book, and Lua can efficiently process long strings, 1 m string is very common in Lua. You can use single or double quotation marks to represent strings. For the sake of unified style, it is best to use one type. Unless two types of quotation marks are nested, you can also use the Escape Character \ to represent the conditions where the strings contain quotation marks.

(8) The Escape Sequence in Lua is similar to that in C language. The special characters include:

\ [Left brackets

\] Brackets

(9) You can also use [[...] to represent a string. Strings in this form can contain multiple rows and can be nested without interpreting escape sequences. This form of string is very convenient to contain a piece of code.

(10) Lua automatically converts the type between string and number. When a string uses an arithmetic operator, the string is converted to a number. When Lua expects a string to encounter a number, the number is converted to a string.

Note: although the string and number can be automatically converted, the two are different. Comparisons like 10 = "10" are always wrong (during comparison, they are not automatically converted, need to display conversion !). If you want to convert string to a number, you can use the tonumber () function. If the string is not a correct number, the function returns nil. Instead, you can call tostring () to convert a number into a string.

(11). It is a string connector in Lua. When writing a number after a number, spaces must be added to prevent interpretation errors.

(12) functions are the same as other variables. functions can be stored in variables and can be used as function parameters or return values. (This feature gives Lua great flexibility: a program can redefine functions to add new features or hide functions to avoid running unreliable code to create a secure runtime environment)

(13) userdata can store c Data in Lua variables. In Lua, userdata has no predefined operations except assignment and equal comparison. Userdata is used to describe the new types created by applications or libraries implemented by C.

N any language has a lexical convention.

The identifier conventions of Lua are the same as those of C.

Note:

(1) Reserved Words of Lua cannot be used as identifiers.

And; break; do; else; elseif; end; false; For; function; If; In; local; nil; not; or; repeat; return; then; true;; while;

(2) Lua is case sensitive.

(3) single-line comment method :--

(4) multi-line comment method: -- [[--]

N common command line options

-E directly transmits the command to Lua

-L load a file

-I: Enter the interaction mode.

-Prompt built-in variables act as interaction mode prompts

Note:

The global variable Arg stores the Lua command line parameters. Before running, Lua uses all construction parameters to construct the ARG table. The script name index is 0, and the script parameter is increased from 1. The parameters in front of the script are reduced from-1.

N expression

Lua expressions include: Numeric constants, string constants, variables, unary and binary operators, and function calls.

(1) Arithmetic Operators

Binary OPERATOR: +-*/^ addition, subtraction, multiplication, and Division power

Unary operator:-negative value

The operands of these operators are all real numbers.

(2) Relational operators

<> <= >== ~ =

(3) logical operators

And or not

Note:

Logical operators consider false and nil as false, while others are true (0 is true ).

A and B

If a is false, A is returned; otherwise, B is returned.

A or B

If A is true, A is returned; otherwise, B is returned.

Ternary operators in C Language

A? B: c

In Lua, it can be implemented as follows:

(A and B) or C

Not always returns false or true.

(4) join Operators

... Two points

Note:

String connection. If the operand is a number, Lua converts the number to a string.

Table)

The constructor is the expression used to create and initialize tables. A table is unique to Lua. The simplest constructor is {}, which is used to create an empty table. You can directly initialize the array.

Note:

(1) It is not recommended that the array subscript start from 0, otherwise many standard libraries cannot be used.

(2) "," at the end of the constructor is optional and can be easily expanded in the future.

(3) In the constructor, the field separator comma can be replaced by a semicolon. Generally, a semicolon is used to separate different types of table elements.

2. Basic syntax

 

N Assignment Statement

Lua can assign values to multiple variables at the same time. The elements in the Variable list and Value List are separated by commas. The values on the right of the value assignment statement are assigned to the variables on the left in sequence. (In case of a value assignment statement, Lua calculates all values on the right and then performs the value assignment operation)

Note:

When the number of variables and the number of values are inconsistent, Lua always adopts the following strategy based on the number of variables:

A. number of variables> Number of values (Supplement nil by number of variables)

B. Number of variables <number of values (extra values will be ignored)

Note: To assign values to multiple variables, assign values to each variable in sequence (common errors ).

N local variables and code blocks

Use local to create a local variable. Unlike global variables, local variables are only valid within the declared code block.

Use local variables as much as possible:

(1) avoid naming conflicts;

(2) faster access to local variables than global variables;

A clear boundary can be defined for the block:

Do... end (this is useful when you want to better control the scope of local variables)

N control structure statement

(1) If has three forms

(2) While statement

(3) Repeat-until statement

(4) For has two forms

A: Numerical For Loop

For Var = exp1, exp2, exp3 do

Loop-part

End

For will use exp3 as the step from exp1 (initial value) to exp2 (termination value) and execute loop-part. Exp3 can be ignored. The default step is 1.

Note:

(1) The three expressions in for are calculated only once before the start of the loop.

(2) The control variable VAR is automatically declared as a local variable and only valid within the loop.

(3) to retain the value of the control variable, save it in a loop.

(4) do not change the value of the control variable during the loop process. The result is unpredictable. To exit the loop, use the break statement.

B: fan type for Loop

For I, Val in ipairs (a) Do print (v) End

The model for traverses each value (VAL) returned by the iteration subfunction ).

3 Function

Note:

(1) When calling a function, if the parameter list is empty, you must use () to call the function. However, when a function has only one parameter and the parameter is a string or table structure, () is optional.

(2) Lua also provides the object-oriented syntax for calling functions. For example, O: Foo (X) is equivalent to O. Foo (O, X.

(3) The functions used by Lua can be written by Lua or other languages. For Lua programmers, the functions implemented in the same language are used.

(4) the matching of the Lua function's real parameters and form parameters is similar to the value assignment statement. The excess parameters are ignored, and the missing parameters are supplemented with nil.

(5) The Lua function can return multiple result values. For example, String. Find returns the subscript of the start and end of the matched string. If no match string exists, Nil is returned. In the Lua function, multiple values can be returned by listing the values to be returned after return.

Note:

Return F () This type returns all values returned by F;

Print (FOO () can use parentheses to force the call to return a value;

(6) The special function unpack returned by multiple functions. It accepts an array as the input parameter and returns all elements of the array.

(7) The Lua function can be a variable parameter. Similar to the C language, "..." is used in the function parameter list to indicate that the function has a variable parameter. Lua places the function parameters in an ARG table. In addition to parameters, the ARG table also has a field n to indicate the number of parameters.

(8) Name Parameters

 

Further discussion of functions

 

(1) Closure

When a function is nested with another function definition, the internal function body can access the local variables of external functions. This feature is called lexical demarcation.

(2) Non-global functions (local functions)

Functions in Lua can be used as global variables or local variables. Function as the table field:

A: Put tables and functions together.

B: use the table constructor.

 

Lib_wcdj = {}

Lib_wcdj.add = function (x, y) return x + yend

Lib_wcdj.subtract = function (x, y) return x-y end

 

Lib_gerry = {

Multiply = function (x, y) return x * y end,

Divide = function (x, y) return x/y end

}

Print (lib_wcdj.add (1, 2 ))

Print (lib_wcdj.subtract (1, 2 ))

Print (lib_gerry.multiply (2, 3 ))

Print (lib_gerry.divide (5, 2 ))

 

--[[

3

-1

6

2.5

--]

 

(3) correct end call

The End call is a goto call similar to the end of a function. When the last action of a function is to call another function, this call is called the end call. For example, G is the end call.

Function f (x)

Return g (x)

End

F does not do anything after calling g. In this case, when the called function g ends, the program does not need to return to the caller F, therefore, after the End call, the program does not need to keep any information about the caller in the stack. Some compilers, such as The Lua interpreter, use this feature to process the final call without using additional stacks. It is said that this language supports correct end calls. Because the stack space is not required for the end call, the recursive hierarchy of the End call can be unlimited without causing stack overflow.

Note:

The final call must be clarified.

4 practice code

--[[test.lua 2012-04-02 wcdj-- --]]-- defines a factorial functionfunction fact (n)if n == 0 thenreturn 1elsereturn n*fact(n-1)endendfunction norm(x, y)local n2 = x^2 + y^2return math.sqrt(n2)endfunction twice (x)return 2*xendprint("enter a number: ")input = io.read() -- read a numberdata_in = tonumber(input)if data_in == nil thenprint("invalid number")elseprint(fact(data_in))endprint(tostring(10) == "10") -- trueprint(10 .. "" == "10")-- true--[[arg[-3] = "lua"arg[-2] = "-e"arg[-1] = "sin=math.sin"arg[0]  = "script"arg[1]= "a"arg[2]  = "b"--]]--[[print(arg[-3])print(arg[-2])print(arg[-1])print(arg[0])print(arg[1])print(arg[2])print(arg[3])--]]print(type("Hello world"))print(type(10.4*3))print(type(print))print(type(type))print(type(true))print(type(nil))print(type(type(X)))--[[stringnumberfunctionfunctionbooleannilstring--]]print(type(a))a = 10print(type(a))a = "a string !"print(type(a))a = printprint(type(a))a(type(a))--[[nilnumberstringfunctionfunction--]]a = "one string"-- change string partsb = string.gsub(a, "one", "another")print(a)print(b)--[[one stringanother string--]]print("10" + 1)print("10 + 1")-- error-- print("hello" + 1)--[[1110 + 1--]]print(10 .. 20)-- malformed number near '10..20'-- print(10..20)print("I'm " .. 10 .. " years old!")--[[1020I'm 10 years old!--]]print(4 and 5)print(nil and 6)print(false and 13)print(4 or 5)print(false or 5)--[[5nilfalse45--]]print(not nil)print(not false)print(not 0)print(not not nil)--[[truetruefalsefalse--]]print("Hello " .. "World")print(0 .. 1)--[[Hello World01--]]days = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday",}print(days[4])a = {x = 100, y = 200; "one", "two", "three"}print(a.x)print(a[0])print(a[1])print(a[3])print(a[4])b = {}b.x = 300b.y = 400print(b.x)--[[Wednesday100nilonethreenil300--]]a, b, c = 10, 2^4, "wcdj"print(a)print(b)print(c)a, b, c = 0print(a)print(b)print(c)--[[1016wcdj0nilnil--]]-- swapx = 1y = 3x, y = y, xprint(x)print(y)--[[31--]]x = 100if "wcdj" ~= "gerry" thenlocal xx = 1;print(x)elseprint(x)endprint(x)--[[1100--]]x = 100local x = 1print(x)dolocal x = 2print(x)endprint(x)--[[121--]]print(8*9, 1/3)a = math.sin(3) + math.cos(10)print(os.date())--[[72      0.33333333333333Mon Apr  2 14:54:02 2012--]]print "Hello World"print [[My name is wcdj]]--[[Hello WorldMy name is wcdj--]]a, b = string.find("hello Lua users", "Lua")print(a, b)--[[7       9--]]function maximum(a)local max_idx = 1local max = a[max_idx]for i, val in ipairs(a) doif val > max thenmax_idx = imax = valendendreturn max, max_idxendprint(maximum({8, 10, 23, 12 ,5}))print(maximum{8, 10, 23, 12 ,5})--[[23      323      3--]]function newCounter()local i = 0return function() -- anonymous functioni = i + 1return iendendadd = newCounter()print(add())print(add())--[[12--]]Lib_wcdj = {}Lib_wcdj.add = function (x, y) return x + y endLib_wcdj.subtract = function (x, y) return x - y endLib_gerry = {multiply = function (x, y) return x * y end, divide = function (x, y) return x / y end}print(Lib_wcdj.add(1, 2))print(Lib_wcdj.subtract(1, 2))print(Lib_gerry.multiply(2, 3))print(Lib_gerry.divide(5, 2))--[[3-162.5--]]

5 References:

[1] programming in Lua

[2] Lua 5.2 Reference Manual http://www.lua.org/manual/5.2

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.