Lua programming skills learning tutorial

Source: Internet
Author: User

LuaProgramming Skills Learning tutorial is the content to be introduced in this article, mainly to learnLUAProgramming skills, so that you can learn more easily, first to the details of this article.LuaVersion 5.1 has been officially released. Now we should put all the discussions on this version.

Use local whenever possibleVariableNot globalVariable. This isLuaThe easiest mistake for beginners. The global variable is actually placed in a global table. GlobalVariableIt is actually using a string (VariableTo access this table.

Although the table efficiency of Lua5 is very high, there is still a lot of efficiency loss compared with the local variable. The local variable is directly accessed through the Lua stack. Some global variables are inadvertently accessed. For example, we have a dual loop to operate an iterative table:

 
 
  1. for k1,v1 inpairs(tbl)dofor k2,v2 inpairs(v1)do  
  2.         ...   
  3.     end  
  4. end 

Here, pairs is actually a Function Applied to global variables. If we do this:

 
 
  1. dolocalpairs=pairs  
  2.     for k1,v1 inpairs(tbl)dofor k2,v2 inpairs(v1)do  
  3.             ...   
  4.         endend  
  5. end 

The efficiency will be slightly improved. This is meaningless if it is a single-layer loop. Because the pairs function in the for... in loop will only be called once, instead of being called every loop. Our principle is that the global variables read multiple times should be extracted and put into the local variables.

Be cautious about the connection operation of the Temporary Variable string and generate new objects. This is causedLuaThis is caused by the string management mechanism.LuaIn the VM, only one unique copy is retained for the same string, so that all string comparisons can be simplified to address comparisons. This is alsoLuaOne of the reasons for the quick table operation. This string management policy is the same as java, so like java, we should try to avoid continuously connecting strings in the loop, such as a = a. x. A new copy may be generated every time you run it.

Similarly, remember that each time you construct a table, there will be an additional copy of the table. For example, in lua, the plane coordinates are encapsulated into {x, y} for parameter transmission. This problem needs to be considered. Every time you want to construct a coordinate object and pass it to a function, a new table will be constructed every time you write it clearly in the format of {10, 20. Either, we can find a way to consider table reuse; or simply use the x and y parameters to transmit coordinates.

Similarly, you must pay attention to defining a function in the way of function foo (...). Such an indefinite parameter is defined every time a table is called.

These temporary constructed objects are often recycled only when gc is used. Frequent gc is sometimes the efficiency bottleneck.

Use closure to replace the encapsulation coordinate mentioned above. We can use {x = 1, y = 2} to encapsulate a coordinate. However, there is another method to choose from. It is a little lightweight.

 
 
  1. function point (x,y)returnfunction()return x,y end  
  2. end 

Example

 
 
  1. P = point (1, 2) print (p () -- output 1 2

If you want:

 
 
  1. function point (x,y)returnfunction(idx)if idx=="x"thenreturn x  
  2.   elseif idx=="y"thenreturn y  
  3.   elsereturn x,y endend  
  4. end 

Example

 
 
  1. p=point(1,2)print(p("x"))-- 1print(p("y"))-- 2  

X and y are actually stored in closure, and each call to function point has an independent closure. Of course, there is only one function code.

Trying to reduce the speed of passing string constants from C to Lua within Lua VM, but when a String constant from C to lua vm is passed to the VM through APIS such as lua_pushstring, you need to refresh it. This includes at least one re-hash and matching process. An article on my Blog discussed this issue.

In lua, the inheritance of lua implements OO. Virtual tables usually set a retriable and _ index, while inheritance concatenates virtual tables with the _ index of the retriable. When there are too many class inheritance layers and the efficiency is relatively low, you can use the following technique.

 
 
  1. function inherit(sub,super)setmetatable(sub,  
  2.      { __index=function(t,k)local ret=super[k]  
  3.              sub[k]=ret  
  4.              return ret  
  5.      end})end 

In lua programming based on the short-circuit effect of logical operations, and or and C have short-circuit effects, but their return values are not bool type, but the left or right values in expressions. We often use this feature to simplify code.

 
 
  1. function foo(arg)  
  2.      argarg=arg or"default"  
  3.      ...  
  4. end 

Using or to assign default values is the most common technique. In the preceding example, if arg is nil, arg is assigned "default ". However, this technique has a flaw. It may be a problem when the default value is true.

A = a ortrue -- incorrect syntax. When a explicitly writes false, it is also changed to true.
A = ~ = False -- the correct method. When expression a is nil, it is assigned true, while false does not.

In addition, the clever use of and or can also implement? : Three-element operation:

 
 
  1. functionmax(a,b)return a>b and a or b  
  2. end 

The above function can return a larger one in a and B. Its logic is similar to return (a> B) in C )? A: B;

Summary:LuaThe programming skills learning tutorial is complete. I hope this article will help you!

Related Article

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.