AndLua+ English
180 subscribers
6 photos
9 links
➡️Only English💐
AndLua+ Tutorial
AndLua+ Function
AndLua+ Source codes
AndLua+ Videos
AndLua+ App's
keep_support
Download Telegram
Title :- Lua error handling
The program is running, the error processing is necessary, in our for File Operation, data transfer and web service call process will occur unexpected error. If you do not focus on the error information of the treatment, it will according to the leaked information, the program is not running, etc.
Any program language, need error handling. The error types are:
1, syntax error
2, the run-time error
Title :- Syntex error
A syntax error is usually due to the program components such as operators, expressions improper use caused. A simple example is as follows:
-- test. lua file
a == 2
The above code is executed the result is:

lua: test. lua:2: syntax error near '=='

As you can see, the above appears a syntax error, An "=" sign with two "=" sign there is a difference. A "=" is an assignment expression two "=" is a comparison operation.
Another example:

for a= 1,10
print(a)
end

The implementation of the above program will appear the following error:

lua: test2. lua:2: 'do' expected near 'print'

Grammatical errors than the program run error is more simple, run the error Unable to locate the specific errors, and syntax errors we can quickly resolve, such as the above examples as long as we in the for statement Add do to:

for a= 1,10
do
print(a)
end
Title :- Run time error
Run the error is the program can be executed normally, but will output the error message. The following example due to parameter input error, the program execution times wrong:

function add(a,b)
return a+b
end

add(10)

When we compile and run the following code, the compile is successful, but at run time will produce the following error:

lua: test2. lua:2: attempt to perform arithmetic on local 'b' (a nil value)
stack traceback:
test2. lua:2: in function 'add'
test2. lua:5: in main chunk
[C]: ?

The following error message is because the program is missing b parameter caused.
Title :- Error Handling
We can use two functions: assert and error to handle the error. Examples are as follows:

local function add(a,b)
assert(type(a) == "number", "a is not a number")
assert(type(b) == "number", "b is not a number")
return a+b
end
add(10)

The implementation of the above program will appear the following error:

lua: test. lua:3: b is not a number
stack traceback:
[C]: in function 'assert'
test. lua:3: in local 'add'
test. lua:6: in main chunk
[C]: in ?

Example assert first check the first argument, if no problem, assert do nothing; otherwise, the assert in the second argument as the error message thrown.
Title :- The error function
Syntax format:

error (message [, level])

Function: terminate is executing a function, and returns the message content as an error information(error function will never return)
Typically, the error will be some additional error location information to the message header.
The Level parameter indicates to obtain the location of the error:
Level=1[default]: to call the error location(file+line number)
Level=2: indicates to which call the error function
Level=0:do not add error location information
Title :- pcall and xpcall and debug
Lua error handling, you can use the function pcall(protected call to package require execution of the code.
pcall receives a function and to pass one of the latter parameters, and execution, implementation of the results: there is an error, no error; returns a value of true or or false, errorinfo。
The syntax format is as follows

if pcall(function_name, ....) then
-- No error
else
- Some error
end

Simple example:

> =pcall(function(i) print(i) end, 33)
33
true

> =pcall(function(i) print(i) error('error..') end, 33)
33
false stdin:1: error..
> function f() return false,2 end
> if f() then print '1' else print '0' end
0

pcall in a"protected mode"to call the first argument, so pcall can capture the execution of the function of any errors.
Usually when an error occurs, the want to end up with more debug information, instead of just generating the wrong location. But pcall returns, it has been destroyed call the Zhan part of the content.
Lua provides the xpcall function xpcall receiving a second parameter-an error handling function when an error occurs, Lua will call the Zhan exhibition see unwind before calling Error handling function, so you can in this function to use the debug library to obtain information about the error and additional information.
the debug library provides two General-purpose error-handling function:

debug. debug: provide a Lua prompt that lets the user to price error causes
debug. traceback: according to the call Zhan to build an extension to the error message

>=xpcall(function(i) print(i) error('error..') end, function() print(debug. traceback()) end, 33) 33 stack traceback: stdin:1: in function [C]: in function 'error' stdin:1: in function [C]: in function 'xpcall' stdin:1: in main chunk [C]: in ? false nil

xpcall the use of Example 2:

function myfunction ()
n = n/nil
end

function myerrorhandler( err )
print( "ERROR:", err )
end

status = xpcall( myfunction, myerrorhandler )
print( status)

The implementation of the above program will appear the following error:

ERROR: test2. lua:2: attempt to perform arithmetic on global 'n' (a nil value)
false
Title :- Lua debugging (Debug)
Lua provides a debug library is used to create our custom variable speed controller function. Lua itself does not have built-in speed controller, but a lot of developers share their Lua the Governor code.
Lua debug library contains the following function:

sethook ([thread,] hook, mask [, count]):

1. debug():
Enter a user-interactive mode, run the user input of each string. Using simple commands and other debug settings, the user can inspect global and local variables, change the values of variables, calculate expressions, and so on.
Enter a line containing only the cont of the string will be the end of this function, so the caller can continue down the run.

2. getfenv(object):
Returns the object's environment variables.

3. gethook(optional thread):
The return of the Three Represents the thread hooks set of values: the current hook function, the current hook mask, and the current hook count

4. getinfo ([thread,] f [, what]):
Return information about a function table information. You can directly provide this function, you can also use a digital f represents the function. Digital f that runs in the specified thread's call stack corresponding to the level of function: layer 0 represents the current function getinfo itself; the Layer-1 represents the call the getinfo function, unless it is a tail call, this case is not counted against the stack; and so on. If f is a ratio of the activity a function of the number of large numbers, getinfo returns nil.

5. debug. getlocal ([thread,] f, local):
This function returns the stack of the f layer at the function of the index of local the local variable's name and value. This function is used not only for access to explicitly-defined local variables, including formal parameters, temporary variables, etc.

6. getmetatable(value):
The given index points to the value of the metadata table is pushed onto the stack. If the index is invalid, or this value is not the meta table, the function will return 0 and not to stack the pressure on anything.

7. getregistry():
Returns the registry table, which is a predefined out of the table, can be used to save any C code you want to save Lua values.

8. getupvalue (f, up)
This function returns a function f of the first up on the value name and value. If the function does not have that value, return nil.
With a ' ('open parentheses hit the head of the variable name represents no names of variables, removing debug information of the code blocks.

10. Will a function as the hook function is set into. The string mask and the number count determines the hook when called. The mask is composed of the following combination of characters into a string, each character has its meaning:
'c': whenever Lua calls a function, call the hook;
'r': whenever Lua from a function returns, call the hook;
'l': whenever Lua enters a new line, call the hook.

11. setlocal ([thread,] level, local, value):
This function will be the value assigned to the stack of the first level layer function of the local a local variable. Without that variable, the function returns nil. If the level is out of bounds, throws an error.

12. setmetatable (value, table):
The value of the meta table is set to table may be nil in. Return value.

13. setupvalue (f, up, value):
This function will be the value set for the function f of the up on values. If the function does not have that value, and returns nil otherwise returns the value of the name.

14. traceback ([thread,] [message [, level]]):
If the message is there, and not a string or nil, the function does not do any processing directly returns the message. Otherwise, it returns the call stack of the stack of backtracking information. String optional message to be added in the stack backtrace at the beginning. Digital options level specified from the stack which layer to start the traceback, the default is 1, i.e., the call traceback of where it.

The table above lists our commonly-used debugging functions, then we can look at some simple examples:

function myfunction ()
print(debug. traceback("Stack trace"
))
print(debug. getinfo(1))
print("Stack trace end")
return 10
end
myfunction ()
print(debug. getinfo(1))

Execute the code above the output result is:

Stack trace
stack traceback:
test2. lua:2: in function 'myfunction'
test2. lua:8: in main chunk
[C]: ?
table: 0054C6C8
Stack trace end

In the example, we used to debug the library's traceback and the getinfo function getinfo function is used to return the function information table.
Title :- The Debug function is another example
We often need to debug the function within the local variable. We can use getupvalue function to set these local variables. Examples are as follows:

function newCounter ()
local n = 0
local k = 0
return function ()
k = n
n = n + 1
return n
end
end

counter = newCounter ()
print(counter())
print(counter())

local i = 1

repeat
name, val = debug. getupvalue(counter, i)
if name then
print ("index", i, name, "=", val)
if(name == "n") then
debug. setupvalue (counter,2,10)
end
i = i + 1
end -- if
until not name

print(counter())

Execute the code above the output result is:

1
2
index 1 k = 1
index 2 n = 2
11

In the above example, the counter in each call will increment by 1. Example we use getupvalue function to view local variables in the current state. We can set a local variable to a new value. Example, in the set before the value of n is 2,Use setupvalue function which is set to 10. Now we call the function, after execution output is 11 instead of 3.
Title :- The Debug type
1, the command line debug
2, a graphical debug

The command-line debugger are: RemDebug, the clidebugger, a ctrace, the xdbLua, the LuaInterface - Debugger, the Rldb, the ModDebug it.
Graphical interface of the debugger are: SciTE, the Decoda, the ZeroBrane Studio, akdebugger, the luaedit is.
Title :- Lua garbage collection
Lua uses automatic memory management. This means that you don't have to worry about the newly created object requires memory allocation out, also do not consider the object is no longer being used after how to release the memory occupied.
Lua runs a garbage collector to collect all dead objects, i.e., in Lua it is not possible then access to the object to complete the automatic memory management of the work. Lua all to memory, such as: string, table, user data, functions, threads, internal structures, etc., are subject to automatic management.
Lua implements an incremental mark-sweep collector. It uses two numbers to control the garbage collection cycle: garbage collector an intermittent rate and the garbage collector the stepper magnification. The two figures use the percentage of units for example: the value 100 in the inner portion represents 1 km.
The garbage collector intermittent rate control of the Collector need to open a new cycle to wait before long. Increasing this value will reduce the Collector's enthusiasm. When this value is smaller than 100 is small, the collector turned on a new cycle before won't have to wait. Set this value to 200 will allow the collector to wait until the total memory usage reached before twice before starting a new cycle.
The garbage collector stepper magnification control of the Collector operation speed with respect to memory allocation speed of the magnification. Increasing this value will not only make the Collector more positive, will also increase with each incremental step length. Do not set this value to be less than 100, as if the collector is working too slow that never dry after one cycle. The default value is 200, this indicates that the collector is less than memory allocated"twice"the speed of work.
If you put the stepper magnification is set to a very large number than your program may be used to the number of Bytes is greater 10%, The Collector behaves like a stop-the-world Collector. Then you if the intermittent rate is set to 200, the collector of the behavior and the last Lua version of the same: every time Lua memory use doubles when doing a full collection.
Title :- The garbage collector function
Lua provides the following function collectgarbage ([opt [, arg]])is used to control the automatic memory management:

1, the collectgarbage("collect"): do a full garbage collection cycle. By the parameter opt-it provides a set of different functions:
2, the collectgarbage("count"): K number of bytes returned to Lua using the total memory number. This value has a fractional part, it is only necessary to multiply on 1024 you can get the Lua to use the exact number of bytes, unless the overflow is.
3, the collectgarbage("restart"): restarts the garbage collector to run automatically.
4, the collectgarbage("setpause"): the arg is set to the collector of the intermittent rate, see §2.5 in. Returns the intermittent rate of the previous value.
5, the collectgarbage("setstepmul"): returns the stepper magnification of the previous value.
6, the collectgarbage("step"): a single-step run the garbage collector. Step size"size"by the arg control. Incoming 0, The Collector step into an integral a step. Incoming non-0 value, the Collector collects the equivalent of the Lua distribution of these multi-K-Byte memory work. If the Collector end of a cycle will return true.
7, the collectgarbage("stop"): stops the garbage collector runs. In calls before restarting the collector will only be because of an explicit call to run.

The following demonstrates a simple garbage collection example:

mytable = {"apple", "orange", "banana"}

print(collectgarbage("count"))

mytable = nil

print(collectgarbage("count"))

print(collectgarbage("collect"))

print(collectgarbage("count"))

The implementation of the above program, the output results are as follows(note that the memory usage changes): the

20.9560546875
20.9853515625
0
19.4111328125
Title :- Lua object oriented
Object Oriented Programming Object Oriented Programming, OOP, is a very popular computer programming architecture.
Several programming languages support Object-Oriented Programming:

C++
Java
Objective-C
Smalltalk
C#
Ruby
AndLua+ English pinned Deleted message
Title :- Lua inheritance
Inheritance refers to an object directly using another object's properties and methods. Can be used to extend the base class properties and methods.
The following shows a simple inheritance example:

-- Meta class
Shape = {area = 0}
-- Base class method new
function Shape:new (o,side)
o = o or {}
setmetatable(o, self)
self.__ index = self
side = side or 0
self. area = side*side;
return o
end
-- Base class method printArea
function Shape:printArea ()
print("area is ",self. area)
end

The next example, the Square object has inherited The Shape class:

Square = Shape:new()
-- Derived class method new
function Square:new (o,side)
o = o or Shape:new(o,side)
setmetatable(o, self)
self.__ index = self
return o
end

A complete example
The following example, we inherited a simple class to extend a derived class method, the derived class retains the inherited class member variables and methods:

-- Meta class
Shape = {area = 0}
-- Base class method new
function Shape:new (o,side)
o = o or {}
setmetatable(o, self)
self.__ index = self
side = side or 0
self. area = side*side;
return o
end
-- Base class method printArea
function Shape:printArea ()
print("area is ",self. area)
end

-- Create the object
myshape = Shape:new(nil,10)
myshape:printArea()

Square = Shape:new()
-- The derived class method new
function Square:new (o,side)
o = o or Shape:new(o,side)
setmetatable(o, self)
self.__ index = self
return o
end

-- The derived class method printArea
function Square:printArea ()
print("Square area is ",self. area)
end

-- Create the object
mysquare = Square:new(nil,10)
mysquare:printArea()

Rectangle = Shape:new()
-- The derived class method new
function Rectangle:new (o,length,breadth)
o = o or Shape:new(o)
setmetatable(o, self)
self.__ index = self
self. area = length * breadth
return o
end

-- The derived class method printArea
function Rectangle:printArea ()
print("rectangle area is ",self. area)
end

-- Create the object
myrectangle = Rectangle:new(nil,10,20)
myrectangle:printArea()

The implementation of the above code, the output result is:

Area of 100
A square area of 100
A rectangular area of 200
Title :- Function Rewrite
Lua we can override the base class function in a derived class to define your own implementation:

-- The derived class method printArea
function Square:printArea ()
print("Square area ",the self. area)
end
Title :- print
print"Hello World!"
print("Hello World")
Title :- comment
Single-line comments --
Multi-line comment --[[]]
Title :- string
a="String"
a=[[String]]
a=[===[the String]===]
Title :- assignment
a="Hello World"

--lua supports multiple assignment
a,b="String a","String b"

--Exchange value
a,b="String a","String b"
a,b=b,a