Lua General Rules

Source: Internet
Author: User

Lua official English document: http://www.lua.org/manual/5.2/

Lua China developer Website: http://bbs.luaer.cn/

 

[Turn] Lua programming skills Lua version 5.1 has been officially released. Now we should put all the discussions on this version.

Use local variables instead of global variables whenever possible. This is the easiest mistake for Lua beginners. The global variable is actually placed in a global table. The global variable uses a string (the variable name is the key) to access the 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:
for k1,v1 in pairs(tbl) do    for k2,v2 in pairs(v1) do        ...        endend

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

do local pairs=pairs    for k1,v1 in pairs(tbl) do         for k2,v2 in pairs(v1)do            ...            end    endend    

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.


Alert for temporary variablesA new object is generated by concatenating strings. This is caused by Lua's own string management mechanism. Lua always retains only one copy of the same string in the VM, so that all strings can be simplified to address comparison. This is one of the reasons for Lua's fast 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.

Replace table with closureThe encapsulation coordinate problem is 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.
Function Point (x, y) return function () return X, Y endend -- use example P = point (1, 2) print (P () -- output 1 2

If you want:

Function Point (x, y) return function (idx) If idx = "X" then return x elseif idx = "Y" then return y else return X, Y end endend -- use example P = point (1, 2) print (P ("X") -- 1 print (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.


Try to reduce the number of strings passed from C to LuaString constants work very quickly inside Lua Vm, but when a string is transferred from C to Lua VM through APIS such as lua_pushstring to VM, You need to refresh it. This includes at least one re-hash and matching process. An article on my blog discussed this issue.

Inheritance in LuaIn Lua, oo is implemented. A virtual table usually sets a retriable and _ index. In inheritance, the _ index of the virtual table is serialized. When there are too many class inheritance layers and the efficiency is relatively low, you can use the following technique.
function inherit(sub,super)    setmetatable(sub,     { __index=function(t,k)            local ret=super[k]             sub[k]=ret             return ret     end})end
Use the short-circuit effect of logical operationsIn Lua programming, and or has a short-circuit effect like C, but their return values are not bool type, but the left or right values in the expression. We often use this feature to simplify code.
function foo(arg)     arg=arg or"default"     ...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:

function max(a,b)    return a>b and a or bend

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

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.