Learning notes for LUA Basic grammar

Source: Internet
Author: User
Tags arithmetic arithmetic operators data structures numeric logical operators lua


LUA annotations

--Single-line Comment: Use two minus signs to indicate this line is commented
Print ("Hello Lua.")

--[[
Multiple-line comment. The rows in this range are looked at.
]]
Print ("Hello world.")
LUA data types

Lua is a dynamic type language, and variables do not require type definitions. There are 8 basic types in Lua, respectively:
1, special type in Nil:lua, the default value is nil before the variable is assigned, and assigning to the variable as nil can delete the variable.
2, Boolean: Boolean type. Desirable value true and false
3, Number: Digital type
4, String: String, in Lua the string can contain any character and the string cannot be modified.
5, table: tables. An array, a dictionary, similar to other languages.
6, Function: Functions type. LUA can call LUA or C-implemented functions, and all of the standard libraries in LUA are implemented in C. The standard library includes string libraries, table libraries, I/O libraries, OS libraries, arithmetic libraries, and debug libraries.
7, UserData: This type specializes in Lua's host. Hosts are usually developed by the C and C + + languages, in which case UserData can be any type of host, commonly used in structure and pointer type
8. Thread: Threading Type

Lua expressions

A, arithmetic operators: + (plus)-(minus) * (multiply)/(except) ^ (exponentiation)% (modulo)

B, relational operator: > (greater than) < (less than) >= (greater than or equal to) <= (less than equals) = = (equal) = = (equals) ~= (not equal to, this is a bit different!) )

C, logical operators: and OR not

Logical operators think false and nil false (false), others are true, and 0 is true!!! The operations of and and or are not true and false, but are related to its two operands.

A and B-if a is false, return a, or return B
A or B-if A is true, return a, or return B
D, join operators
.. Two points represent string concatenation, and Lua converts numbers to strings if operands are numbers

Print ("Hello" ...) Lua ")

LUA Basic syntax

A, variable

A variable can be used without declaring it, and assigning a value to a variable creates this variable. By default, all of LUA's variables are global variables, and if you need to declare a local variable, you can add it to the front, such as:

--Global variables
A = 1

--Local variables
Local B = 2

--equivalent to x = 1;y = 2
X,y = 1,2

--swap values for x and Y
X,y = Y,x

B, if statement


If Mon = 1 Then
Print ("Out of the box")
ElseIf Mon = = 2 Then
Print ("Feb")
Else
Print ("other")
End
C, while statement

Lua, like other common languages, provides a while control structure that is not syntactically specific. But the Do-while type control structure is not provided, but the function of the repeat is provided.


a=10
While a < do
Print ("Value of A:", a)
A = A+1
End
It is worth mentioning that Lua does not provide control statements like continue in many other languages for immediate access to the next loop iteration (if any). Therefore, we need to carefully arrange the branches in the loop body to avoid such a requirement.

D, repeat-until statements
The repeat control structure in Lua is similar to the do-while in other languages, such as the C + + language, but the control method is just the opposite. Simply put, the repeat loop body is executed until the until condition is true, while the do-while of other languages (such as the C + + language) end the loop when the condition is false.

A = 10
Repeat
Print ("Value of A:", a)
A = a + 1
Until a > 15

E, for statement

The For statement has two forms: a numeric for (numeric for) and a generic for (generic for).
E.1, numeric for loop

For init,max/min value, increment
Todo
Statement (s)
End

The following is the process of controlling a loop:

1. The initiation steps are first executed and only once. This step allows you to declare and initialize any of the loop control variables.
2, followed by the Max/min, which is the maximum or minimum value until the loop continues to execute. It creates a comparison between the initial and maximum/minimum values of a condition check internally.
3. After the For loop body executes, the control flow jumps back to the increment/decrement declaration. This statement can update any loop control variable.
4. The condition is now recalculated and evaluated. If this is true, the loop executes and repeats the process (the loop body, then adds one step, then the condition). If the condition is false, the loop terminates.

Example:


--Print 10 ... 1
For i=10,1,-1
Todo
Print (i)
End

E.2, generic for loop

The generic for loop traverses all values through an iterator (iterator) function:


--Print all values of array ' a '
For i,v in Iparis (a) doing print (v) end

--Print all keys of table t
For K in Paris (T) does print (k) End
F, break, and return statements
The break statement is used to exit the current loop (for, repeat, while). Not available outside of the loop. Return returns the result from the function.
Lua syntax requires that break and return can only appear at the end of a block (that is, the last sentence of chunk, before the end, else before or before until).

Lua table

Table is an important data structure in Lua, it can be said to be the basis of other data structures, usually arrays, records, linear tables, queues, sets and other data structures can be represented by a table, even global variables (_g), modules, meta table (metatable) and other important Lua Elements are the structure of the table. It can be said that table is a powerful and magical thing. The table is constructed with two curly braces. Such as:


Days = {"Sunday", "Monday", "Tuesday"}

For IDX, day in Ipairs
Print (IDX, day)
End
You can use any type of value to count the index of a group, but this value cannot be nil
The domain delimiter comma (",") in the constructor can be separated by a semicolon (";"). Instead, we usually use semicolons to divide different types of table elements.


{x=10, y=45; "One", "two", "three"}

All index values need to be enclosed in "[" and "]", and if it is a string, you can also remove the quotation marks and brackets; that is, if there is no [] enclosed, it is considered a string index


Day = {1,2,3,4,5,6,7}
days = {[Day] = "table", sun= "Sunday", ["mon"] = "Monday", 123}
Print (Days[day])
Print (days["Sun"])
Print (Days.mon)
Print (Days[1])

If the index is not written, the index is considered a number and is automatically compiled from 1 in order;


Days = {"Sunday", "Monday",}
For I=1, #days do
Print (Days[i])
End

When using a table, for strings, you can access them through the.


Days = {Sun = "Sunday", Mon = "Monday",}
Print (Days.sun)
Print (days["mon"])
LUA functions

A function can be stored in a variable, passed to another function by argument, or as a function return value (analogous to a function pointer in C + +), which gives Lua great flexibility. LUA provides good support for functional programming and can support nested functions.
In addition, LUA can invoke functions written by Lua and invoke functions written in C (all of the standard libraries in Lua are written in C).


function Func_name (arguments-list)
Statements-list
End

The LUA function argument and the shape participation assignment statement are similar, the superfluous part is ignored, the missing part is supplemented with nil. When a function is called, when there is only one argument and the argument is a string or the table construction time bracket is optional. Such as

Print "Hello Lua"
F{x = ten, y = 20}

1. The LUA function does not support parameter defaults, which can be implemented by or.


function sum (A, B)
A = A or 1.1
B = B or 2.2
Return a + b
End

Print (sum ())

2. The LUA function supports multiple return values

function Str_replace ()
Return "Hello Lua", 1
End

A, B = str_replace ()
Print (A,B)

3. The LUA function can support variable-length parameters
The LUA function can accept a variable number of arguments, passing three dots (...). Indicates that the function has variable parameters.


function sum (...)
For i,v in pairs ({...}) do
Print (I, v)
End
End

SUM (2,3,4)

Typically, you only need to use {...} when traversing variable-length parameters, whereas variable-length parameters may contain some nil; then you can use the Select function to access variable-length arguments: Select (' # ', ...) or select (N, ...)
Select (' # ', ...) Returns the length of a variable parameter, select (n,...) Used to access N to select (' # ',...) The parameters

4. The LUA function supports named parameters
The function parameters of LUA are related to the position, and the actual participants are passed to the formal parameters sequentially. Sometimes it is useful to specify parameters by name, such as the rename function is used to rename a file, and sometimes we do not remember the order of the two parameters before and after the naming:


Rename{old= "Temp.lua", new= "Temp1.lua"}

Lua can implement this pseudocode by putting all the parameters in a table and using the table as a unique parameter to the function. Because the LUA syntax supports function calls, arguments can be constructs of a table.

5. LUA functions support closures

tab = {1,2,3,4,5,6,7,8}

function iter ()
Local index = 0
return function ()
index = index + 1
return Tab[index]
End
End

For I in ITER () do
Print (i)
End

6. Lua functions can be placed in variables, tables

Local sum = function (...)
Local s = 0
For _, V. in pairs ({...}) do
s = s + V
End
return s
End
Print (sum (1,2,3,5))

Op = {add = sum}
Print (Op.add (1,2,3))
Similarly, a function can be passed as a parameter or returned as a return value

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.