A guide to the introduction of the Lua minimalist (i): basic knowledge Article _lua

Source: Internet
Author: User
Tags arithmetic comments goto numeric logical operators lua

This article is a reading note in the "Programming in Lua 3rd".

Chunks

A Chunk is a set of executed statements, such as a file or a row in interactive mode.

Identifiers (Identifiers)

We should avoid using a string that starts with _ and follows one or more uppercase letters as identifiers, and they are reserved for special purposes (e.g., _version).

Comments

Single-line comments Use

Copy Code code as follows:

--

Multiple-line annotations use
Copy Code code as follows:

--[[and--]]

Introduction to Types

The data types that Lua exists include:

1.nil. This type has only one value nil. Used to indicate an "empty" value. Global variable defaults to nil, delete a global variable that has already been assigned only by assigning it to nil (compared to JavaScript, assigning null does not completely remove the object's properties, the property also exists, the value is null)

2.boolean. This type has two values true and false. In Lua, false and nil both indicate conditional leave, and other values indicate that the condition is true (0 is true for languages different from C + +)

3.number. Double Fine floating-point number (IEEE 754 standard), Lua does not have integer types

4.string. You can save any binary data into a string (including 0). Characters in a string cannot be changed (you can only create a new string when you need to change it). Gets the length of the string, which can be used with the # operator (the length operator). For example: print (# "Hello"). Strings can be wrapped with single quotes or double quotes, and [[and]] packages can be used for multiple-line strings. Escape characters can be used in strings, for example \ r \ n, and so on. Escape characters in strings that are wrapped with [[and]] are not escaped

5.userdata. Used to hold arbitrary C data. UserData can only support assignment operations and comparison tests

6.function. function is the first class value (first-class value), we can use functions like other variables (functions can be stored in variables, can be passed as arguments to functions)

7.thread. Different from what we often say about system-level threads

8.table. is implemented as an associative array (associative arrays) that can be indexed by any value (except nil). As with global variables, the Unassigned field in the table is nil, and the only way to delete a field is to assign it to nil (in fact, the global variable is placed in a table)

The type function is used to return the types of values:

Copy Code code as follows:

Print (Type ("Hello World")--> string
Print (Type (10.4*3))--> number
Print (type (print))--> function
Print (Type (X))--> string

In Lua, any variable can hold any value.

Table Use Introduction

You can create a table by using a construction expression:

Copy Code code as follows:

--Create an empty table
A = {}

--Create and initialize a table, where
--days[1] = = "Sunday"
--days[2] = = "Monday"
-- ...
Days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

--Create and initialize a table, where
--a["x"] = = 10
--a["y"] = = 20
A = {x = ten, y = 20}

Use the [] operator to access the field of the table:

Copy Code code as follows:

A = {}
K = "X"
A[K] = 10
a["x"] = 20
Print (a["y"])--> Nil
a.x = 30

Note that the A.name syntax is equivalent to a[' name '.

A table can be used to represent an array, at which point the index is an integer and starts at 1 (not 0), for example:

Copy Code code as follows:

A = {' A ', ' B '}
A[1] = = ' a '
A[2] = = ' B '

The length operator can get the length of the table array part:

Copy Code code as follows:

A = {}
A[1] = 1
A[2] = 2
Print (#a)--> 2

A.A = 1
A.B = 2
Print (#a)--> 2

A = {}
A.A = 1
A.B = 2
Print (#a)--> 0

An expression

Arithmetic operator

1.+ (plus)
2.-(minus)
3.* (multiply)
4./(except)
5.^ (Power)
6.% (Take Mold)

Any arithmetic operator attempts to convert the operand to a numeric type, for example:

Copy Code code as follows:

Print (Ten + ' 1 ')--> 11

Relational operators

1.< (less than)
2.> (greater than)
3.<= (less than or equal)
4.>= (greater than or equal to)
5.== (equals)
6.~= (not equal to)

Two different types of values are not equal, for example:

Copy Code code as follows:

Nil ~= False

Table, UserData types are compared by reference, for example:

Copy Code code as follows:

A = {}; a.x = 1; A.Y = 0
b = {}; b.x = 1; B.Y = 0
c = A

Here A and C refer to the same object, so a = = C, but a ~= B (even if a, B content is the same).

logical operators

1.and
2.or
3.not

The logical operator has a return value. For an and operation, the second operand is returned if the first operand is false and the operand is returned. For an OR operation, the second operand is returned if the first operand is not false and returns this operand.

Connection operator

string concatenation can use the join operator "...", for example:

Copy Code code as follows:

Print ("Hello" ...) World ")

The connection operator attempts to convert the operand to a string, for example:
Copy Code code as follows:

Print ("Number:" ...). 1)

Statement

Multiple assignment (multiple assignment) support, for example:

Copy Code code as follows:

A, B = 1, 2
Print (a)--> 1
Print (b)--> 2

One idiom for multiple assignments is to exchange the values of two variables:
Copy Code code as follows:

X, y = 1, 2
X, y = y, X
Print (x)--> 2
Print (y)--> 1

To create a local variable to use regional:
Copy Code code as follows:

j = 10--Global variable J
Locals i = 10--local variable i

The scope of local variables is limited to the blocks they declare. Blocks (block) include:

1. Main part of control structure
2. Function body
3.chunk
4.do-end

Example:

Copy Code code as follows:

If True Then
Local x = 20
Print (x)--> 20
End

Print (x)--> Nil

We can use the Do-end keyword to construct a block:
Copy Code code as follows:

Todo
Local x = 20
Print (x)--> 20
End

Print (x)--> Nil

Accessing a local variable is faster than accessing the global variable. There is a idiom in Lua:
Copy Code code as follows:

local foo = foo

Used to create a local variable and initialize it to a global variable of the same name. This is often done for two reasons:

1. Avoid certain types of global variables being modified
2. Improve Access speed

Control structure

If then ElseIf else

Copy Code code as follows:

If a < 0 Then
A = 0
End

If a < b then
Return a
Else
Return b
End

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

There are no switch statements in Lua.

While

Copy Code code as follows:

Local i = 1
While A[i] do
Print (A[i])
i = i + 1
End

Repeat

Copy Code code as follows:

Repeat
line = Io.read ()
Until Line ~= '
Print (line)

Unlike While,repeat, the loop body is executed first, and then the test condition is judged.

Numeric for (numeric for)

For there are two kinds of:

Numeric for (numeric for)

1. Generics for (generic for)
2. The numeric for syntax is as follows:

Copy Code code as follows:

for var = exp1, Exp2, Exp3 do
<something>
End

Here EXP1 as the initial value of Var, exp2 is the maximum value of Var, exp3 is the value of Var increment each time, EXP3 is optional, the default is 1. Example:
Copy Code code as follows:

--Output 1 2 3
For i = 1, 3 do
Print (i)
End

There are some places to note:

The EXP1, EXP2, and Exp3 in 1.for are counted only once, for example:

Copy Code code as follows:

For i = 1, f (x) does print (i) end

The f (x) here will only be called once

2. Control variable var is only a local variable
3. Do not attempt to modify the value of the control variable VAR (the result is unknown)

Generics for

Generics for traversal through an iterator function, for example:

Copy Code code as follows:

For K, v. in pairs (t) do
Print (k, v)
End

The pairs here is an iterator function that iterates through table T, each time the key that gets is saved in the variable K, and the value obtained is saved in the variable v. In addition to pairs, there are other iterators that can be used:

1.io.lines can be used to iterate through the rows in a file
2.ipairs the array portion that can be used to iterate the table

We can also write iterators ourselves.

Break, return, goto

The break statement is used to jump out of a loop (for, repeat, while).

The return statement is used for returning a result to a function. In Lua, the return statement must be the last statement of a block, looking at an example:

Copy Code code as follows:

function foo ()
--Grammatical errors
Return
Local i = 1
End

Sometimes, for some reason (for example, for debug), we need to insert a return statement in a function, which we can do:

Copy Code code as follows:

function foo ()
-- ...
Do return end
-- ...
End

The goto statement is used to jump in a function. A goto statement allows execution to jump to a specific label (label), for example:

Copy Code code as follows:

Goto quit
Print (' Come on ')
:: Quit::
Print (' Quit ')

Here the output quit. As we can see, the label is written as:: Name::. Goto jumps are also limited:

1. Not allowed to jump to a block
2. Not allowed to jump outside the function
3. Not allowed to jump into the scope of a local variable

For the 3rd, look at an example:

Copy Code code as follows:

Goto quit
Local A
:: Quit::
Print (' Quit ')

Here, there will be a syntax error (jumps into the scope of "a"). However, there is one detail that needs to be noted, we first modify the example above:

Copy Code code as follows:

Goto quit
Local A
:: Quit::

Execution succeeded with no syntax errors. This is because the scope of the local variable ends with the last non-void statement of the block defined by the variable, the label is considered to be a void statement, and for the above example, the scope of A is:: Quit:: It is over, so Goto quit does not jump into the scope of local variable a.

The use of Goto can be more convenient to write state machines, such as (S1, S2 for state):

Copy Code code as follows:

:: S1:: Do
Local C = io.read (1)
if c = = ' 0 ' then goto S2
ElseIf c = = Nil then print ' OK '; Return
else goto S1
End
End

:: S2:: Do
Local C = io.read (1)
if c = = ' 0 ' then goto S1
ElseIf c = = Nil Then print ' Not OK '; Return
else goto S2
End
End

Goto S1

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.