"LUA Program Design" Learn notes __ Read book notes

Source: Internet
Author: User
Tags logical operators lua
The first chapter begins

If you use command-line parameter-I to start the LUA interpreter, the interpreter will enter interactive mode after the specified block is run. For example, at the command line, enter:

% Lua-i Prog

This will run the program block in file prog before entering interactive mode. Parameter-I is especially useful for debugging and manual testing.


An identifier in Lua can be a string of arbitrary letters, numbers, and underscores, but cannot begin with a number.

You should avoid using identifiers that start with an underscore followed by one or more uppercase letters (such as "_version"), and Lua retains such identifiers as a special purpose. The identifier "_" (an underscore) is usually reserved for use as a dummy variable (Dummy Variable).


You can start a line comment anywhere with two hyphens (--), which extends to the end of a line. Lua also provides "block annotations", starting with "--[[" until "]".


There are 8 basic types in Lua: nil (empty), Boolean (Boolean), Number (numbers), string (String), UserData (custom type), function (function), thread (thread), and table (tables).


Strings in Lua are immutable values. Instead of modifying a character of a string as you would in C, you should create a new string based on the modification requirements.


You can define an alphabetic string with a pair of matching brackets, and a string written in this form can extend more than one line, and Lua does not interpret the escape sequence. Also, if the first character of a string is a newline string, LUA ignores it. This writing is especially useful for writing strings that contain program code. The following example:

page = [[



chapter II Types and Values

In the table type, a.x and a[x] are not the same. The former represents a["X"], which means that the table is indexed with the string "X". The latter index table as the value of the variable x.


Although you can use any value as the index of a table, you can use any number as the starting value for an array index. But in the context of Lua's habits, arrays typically use 1 as the starting value for the index. And there are a number of mechanisms that depend on this formula.


In Lua5.1, the length operator "#" is used to return the last index value (or its size) of an array or a linear table. For example:

For I=1, #a does
  print (A[i])
end



Note: The index result for all uninitialized elements is nil. Lua takes nil as a flag to define the end of an array. When an array has "voids", that is, when the middle contains nil, the length operator considers these nil elements to be the end signs. It is certain that we do not want this unpredictability. Therefore, you should avoid using length operators for arrays that contain "voids." Most arrays do not contain "voids," so it is safe to use the length operator most of the time. If you really need to work with an array that contains "voids," you can use the function TABLE.MAXN, which returns the maximum number of positive indexes for a table. For example:

A = {}
a[1000] = 1
print (TABLE.MAXN (a))   --> 1000


In Lua, functions are treated as "first class values". This means that a function can be stored in a variable, passed by argument to another function, and can be the return value of another function.


The third chapter of expression

The logical operators have and, or, and not. As with conditional control statements, all logical operators treat false and nil as false, and any other thing as true. For operator and, the first operand is returned if its first operand is false, or the second operand is returned. For an operator or, if its first operand is true, the first operand is returned, or the second operand is returned.

Print (4 and 5)  -->5
print (nil and)-->nil
print (false and)-->false
print (4 or 5)-->4< C9/>print (False or 5)-->5



There is a commonly used Lua idiom, "x=x or V", which is equivalent to:

If not X then 
  x = v 
End


It can be set to a default value of V when no X is set.


Another idiom is "(A and B) or C", which is similar to the expression A?b:c in the C language, provided that B is not false. For example, to select the larger of the numbers x and y, you can use the following statement:

max = (x>y) and X or Y


To connect two strings in Lua, you can use the operator "..." and if any of its operands are numbers, LUA converts the number to a string:

Print ("Hello" ...). "World")-->hello World
Print (0.. 1)-->01



Whenever Lua evaluates a stereotype, it first creates a new table and then initializes it. This way, you can use table to write the following list code:

List = nil
for line in Io.lines () does
list = {next = list, value = line}
end


This code reads the contents of each row from the standard input, and then stores each row in the opposite order in a linked list. Each node in a list is a table,table containing two fields: value (the contents of each row) and next (a reference to the next node). But in real LUA programs, lists are rarely used.


Fourth Chapter statement

In multiple assignments, LUA first evaluated all the elements to the right of the equals sign before performing the assignment. This allows you to interact with two variables with a single sentence of multiple assignments. as follows:

X,y = y,x  -Exchange x and Y


In Lua, there is a customary way of writing:

local foo = foo

This code creates a local variable, foo, and initializes it with the value of global variable foo.


Lua also treats 0 and empty strings as true.


Because statements that are located after a return or break cannot be executed, they are usually used only in the few locations mentioned above. Sometimes, however, you may want to insert a return or break in the middle of a block. For example, you are ready to debug a function, but you do not want to perform the contents of that function. In this case, you can use a displayed do block to wrap a return statement:

function foo () return
  --<< syntax error-return
  is the last statement in the next block
  End--ok
  < Other statements > end



Fifth Chapter function

LUA adjusts the number of return values for a function to accommodate different invocation situations. When a function call is taken as a separate statement, LUA discards all return values for the function. If you call a function as part of an expression, Lua retains only the first return value of the function. You can get all of its return values only if a function call is the last element in a series of expressions (or only one element).


Sixth chapter Deep function

In Lua, a function is a "first class value" that has a specific lexical domain.

"First Class value": Represents a function in Lua with the same rights as other traditional types of values, such as numbers and strings. A function can be stored in a variable (whether global or local) or in a table, can be passed as an argument to another function, and can be the return value of another function.

Lexical fields: A function can be nested within another function, and internal functions can access variables in external functions.


Seventh chapter iterators and generics for

The so-called "iterator" is a mechanism that traverses all the elements of a set. In Lua, iterators are typically represented as functions. Each time a function is invoked, the next element in the collection is returned.

Each iterator needs to maintain some state between each successful invocation in order to know where it is and how to get to the next location.


The generic for holds the iterator function inside the loop process. In fact, it holds 3 values: An iterator function, a constant state (invariant states), and a controlling variable (control variable).

The syntax for generics for is as follows:

For <var-list> in <exp-list> does
  <body>
end


Where,<var-list> is a list of one or more variable names, separated by commas;<exp-list> is a list of one or more expressions, also separated by commas. Usually an expression list has only one element, that is, a call to an iterator factory. For example, the following code:

For k,v in pairs (t) does print (K,V) end


Where the list of variables is "k,v", the expression list has only one element pairs (t). In general, there is only one variable in the list of variables, such as the following loop:

For line in Io.lines () does
  io.write (line, \ n) End


The first element of a variable list is called a control variable. This value is never nil during the loop because the loop ends when it is nil.

For the first thing to do is evaluate the expression in the following. These expressions should return 3 values for Save: The initial value of the iterator function, the constant state, and the control variable. This is somewhat similar to multiple assignments, where only the last expression produces multiple results, and only the first 3 values are retained, and the excess value is discarded, and, if not enough, it is nil.

After the step is initialized, for a constant state and control variable to invoke the iterator function. Then, for assigning the return value of the iterator function to the variable in the variable list. If the first return value is nil, then the loop terminates. Otherwise, the for executes its loop body, then calls the iterator function again, and repeats the process.

More specifically, the following statement:

For var_1,..., var_n in <explist> doing <block> end


Equivalent to the following code:

Do local
  _f,_s,_var = <explist>
  While true does local
    var_1, ..., var_n = _f (_s, _var)
    _var = Var_1
  if _var = = Nil Then break end
    <block> End


Therefore, assuming that the iterator function is F and the constant state is S, the initial value of the control variable is a0. Then the value of the control variable in the loop is A1 = f (s,a0), a2 = f (s,a1), and so on until the AI is the nil end loop. If there are other variables for the, they will also get an extra value after each call to F.


Eighth chapter compilation, execution and error

Although Lua is referred to as an interpreted language, LUA does allow the source code to be precompiled into an intermediate form before running the source code. It sounds like "compiling" should not be in the category of an interpretive language. In fact, the main feature of the differential interpretation language is not whether they can be compiled, but whether the compiler is a part of the library, whether it is capable (and easily) to execute dynamically generated code. It can be said that because of the existence of functions such as Dofile, LUA can be referred to as an interpreted language.


When a function encounters an unexpected condition (that is, an "exception"), it can take two basic behaviors: returning an error code (usually nil) or raising an error (call error). There is no fixed rule between the two choices, but the usual guideline is that an exception that is easy to avoid should raise an error or return an error code.


Nineth Chapter Cooperative Procedure

A collaborative program is similar to a thread, a sequence of execution, with its own stack, local variables, and instruction pointers, while sharing global variables and most other things with other collaborative programs. Conceptually, the main difference between a thread and a collaboration program is that a program with multiple threads can run several threads at the same time, while a collaborative program needs to work in concert with one another. That is, a program that has multiple concurrent programs can only run a single program at any one time, and a cooperating program that is running will only suspend execution when it explicitly asks to be suspended.


A collaborative program can be in 4 different states: Suspend, Run, die, and normal. When you create a collaboration program, it is in a pending state.

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.