Lua2.4 Reference Manual (2)

Source: Internet
Author: User

(Part 1)
--------------------------------------
4 languages
--------------------------------------
This section describes Lua's lexical, syntax, and semantics.

-------------------
4.1 lexical conventions
-------------------
Lua is a case-sensitive language. An identifier can be a string consisting of letters, numbers, and underscores. The first letter cannot be a number. The following are reserved keywords that cannot be used as identifiers:
And do else elseif end
Function if local nil not
Or repeat return until then while

The following string is reserved for use:
~ = <=> = <>== =... + -*/
% () {} [];,.

String constants can be defined by pair single quotes or double quotes, and can include escape sequences '\ n',' \ t', and '\ R' in the C language style '. String constants can also be defined by [[...] pairs. The latter form of literal can be cross-row, can contain nested [...], and does not explain the escape sequence.

A comment can start anywhere outside the string with two hyphens (--) until the end of the line.

A numerical constant can be written into an optional fractional part and an optional exponent part. The following are examples of valid numerical constants:
4. 4 4.57e-3. 3e12

-------------------
4.2 conventions
-------------------
Lua provides some automatic conversions. Arithmetic Operations on strings attempt to convert strings into numeric values and follow the common rules. On the contrary, when a value is involved in a string operation, the value is converted to a string. According to the following rule: if the value is an integer without an index or decimal point, it is converted directly; otherwise, it is converted in the same format as the standard C function printf "% G.

-------------------
4.3 Adjustment
-------------------
The function in Lua can return multiple values. Because there is no type declaration, the system does not know how many values the function will return or how many parameters it needs. Therefore, sometimes, the value list must be adjusted to the given length at runtime. If the actual value is greater than the required value, the extra value will be discarded. If the required value is greater than the actual value, nil expansion will be performed in the list as needed. The adjustment also involves multiple values and function calls.

-------------------
4.4 statement
-------------------
Lua supports almost all general statements. Common Commands include assignment, control structure, and process call. Unconventional Commands include the table constructor described in section 4.5.7 and the declaration of local variables.

---------
4.4.1 Block
---------
A block is a list of statements executed in sequence. Any statement can be optional followed by a semicolon.
Block --> {stat SC} [ret SC]
SC --> [';']
For semantic analysis, the return statement can only be the last sentence in a block. This constraint also avoids the "statement not reachable" error.

---------
4.4.2 value assignment
---------
Lua supports multiple values. Therefore, the syntax defines a variable list on the left and an expression list on the right. Both list elements are separated by commas.
Stat --> varlist1 '= 'explist1
Varlist1 --> var {', 'var}
This statement first finds all the values on the right, sorts the variables on the left, and assigns values to them. Therefore, the values of two variables can be exchanged as follows:
X, Y = Y, X
Before a value is assigned, the Value List is adjusted to be the same length as the variable list (see section 4.3 ).

VaR --> name
A name can indicate a global variable, a local variable, or a formal parameter.

VaR --> var '['exp1']'

Square brackets are used to index the table. If the result of VaR is a table, the value assigned is obtained by the field indexed by the expression value. Otherwise, the settable function (fallback) is called and there are three parameters when called: the value of VaR, the value of the expression, and the value to be assigned. See section 4.7.

VaR --> var '. 'name
Var. Name is just the syntax sugar of VaR ['name.

---------
4.4.3 Control Structure
---------
The conditional expression of the control structure can return any value. All values that are not nil are considered true, while Nil is considered false. If, while, and repeat have the same meaning as normal.
Stat --> while exp1 do block end
Stat --> repeat block until exp1
Stat --> If exp1 then block {elseif} [else block] End
Elseif --> elseif exp1 then block
Return is used to return values from a function. Because a function can return multiple values, the syntax of the return statement is:
RET --> return explist

---------
4.4.4 function call as a statement
---------
Due to side-effects, function calls can be executed as statements.
Stat --> functioncall
The last returned value is discarded. Function calls are explained in section 4.5.8.

---------
4.4.5 local Declaration
---------
Local variables can be declared anywhere in the block. Its scope starts from the declared place until the block ends. A statement can contain an initial value.
Stat --> Local declist [init]
Declist --> name {', 'name}
Init --> '= 'explist1
If an initial value assignment operation is performed, it has the same semantics as multiple values. Otherwise, all variables are initialized as nil.

-------------------
4.5 expression
-------------------
---------
4.5.1 simple expression
---------
The simple expression is:
Exp --> '('exp ')'
Exp --> Nil
Exp --> 'number'
Exp --> 'literal'
Exp --> VaR
The values (numerical constants) and string constants are explained in section 4.1. The variables have been explained in section 4.4.2.

---------
4.5.2 Arithmetic Operators
---------
Lua supports common arithmetic operators. These operators are binary operators +,-, *,/and ^ (power), and unary operators -. If the operand is a numeric value, or a string that can be converted to a numeric value according to the rules given in section 4.2, all operations (except power operations) have a general significance. Otherwise, the rollback function "Arith" will be called. See section 4.7. The power operation will always call This rollback function. The standard math redefines the power operation rollback as expected. See section 6.3.

---------
4.5.3 Relational operators
---------
Lua provides the following Relational operators:
<> <=> = ~ ===
They return nil as false, and non-nil (the fact is the value 1) is true.

Equal first, compare the types of two operands. If they are different, the result is nil. Otherwise, compare their values. The value or string is compared in common mode. Table, cfuntion, and function are compared by reference. That is to say, the two compared tables are considered equal only when they are the same. Unequal operation ~ = And equal operation (=) have completely opposite results.

Other operators work like this: if both parameters are numerical values, they are compared with numerical values. If both parameters can be converted to strings, they are compared in lexicographically. Otherwise, the rollback function "order" will be called. See section 4.7.

---------
4.5.4 logical operators
---------
All logical operators, like the control structure, assume that nil is false and all others are true. The logical operators are:
And or not
And and or are short-circuit values, that is, the second operand is evaluated only when needed.

---------
4.5.5 connection
---------
Lua provides a String concatenation operator "...". If the operands are strings or numbers, they are converted to strings according to the rules in section 4.2. Otherwise, the rollback function "Concat" will be called. See section 4.7.

---------
4.5.6 priority
---------
The operator priorities are listed in the following table, in ascending order:
And or
<> <=> = ~ ===
..
+-
*/
Not-(unary)
^
Except for the specific left concatenation of the binary operator ^, the power operation has the right combination.

---------
4.5.7 Constructor
---------
The table constructor is the expression used to create a table. When you evaluate the constructor of a table, a new table is generated. The constructor can be used to create an empty table or a new table and initialize some fields.
The constructor syntax is as follows:
Tableconstructor --> '{'fieldlist '}'
Fieldlist --> lfieldlist | ffieldlist | lfieldlist '; 'ffieldlist
Lfieldlist --> [lfieldlist1]
Ffieldlist --> [ffieldlist1]

Lfieldlist1 is used to initialize the list.
Lfieldlist1 --> exp {', 'exp} [', ']

The expression in the list is assigned a continuous value index, which starts from 1. For example:
A = {"V1", "V2", 23}
Equivalent:
Temp = {}
Temp [1] = "V1"
Temp [2] = "V2"
Temp [3] = 34
A = temp

Another form is used to initialize the name field in the table:
Ffieldlist1 --> Ffield {', 'ffield} [', ']
Field --> name' = 'exp
For example:
A = {x = 1, y = 3}
Equivalent:
Temp = {}
Temp. x = 1
Temp. Y = 3
A = temp

---------
4.5.8 function call
---------
Function calling has the following syntax:
Functioncall --> var realparams
Here, VaR can be any variable (global, local, subscript index, etc.). If its type is function or cfunction, this function will be called. otherwise, the callback function "function" is called. The first parameter is the value of VaR, followed by the original call parameter.

Shape:
Functioncall --> var ': 'name realparams
It can be used to call "methods ". VaR: Name (...) is the syntactic sugar of Var. Name (VAR. Except var, it is evaluated only once.
Realparams --> '(' [explist1] ')'
Realparams --> tableconstructor
Explist1 --> exp1 {', 'exp1}
All parameter expressions are evaluated before the function is called. Then, the real parameter list is adjusted to the same size as the parameter list (see section 4.3). Finally, this list is assigned to the form parameter. F {...} calls the syntax sugar of F ({...}), that is, the parameter list is a new table.

Because a function can return any number of values (see Section 4.4.3), the number of returned values must be adjusted before use. If a function is used as a statement (see section 4.4.4), its return results are adjusted to 0 (that is, all are discarded ). If a function is called where a value (expressed as a non-final exp1 In the syntax) is required, the returned result is adjusted to one. If a function is called where multiple values are needed (syntactically expressed as non-final exp), no adjustment is made to the returned results.

-------------------
4.6 Function Definition
-------------------
The function can be defined at any global level in the module. The syntax of the function definition is:
Function --> function var '(' [parlist1] ')' block end

When Lua pre-compiles a module, all its function bodies are also pre-compiled. Then, when Lua "executes" The Function Definition, its function body is saved in the variable var and its type is function.

Parameters are the same as local variables. parameter values are initialized.
Parlist1 --> 'name' {', 'name}

The return result is returned by the Return Statement (see Section 4.4.3 ). If no return command is executed at the end of the function, the function does not return a value.

The function definition has a special syntax, that is, the function has an additional parameter self.
Function --> function var ': 'name' (' [parlist1] ') 'block end
A statement is as follows:
Function V: F (...)
...
End
Equivalent
Function V. F (self ,...)
...
End
That is, the function obtains an additional parameter named self. Note that the variable V must be initialized to table in advance.

-------------------
4.7 rollback
-------------------
(Fallbacks does not know what to translate into. Is it a rollback? Preset? Fall? Here we call it a rollback, but we should call it a more appropriate preset. I know that writing for rollback refers to fallback. I knew that I would not translate it, but it would be better to use English directly .)
Lua provides a powerful mechanism to expand its semantics, called fallbacks ). Basically, a rollback is a programmer-defined function that will be called when Lua does not know how to continue execution.
Lua supports the following rollback, identified by a given string:
"Arith" is an arithmetic operation applied to non-numeric operations, or when the power operation ^ is called. It accepts three parameters: two operands (if the second is nil when the single-object subtraction operation is performed) and one of the following strings that describe the error OPERATOR:
Add sub Mul Div POW UNM
The return value is the final result of arithmetic operations. The default function triggers an error.
"Order" is a comparison operation applied to non-numeric or non-string type operands. It accepts three parameters: two operands and one of the following strings that describe the error OPERATOR:
Lt gt le Ge
The return value is the final result of the comparison operation. The default function triggers an error.
"Concat" is a join operation applied to non-string operands. It accepts two operands as parameters. The return value is the final result of the join operation. The default function triggers an error.
"Index" Lua tries to obtain the value of an index not in the table. It accepts table and index as parameters. The return value is the final result of the index operation. The default function returns nil.
"Getglobal" Lua tries to obtain a global variable whose value is nil (or when the global variable is not initialized ). It accepts the variable name as a parameter. The return value is the final result of the expression. The default function returns nil.
"Gettable" Lua tries to index a non-Table value. It accepts non-table values and index as parameters. The returned value is the final result of the index operation. The default function triggers an error.
"Settable" Lua tries to assign a value to an index with a non-Table value. It accepts non-table values, index indexes, and assigned values as parameters. The default function triggers an error.
"Function" Lua tries to call a non-function value. It accepts non-function values and originally called parameters as parameters. The returned value is the final result of the call operation. The default function triggers an error.
"GC" garbage collection. It accepts the table to be reclaimed as a parameter. The garbage collector calls it after each call. The parameter is nil. Because this function runs in garbage collection, you must be cautious when using it. programmers should avoid creating new objects (tables or strings) in it ). The default function does not do anything.
"Error" when an error occurs. It accepts a string with an incorrect description as a parameter. The default function prints the error message to the standard error output.
The setfallback function is used to change a rollback action. Its first parameter is a string describing fallback, and the second parameter is the new rollback function. It returns the corresponding old rollback function.
Section 8.6 shows an example of using rollback.

-------------------
4.8 handle errors
-------------------
Because Lua is an extension language, all Lua Actions start from calling a function in the Lua library in the C code. When an error occurs during Lua compilation or execution, the fallback function is called, and the functions in the corresponding Library (lua_dofile, lua_dostring, lua_call, and lua_callfunction) is terminated and an error is returned.
The unique parameter of the error rollback function is a string that describes the error. The standard I/O Library redefines This rollback using a debug mechanism (see section 7) to print additional information such as the call stack. To get more information about errors, the Lua program can contain the Compilation instruction option $ debug. This indicates that only one row is exclusive. When an error occurs with this Compilation instruction option, the error checking program can print the calling (and error) lines that cause the error. If necessary, you can modify the error handling rollback program. See section 4.7.
The Lua code may generate an error by calling the function error. Its optional parameter is a string used as an error message.
(To be continued)

Lua2.4 Reference Manual (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.