Lua Programming in 8 Hours - For Beginners - Learn Coding Fast
Lua Programming in 8 Hours - For Beginners - Learn Coding Fast
In 8 Hours
For Beginners
Learn Coding Fast
Ray Yao
Copyright © 2015 by Ray Yao
All Rights Reserved
Neither part of this book nor whole of this book may be reproduced or
transmitted in any form or by any means electronic, photographic or
mechanical, including photocopying, recording, or by any information
storage or retrieval system, without prior written permission from the
author. All rights reserved!
Ray Yao
Note:
This book is only for Lua beginners, it is not suitable for experienced Lua
programmers.
Hour 1
What is Lua Language?
Install Lua
“Hello World” Script
Lua Comment
Identifier
Lua Reserved Keywords
Data Type
Check Data Type
Variable
Nil
Global & Local
Hour 2
String
Escape Character
String Length & Reverse
String Format
#string, find() & sub()
Connect & Repeat
Conversion & Replace
Character & ASII
Arithmetical Operators
Comparison Operators
Logical Operators
Hour 3
Precedence of Operators
While Loop
For Loop
For … In ipairs()
Repeat---Until()
Break Statement
Go To Statement
Nested Loop
If Statement
Hour 4
If-else Statement
Function
Function with Arguments
Return
Uncertain Parameters
Function Stored in Variable
Anonymous Function
How Many Parameters?
Array
Access Array Elements
Table
Iterate Over Table
Hour 5
Connect Table Elements
Insert Element
Remove & Sort
Table Length
Module
Garbage Collection
MetaTable
_ _index Method
_ _call Method
Hour 6
_ _newindex Method
_ _tostring Method
Other Meta_Methods
File I/O
Write a File
Read a File
Append a File
Read() Parameters
Process Multiple Files
Locate a String
Hour 7
Class
Object
Constructor
Inheritance
Overriding
Coroutine
Hour 8
coroutine . wrap()
Error
Error Processing (1)
Error Processing (2)
pcall()
xpcall()
Debug
03.
Click the Installer, start installation of Lua.
04 .
After complete the installation, Please test whether the Lua installation was
successful.
Double click the Lua icon on the computer desktop, open the Lua
command-line editor.
05.
In the Lua editor, Please input the following code, and press Enter key.
print("Hello World! ")
06.
Output:
Hello World!
02.
In the SciTE , click File > New , input the following code:
print("Hello World! ")
03.
Save the file as “Hello.lua ”. (The extension name of Lua is “.lua ”), and
click the “Run Program” icon to run the scripting file.
Output: Hello World!
Explanation:
“print()” is a Lua command to output the contents.
Lua Comment
Note:
Names that begin with an underscore and followed by a series of uppercase
letters, such as _COMPUTER, are reserved for Lua internal global
variables.
Data Type
There are eight data types in Lua: Nil, Boolean, Number, String, Userdata,
Function, Thread, and table.
When a variable is defined, its type does not need to be defined. Variable
only need to be assigned a value.
Example 2.5
str1 = "Swift "
str2 = "in 8 Hours "
print(str1..str2 )
print(string.rep(str1, 3) )
Output:
Swift in 8 Hours
Swift Swift Swift
Explanation:
“str1.. str2” connects the str1 and str2.
“rep(str)” repeats the str three times.
Conversion & Replace
Operators Running
+ add
- subtract
* multiply
/ divide
% get remainder
^ power
- change sign
Example 2.8
a , b = 10 , 2
c=a/b
print("a / b =", c ) -- output : a / b = 5 . 0
c=a%b
print("a % b =", c ) -- output : a % b = 0
c=a^2
print("a ^ b =", c ) -- output : a ^ b = 100 . 0
c = -a
print("- a =", c ) -- output : -a = -10
Comparison Operators
Example 2.9
a, b = 20, 10
print(" a == b ",a == b) -- output : a == b false
print(" a > b ",a > b) -- output : a > b true
print(" a < b ",a < b) -- output : a < b false
print(" a >= b ", a >= b) -- output : a >= b true
print(" a <= b ", a <= b) -- output : a <= b false
print(" a ~= b ", a ~= b) -- output : a ~= b true
Logical Operators
X, Y = false, false
print("X and Y", X and Y) -- output : X and Y false
print("X or Y", X or Y) -- output : X or Y false
print("not X", not X) -- output : not X true
print("not Y", not Y) -- output : not Y true
Hour 3
Precedence of Operators
From high to low:
^
not - (unary)
* / %
+ -
..
< > <= >= ~= ==
and
or
Example 3.1
a , b, c, d = 8, 6, 4, 2
result1 = (a + b) * c / d;
print("(a + b) * c / d returns: ", result1 ) -- output : 28 . 0
result2 = a + b * c / d;
print("a + b * c / d returns: ", result2 ) -- output : 20 . 0
While Loop
The while loop statement repeatedly executes the loop body when the
condition is true. The syntax is:
while(condition)
do
loop body
end
Example 3.2
num = 1
while( num <= 8 ) -- run 8 times
do
print(num)
num = num + 1
end
Output: 12345678
Explanation:
“while( num <= 8 )” runs 8 times when the condition is true.
For Loop
The “for loop” statement can execute the loop body repeatedly. The
condition of repetitions can be specified beforehand.
The syntax is:
for number = startValue, lastValue, stepLength do
loop body
end
Example 3.3
for num = 0, 8, 2 do
-- “0” is the first value to print, “8” is the last value to print
print(num)
end
Output:
02468
Explanation:
“num = 0” is the first value. “num = 8” is the last value.
“2” is the step length.
For … In ipairs()
“for … in ipairs()” is used to iterate over all elements in a table.
The syntax is:
myTable = { …… }
for index,value in ipairs ( myTable ) do
loop body
end
Example 3.4
myTable = {"A","B","C","D","E"} -- define a table
for index,value in ipairs ( myTable ) do
print(value) -- set up the table index and value
end
Output:
A B C D E
Explanation:
“for index,value in ipairs (myTable)” specifies the index, value, and the
table elements to iterate over.
Repeat---Until()
“Repeat---Until()” repeatedly runs the loop body, until the condition is true,
then stops running. The syntax is:
repeat
loop body
until( condition )
Example 3.5
num = 1
repeat
print(num)
num = num + 1
until( num > 8 ) -- run 8 times
Output:
1 2 3 4 5 6 7 8
Explanation:
“repeat…until(num>8)” repeatedly runs the loop body until the condint
(num>8) is true, then stops running.
Break Statement
“break” command works inside the loop. It is used to stop the running of a
loop according to the condition.
break;
Example 3.6
num=0;
while (num<10) do
if (num==5) then break end -- exit the while loop
num=num+1
end
print( num );
Output:
5
Explanation:
“if (num==5) then break end” is a condition statement, it means if the num
is equal to 5, then runs the “break” command, exits the while loop body.
Go To Statement
The “go to” statement moves the control flow unconditionally to the label
statement.
goto label -- go to run the statement with a :: label ::
:: label:: -- is the label which the “goto lable” goes to .
Example 3.7
num = 1
::label:: print("Go in 8 Hours")
num = num + 1
if num < 2 then
goto label -- go to run the statement with :: label ::
end
Output:
Go in 8 Hours
Explanation
“ :: Label :: ” is the label which the “goto lable” goes to.
“goto label” goes to run the statement with :: label:: .
Nested Loop
In Lua, the while nested loop syntax is:
while(condition)
do
while(condition) -- nested loop
do
statements
end
statements
end
Example 3.8
x=1
repeat
print("The value of x is: ",x)
x=x+1
y=1
repeat -- nested loop
print("The value of y is:",y)
y=y+1
until( y > 3 )
until( x > 5 )
Output:
The value of x is : 1
The value of y is : 1
The value of y is : 2
The value of y is : 3
The value of x is : 2
The value of y is : 1
The value of y is : 2
The value of y is : 3
The value of x is : 3
The value of y is : 1
The value of y is : 2
The value of y is : 3
The value of x is : 4
The value of y is : 1
The value of y is : 2
The value of y is : 3
The value of x is : 5
The value of y is : 1
The value of y is : 2
The value of y is : 3
Explanation:
“x” variable runs in the outer “repeat…until” loop.
“y” variable runs in the inner “repeat…until” loop.
If Statement
“if statement” executes codes inside “then…end” only if a specified
condition is true. The syntax is:
if(condition)
then
-- run this if the condition returns true
end
Example 3.9
num = 10;
if( num > 5 )
then
print("num is greater than 5" );
end
Output:
num is greater than 5
Explanation:
“if( num > 5 ) ” checks if the num is greater than 5, if true, runs the code
inside the “then…end”.
There two values in Boolean type: true or false .
In Lua, “nil” is equivalent to false, “0” is equivalent to true.
Example 3.10
if nil then -- check nil whether it is true
print("The nil is true")
else
print("The nil is false")
end
if 0 then -- check 0 whether it is true
print("The 0 is true")
else
print("The 0 is false")
end
Output:
The nil is false
The 0 is true
Explanation:
In Lua, “nil” is equivalent to false, “0” is equivalent to true.
Hour 4
If-else Statement
“if... else statement” runs some code if a condition is true and runs another
code if the condition is false
if ( condition) then -- if true do this
else -- if false do this end
Example 4.1
num = 10;
if( num < 5 )
then
print("num is less than 5" )
else
print("num is greater than 5" )
end
Output:
num is greater than 5
Explanation:
if( num < 5 ) ” checks if the num is less than 5, if true, runs the code inside
the “then…”. Otherwise, runs the code inside the “else…”
Function
A function is a code block that can repeat to run many times.
The syntax to define a function is:
function functionName()….. end
Example 4.2
function myFunc() -- define a function
print("Hello, My Friends! ")
end
myFunc() -- call the function
Output:
Hello, My Friends!
Explanation:
“function myFunc()” defines a function.
“myFunc()” calls the function
Function with Arguments
A function can have one or more arguments inside the bracket. Arguments
are used to pass data to function. The syntax is:
function functionName ( args ) ……end
Example 4.4
function add( num1, num2 )
return num1 + num2; -- pass the result value to the caller
end
print("3 + 5 = ",add( 3, 5 )); -- caller
Output:
3+5= 8
Explanation:
“return num1+num2” returns the result to caller “add(3,5)”, you can treat it
as “add(3,5) = return num1+num2”, assigning the value to add(3,5).
Namely add (3,5) =8.
Uncertain Parameters
The Lua function can receive an uncertain number of arguments, by using
three points (... ) to declare.
function funcName( ... ) …… end
Example 4.5
Output:
15
Explanation:
“function add( ... )” defines a function with uncertain number parameters,
three points (… ) indicate the number of the parameter is uncertain.
Function Stored in Variable
In Lua, a function can be stored in a variable.
variable = function
Example 4.6
function myFunc(num)
print(num + 10)
end
myFunc(1)
myVar = myFunc -- a function can be stored in a variable
print(myVar(2))
Output:
11
12
Explanation:
“myVar = myFunc” means that a function can be stored in a variable.
Anonymous Function
Anonymous function has no any name, but it can be a parameter of another
function.
Example 4.7
function myFunc(num,fun)
print(num)
print(fun());
end
myFunc(8, function() -- anonymous function
return 100;
end
);
Output:
8
100
Explanation
“function()…return 100… end ” is an anonymous function, which works
as a parameter of the myFunc().
How Many Parameters?
The syntax to check how many uncertain parameters is:
select("#",... )
Example 4.8
function add(... )
sum = 0
for index, value in ipairs{... } do
sum = sum + value
end
print("Total",select("#",...) ,"parameters passed")
return sum
end
add(1,2,3,4,5)
Output:
Total 5 parameters passed
Explanation:
“select("#",... )” checks how many parameters have been passed.
Array
Array is a special variable that can contain multiple values.
The syntax to define an array is:
array = { value1, value2, value3,… }
The syntax to access an array is:
array[index]
Example 4.9
array = {"A", "B", "C"} -- define an array
print(array[1]) -- access array
print(array[2])
print(array[3])
Output:
A B C
Explanation:
Above code creates an array, it has three elements: array [1], array [2],
array[3]. Its indexes are 1, 2, 3. Their values are A, B, and C. Note: the
index of Lua array begins from 1.
Access Array Elements
We can access an array with a lot of elements by using “for loop” statement.
The syntax is:
for index = firstIndex, lastIndex do….. end
Example 4.10
array = {"A", "B", "C", "D", "E"}
for index = 1, 5 do
print(array[ index ])
end
Output:
A B C D E
Explanation
“for index = 1, 5 do….. end” accesses all elements in the array from index
1 to index 5.
Note: the index of Lua array begins from 1.
Table
A table is an associative array, the difference between table and array is:
The table’s index can be any data type.
The array’s index only is a number type.
Example 4.11
t = { } -- create an empty table
t["A"] = 10 -- the index of the table is a string type
t["B"] = 20
t["C"] = 30
t["D"] = 40
print(t["A"], t["B"], t["C"], t["D"])
Output:
10 20 30 40
Explanation:
“t = { } ” creates an empty table.
“t["A"] = 10” assigns a value 10 to the element of index “A”.
Iterate Over Table
The syntax to iterate over the table is:
for index, value in pairs(myTable) do…end
Example 4.12
myTable = {"A", "B", "C", "D","E"}
for index, value in pairs(myTable) do -- iterating
print("Index is: ",index, "Value is: ",value)
end
Output:
Index is: 1 Value is: A
Index is: 2 Value is: B
Index is: 3 Value is: C
Index is: 4 Value is: D
Index is: 5 Value is: E
Explanation:
“for index, value in pairs(myTable) do…end” iterates through all elements
of the myTble.
Note: the index of Lua table begins from 1.
Hour 5
Connect Table Elements
The syntax to connect the elements of a table is:
table. concat(tableName, “separator”, startIndex, endIndex)
“separator” means the symbols @, #, $, *, &…
“startIndex, endIndex” connects the elements from startIndex to endIndex.
Example 5.1
book = {" Go "," in "," 8 "," Hours "}
print(table.concat (book)) -- connect all elements
print(table.concat (book," - ")) -- using separator “-”
print(table.concat (book," * ", 3,4)) -- connect from index 3 to 4
Output:
Go in 8 Hours
Go - in - 8 - Hours
8 * Hours
Explanation:
“table. concat(book)” connects each element of the table “book”.
Insert Element
The syntax to insert element to the table is:
table. insert(tableName, index, “newElement”)
“index” is the location to insert the element.
“newElement” is the element to insert.
Example 5.2
book = {" XML "," in "," 8 "," Hours "}
table.insert(book, 2, "JSON") -- insert new element
for index = 1, 5 do -- iterate over table from index 1 to 5
print(book[ index ])
end
Output:
XML JSON in 8 Hours
Explanation:
“table. insert(book, 2, "JSON")” inserts an element “JSON” to the index 2
of the table “book”.
Remove & Sort
The syntax to remove a specified element and sort all elements in the table
is as follows:
table.remove (tableName, index)
table. sort(tableName)
“index” specifies that an element at this index will be removed.
Example 5.3
book = {" D"," B "," E "," F ", " A ", " C "}
table.remove (book, 4) -- remove the element “F”
table.sort (book) -- sort the elements of the table
for index = 1, 5 do
print(book[ index ])
end
Output: A B C D E
Explanation:
“table.remove (book, 4)” removes the element “F” at the index 4.
“table.sort (book)” sorts all elements of the table “book” after removing the
element “F”.
Table Length
The symbol “#” can get the length of a table.
The syntax to get the length of a table is:
#
table
Example 5.4
tab = {"A", "B", "C"}
tab[4] = "D" -- append an element
tab[5] = "E" -- append an element
print("The length of the table is: ", # tab ) -- get table length
Output:
The length of the table is: 5
Explanation:
“# tab” can get the length of the table.
Module
A module is a file that is specifically referenced by other files, and can be
used repeatedly by multiple files. A module is actually a table containing
some variables, constants, functions.
1. The syntax to define a module is as follows:
module = {} -- define a module
module. variable = value -- define a variable
function module. func() -- define a function
end
return module -- return to the file that requires the module
The module can be saved as “myModule.lua ”, so that other file can import
it.
2. The syntax to import a module is as follows:
require("myModule ") -- import the module file
module. variable -- use the variable of the module
module. func() -- use the function of the module
Save the file as “another.lua ”, which requires the “myModule”.
The module file and another file should be in the same folder.
Example 5.5
For example:
setmetatable(mytable, mymetatable)
-- set a metatable of mytable
getmetatable(mytable)
-- get a metatable of mytable
Note:
If the metatable key value exists in the metatable previously,
setmetatable({},{}) will fail.
getmetatable (object) returns the metatable of an object.
_ _index Method
When accessing an index that is not existing in a table, __index method will
be triggered. __index method will handle the error.
Note: “__” is two underlines.
Example 5.7
tab = {
book1="Java"
}
print(tab[book2] ) -- the index book2 does not exist .
Output: nil
Explanation:
This example has not used __index method yet.
“tab[book2]” accesses an index that doesn't exist in the table “tab”, so the
output is nil.
When an index that does not exist in the table is accessed, the interpreter
looks up the __index method.
The code in the __index method is usually written by the programmer.
Example 5.8
tab = {
book1 = "Java"
}
mtab = { -- define a metatable
__index = function() -- define a __index method
print("No such an index! ")
end
}
setmetatable(tab, mtab) -- set a metatable of “tab”
print(tab[book2] ) -- trigger the __index method
Output:
No such an index!
nil
Explanation:
“tab[book2]” accesses an index that doesn't exist in the table “tab”, so it
triggers the __index method. __index method has handled the error.
“setmetatable(tab, mtab)” sets a metatable “mtab” of the “tab”.
_ _call Method
When calling a method that does not exist in the table, __call method will
be triggered, __call method will handle the issue.
Example 5.9
tab = {}
mtab = { -- define a metatable
__call = function( tab, a, b, c) -- define a __call method
return a + b + c
end
}
setmetatable(tab, mtab) -- set a metatable of “tab”
print( tab(1, 2, 3) ) -- try to access tab
Output:
6
Explanation:
“tab(1, 2, 3)” try to access the table “tab”, but “tab” has no any elements,
so it triggers the __call method. __call method has handled the issue.
Hour 6
_ _newindex Method
When assigning a value to an index that is not existing in a table,
__newindex method will be triggered. __newindex method will handle the
error.
Example 6.1
tab = {
book1="Java"
}
tab[book2]="Perl" -- assign a value to an inexistent index
print(tab[book2])
Output: Error message!
Explanation:
This example has not used __newindex method yet.
“tab[book2]=’Perl’” assigns a value to an index that is not existing in the
table, so the output is an error message.
When assigning a value to an index that is not existing in a table,
__newindex method will be triggered.
The __newindex method is usually written by the programmer.
Example 6.2
tab = {
book1 = "Java"
}
mtab = { -- define a metatable
__newindex = function() -- define a __newindex method
print("Assign a value to an inexistent index! ")
end
}
setmetatable(tab, mtab) -- set a metatable of “tab”
tab[book2]="Perl" -- assign a value to an inexistent index
print(tab[book2]) -- trigger the __newindex method
Output:
Assign a value to an inexistent index!
nil
Explanation:
“tab[book2]="Perl"” assigns a value to an inexistent index, so it triggers the
__newindex method. __newindex method has handled the error.
“setmetatable(tab, mtab)” sets a metatable “mtab” of the “tab”.
_ _tostring Method
If want to operate the contents of a table, or output contents in a string
format, we can use __tostring method.
Example 6.3
tab = { 1, 2, 3 }
mtab = { -- define a metatable
__tostring = function(tab) -- define a __tostring method
sum = tab[1] + tab[2] + tab[3]
return sum
end
}
setmetatable( tab, mtab ) -- set a metatable of “tab”
print( tab ) -- access the table “tab”
Output:
6
Explanation:
“__tostring = function(tab) ” defines a __tostring method, which can
calculate the value of the table.
“print( tab )” prints the result of the table.
Other Meta_Methods
In a metatable, we can call various meta_methods as follows:
Meta_Method Operations
__add +
__sub -
__mul *
__div /
__mod %
__unm -
__concat ..
__eq ==
__lt <
__le <=
__pow power
__len length
__metatable protect metatable
File I/O
The Lua I/O library is used to read and write files.
The syntax to open a file is:
file = io. open (filename , mode)
“Mode” is a parameter that specifies the purpose to open the file.
The open mode of the file is as follows:
Mode Purpose
r Open a file for reading contents only
w Open a file for writing contents only
a Open a file for appending contents
r+ Open a file for reading or writing contents
w+ Open a file for writing or reading contents
a+ Open a file for appending or reading contents
b Open a file for binary operation
For example:
file = io. open (myfile. txt , append)
-- open myfile . txt in appending contents mode .
Write a File
The syntax to write a file is:
io. output(file) -- set up the output file
io. write(" contents ") -- write the contents to the file
Example 6.4
file = io. open("myFile. txt", "w") -- open myFile . txt for writing
io.output(file) -- set up myFile . txt as an output file
io.write("Shell Scripting in 8 Hours\n") -- write contents
print("Write a file successfully! ")
io. close(file)
Output:
Write a file successfully!
Explanation:
Please check the file “myFile. txt”, we can find the text “Shell Scripting in
8 Hours ” has been written in the file.
“io. output(file)” sets up myFile. txt as an output file.
“io. write("Shell Scripting in 8 Hours\n")” writes these contents.
Read a File
The syntax to write a file is:
io. inputt(file) -- set up the input file
io. write(" contents ") -- read the contents of the file
Example 6.5
file = io. open("myFile. txt", "r") -- open myFile . txt for reading
io.input(file) -- set up myFile . txt as an input file
print(io.read()) -- read contents in the myFile . txt
io. close(file)
Output:
Shell Scripting in 8 Hours
Explanation:
“io. input(file)” sets up myFile. txt as an input file.
“print(io. read())” reads and print the contents in the myFile. txt.
Append a File
The syntax to append the contents to a file is:
io. output(file) -- set up the output file
io. write(" contents ") -- append the contents to the file
Example 6.6
file = io. open("myFile. txt", "a") -- open myFile . txt for appending
io.output(file) -- set up myFile . txt as an output file
io.write("Scala in 8 Hours\n") -- append contents
print("Append a file successfully! ")
io. close(file)
Output:
Append a file successfully!
Explanation:
Please check the file “myFile. txt”, we can find “Shell Scripting in 8
Hours, Scala in 8 Hours ” has been written in the file.
“io. output(file)” sets up myFile. txt as an output file.
“io. write("Scala in 8 Hours\n")” appends these contents.
Read() Parameters
The “io. read()”’s parameter specifies to read how much content from the
current position.
read all contents
"*a"
e. g. io. read("*a")
read the line
"*l"
e. g. io. read("*l")
read the specified number of characters.
number
e. g. io. read(10)
Example 6.7
file = io. open("myFile. txt", "r")
io. input(file)
print(io.read(15) ) -- read 15 characters in the myFile . txt
io. close(file)
Output: Shell Scripting
Explanation:
“io.read(15) ” only reads 15 characters in the myFile. txt.
Process Multiple Files
Usually we need to process multiple files at the same time.
In this case, we should use “file: functionName()” method instead of the
“io. functionName()” method.
file: functionName()
Example 6.8
file1 = io. open("study. txt", "w")
file1:write("Hello! ")
file1: close()
file2 = io. open("study. txt", "a")
file2:write("My Friends! ")
file2: close()
file3 = io. open("study. txt", "r")
print(file3:read())
file3: close()
Output:
Hello! My Friends!
Explanation:
“file: functionName()” format can process multiple files.
Locate a String
We can use seek() to locate a string in a file.
file. seek(“set/cur/end”, index)
"set": seek the string from the beginning location
"cur": seek the string from the current location
"end": seek the string from the end location
“index”: the index of a character in a string.
Example 6.9
Assume that the string in study. txt is “Hello! My Friends! ”
file = io. open("study. txt", "r")
file:seek("set",7)
print(file: read())
file: close()
file = io. open("study. txt", "r")
file:seek("end",-12)
print(file: read())
file: close()
Output:
My Friends !
My Friends!
Explanation:
Assume that the string in study. txt is “Hello! My Friends! ”
“file: seek("set",7)” seeks at the 7th character from the beginning of the
string. The result is “My Friends! ”
“file: seek("end",-12)” seeks at the -12th character from the end of the
string. The result is “My Friends! ”
“-12” indicates to seek the -12th character from right to left.
Hour 7
Class
Class is the general name for all things of the same nature.
The class describes common properties and methods of objects.
In Lua, usually the class, object, property and function can be described by
a “table” and “metatable”conception.
The syntax to create a class is:
ClassName = {
property1 = value1,
property2 = value2,
}
ClassName. __index = ClassName
In Lua, usually the class, object, property and function can be described by
a “table” and “metatable” conception.
Constructor
The constructor is used to initialize the property values of an object in the
class.
The syntax to define a constructor is:
function ClassName : constructor() -- define a constructor
obj = {} -- create a table of the object
setmetatable(obj, ClassName)
ClassName. property1 = value1 -- initialization
ClassName. property2 = value2 -- initialization
return obj
end
Output:
Hello, My Friends!
Explanation:
“Person. __index = Person” makes the Person’s __index point to itself (a
table), so that Person’s metatable can be used.
“Jen = {}” creates a table of Jen.
“setmetatable(Jen, Person)” sets a metatable of the Jen table, so that the Jen
can access the property and method of Person.
Example 7.2
Example 7.3
Person = {} -- create a class, namely create a table
Person. __index = Person -- __index points to Person
function Person: new() -- define a constructor
Jen = {} -- create a table of Jen
setmetatable(Jen, Person)
return Jen
end
function Person: say(greeting)
print(greeting)
end
Jen = Person. new() -- create an object
Jen: say("Hello, My Friends! ") -- the object accesses say()
Example 7.4
Person = {} -- create a class, namely create a table
Person. __index = Person
function Person: new()
Jen = {}
setmetatable(Jen, Person)
return Jen
end
function Person:say(greeting) -- the method in parent class
print(greeting)
end
Jen = Person. new()
Jen: say("Hello, My Friends! ")
coroutine.resume()
Restart coroutine
coroutine.yield()
Suspend coroutine
coroutine.status()
Check coroutine status
coroutine.wrap(function)
Create coroutine and return a function
coroutine.running()
Return a running coroutine
Explanation:
“coroutine.create(myFunc) ” creates a coroutine, returns a coroutine.
“coroutine.wrap(myFunc) ” creates a coroutine, returns a function.
“coroutine. resume(co, 10)” runs the “coroutine. create(myFunc)”
“coFunc(20)” runs the “coroutine. wrap(myFunc)”
Error
Unexpected errors always can occur during file operations, data transfers,
and web service calls. If we do not pay attention to the handling of errors, it
will cause information leakage, the program cannot run, etc.
In any programming language, error handling is required.
There are two types of error: 1. Syntax error. 2. Runtime error.
Example 8.2
num = = 100
Output:
syntax error near '=='
Explanation:
This is a syntax error.
“==” is used to compare two variable values.
“=” is used to assign a value to the variable.
Therefore “num = 100” is correct.
Example 8.3
num = 10
if ( num > 0 )
then
num = num / 0
print(num)
end
Output:
Error message: inf
Explanation:
This is a runtime error.
Although the program passes the compiling, but
“num = num / 0” will cause the error.
Therefore, we should try to avoid the zero divisor.
Error Processing (1)
assert( parameters ) can process the error.
assert( parameters )
If the “parameter” has no error, assert() does nothing.
If the “parameter” has some errors, assert() will show the error message.
Example 8.4
function test(x,y)
assert(type(x) == "string", "x is not a string")
assert (type(y) = = "string" , "y is not a string")
return x .. y
end
test("ok",10)
Output: y is not a string. (Error messages……)
Explanation:
type(y) = = "string" checks the data type. “y” is a number 10, not a string.
So the assert() will show the error message.
Error Processing (2)
error( message ) can process the error.
error( message )
If the code has some errors, error( message ) will show the error message.
Example 8.5
num =100
function myFunc ()
num = num/nil -- the divisor is nil, error occurs !
end
if pcall(myFunc) then -- check myFunc
print("No Error! ")
else
print("Error Occurs! ")
end
Output:
Error Occurs!
Explanation:
“num = num/nil ” cause an error in the function “myFunc”.
“pcall(myFunc) ” checks the function “myFunc” whether it has any error.
xpcall()
“xpcall()” is used to check a function whether it has any error, and shows
the error messages.
xpcall(function, callback)
“function” is the first parameter, also is a function in which some error may
occur.
“callback” is the second parameter, also is a callback function in which
some error message will be shown.
Example 8.7
function myFunc()
num = num / nil -- the divisor is nil, error occurs !
end
function callback( message )
print( "Error Occurs! ", message )
end
status = xpcall( myFunc, callback ) -- check myFunc
print( "Successful ? ", status)
Output:
Error Occurs! script. lua: 2: attempt to perform arithmetic on a nil
value (global 'num')
Successful ? false
Explanation:
“function myFunc()” is a function in which some errors may occur.
“function callback( message )” is a callback function that is used to output
the error message.
“xpcall( myFunc, callback ) ” has two function parameters:
“myFunc” is the first parameter, also is a function in which some error may
occur.
“callback” is the second parameter, also is a callback function in which
some error message will be shown.
Debug
Lua provides the debug library for creating our custom debugger,
01.
fill in symbol is used in the multi line comment.
A. /*….. */
B. //
C. [[……]]
D. --[[……]]--
02.
myTable = { …… }
for index,value in fill in ( myTable ) do
loop body
end
A. ipairs
B. ipears
C. ipares
D. iperis
03.
function add( fill in ) -- use symbols as a parameter .
sum = 0
for index, value in ipairs{... } do
sum = sum + value
end
return sum
end
print(add(1,2,3,4,5)) -- pass five parameters to the function
A. args
B. parameters
C. …
D. nothing
04.
book = {" Go "," in "," 8 "," Hours "}
print(table. fill in (book)) -- connect all elements
A. connect
B. concat
C. join
D. link
05.
When assigning a value to an index that is not existing in a table, fill in
method will be triggered. fill in method will handle the error.
A. index
B. __index
C. newindex
D. __newindex
06 .
When creating a class, “ClassName. fill in = Class” makes Class’s fill in point
to itself (a table), so that the Class’s metatable can be used.
A. index
B. __index
C. newindex
D. __newindex
07.
“coroutine.create(myFunc) ” creates a coroutine, returns a coroutine.
“coroutine.wrap(myFunc) ” creates a coroutine, returns a fill in .
A. coroutine
B. thread
C. function
D. table
08.
str = "TypeScript in 8 Hours"
print( #str )
print(string. fill in (str, 5, 10) )
-- extracts a substring from index 5 to index 10
A. extract
B. abstract
C. substract
D. sub
09.
num = 1
::label:: print("Go in 8 Hours")
num = num + 1
if num < 2 then
goto fill in -- go to run the statement with :: label ::
end
A. label
B. if
C. while
D. for
10.
function add(... )
sum = 0
for index, value in ipairs{... } do
sum = sum + value
end
print("Total", fill in ("#",...) ,"parameters passed")
-- check how many parameters have been passed .
return sum
end
add(1,2,3,4,5)
A. check
B. parameter
C. show
D. select
11.
tab = {"A", "B", "C"}
tab[4] = "D" -- append an element
tab[5] = "E" -- append an element
print("The length of the table is: ", fill in ) -- get table length
A. tab. length
B. tab. len()
C. #tab
D. tab. size()
12.
read all contents
"*a"
e. g. io. read("*a")
"*l" read the line
e. g. io. read("*l")
13 .
An object uses the “fill in ” symbol to access the method of the class.
For example obj fill in method()
A. .
B. :
C. ::
D. ->
14.
“fill in ” is used to check a function whether it has any error.
A. checkFunction()
B. __function()
C. assert()
D. pcall()
15.
str1 = "Swift "
str2 = "in 8 Hours "
print(str1 fill in str2 ) -- connect two strings
A. connect
B. .
C. ..
D. …
16.
In Lua, “nil” is equivalent to false, “0” is equivalent to fill in .
A. true
B. false
C. nil
D. null
17.
In Lua, the index of an array and the index of a table begin from fill in
A. 0
B. 1
C. 2
D. 3
18.
When calling a method that does not exist in the table, fill in method will be
triggered; fill in method will handle the issue.
A. __function
B. __index
C. __method
D. __call
19.
file. seek(“ fill in ”, index)
-- seek the string from the beginning location
A. set
B. cur
C. mid
D. end
20.
21.
“fill in (object)” returns the environment variable of the object.
A. getfenv
B. environmentVar
C. enviriable
D. environVariable
22.
Usually we need to process multiple files at the same time.
In this case, we should use “fill in functionName()” method instead of the “fill
in functionName()” method.
A. io. file:
B. file: io.
C. io: file.
D. file. io :
23.
“coroutine. fill in ()” returns a running coroutine
A. status
B. thread
C. running
D. run
24.
“fill in ()” returns a registry
A. registry
B. _registry
C. returnregistry
D. getregistry
Answers