You are on page 1of 127

Lua

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

About the Author: Ray Yao


Certified PHP engineer by Zend, USA
Certified JAVA programmer by Sun, USA
Certified SCWCD developer by Oracle, USA
Certified A+ professional by CompTIA, USA
Certified ASP. NET expert by Microsoft, USA
Certified MCP professional by Microsoft, USA
Certified TECHNOLOGY specialist by Microsoft, USA
Certified NETWORK+ professional by CompTIA, USA
www . amazon . com/author/ray-yao
Recommended Books on Amazon
Advanced C++ in 8 Hours
Advanced Java in 8 Hours
AngularJs Programming
Awk in 8 Hours
BootStrap in 8 Hours
C# Interview Q&A
C# Programming
C++ Interview Q&A
C++ Programming
Dart in 8 Hours
Django in 8 Hours
Erlang in 8 Hours
Go in 8 Hours
Html Css Interview Q&A
Html Css Programming
Java Interview Q&A
Java Programming
JavaScript Interview Q&A
JavaScript Programming
JQuery Interview Q&A
JQuery Programming
Kotlin in 8 Hours
Linux Interview Q&A
Lua in 8 Hours
Matlab in 8 Hours
MySql in 8 Hours
Node . Js in 8 Hours
Perl in 8 Hours
Php Interview Q&A
Php MySql Programming
PowerShell in 8 Hours
Python Interview Q&A
Python Programming
R Programming
Ruby Programming
Rust in 8 Hours
Scala in 8 Hours
Shell Scripting in 8 Hours
Swift in 8 Hours
Tcl in 8 Hours
TypeScript in 8 Hours
Visual Basic Interview Q&A
Visual Basic Programming
Vue . Js in 8 Hours
Xml Json in 8 Hours
Preface
“Lua Programming in 8 Hours” covers all essential Lua language
knowledge. You can learn complete primary skills of Lua programming fast
and easy.
The book includes more than 60 practical examples for beginners and
includes tests & answers for the college exam, the engineer certification
exam, and the job interview exam.

Note:
This book is only for Lua beginners, it is not suitable for experienced Lua
programmers.

Source Code for Download


This book provides source code for download; you can download the source
code for better study, or copy the source code to your favorite editor to test
the programs.
Table of Contents

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

Lua Questions & Answers


Questions
Answers

Source Code Download


Hour 1
What is Lua Language?
Lua is a lightweight, advanced, multi-pattern scripting language designed
chiefly for embedded applications, so that it can provide flexible expansion
and customizing features. Lua is written in standard C language and can be
compiled and run on almost any operating system and platform.
Lua scripts can be easily invoked by C/C++ code, and can also call C/C++
functions in reverse, which makes Lua widely available in applications. Lua
can be used not only as an extension script, but also as a plain programming
file. It can replace XML, INI and other file formats and is easier to
understand and maintain.
Lua usually works in conjunction with other languages. Lua is a small but
powerful scripting language.
Lua is a scripting language, like embedding JavaScript code in HTML,
helps with web development and web design.
Lua can make game programs, and game configuration files.
Lua can help with extensions and database plug-ins, such as MySQL proxy.
Lua can help with security systems, such as intrusion detection systems.
Install Lua
01.
Download Link of Lua:
https : //github . com/rjpcomputing/luaforwindows/releases
02.
Click the download link on the website:

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!

Congratulations! Lua is installed successfully!


“Hello World” Script
Example
We can use the Lua IDE to run the “Hello World” scripting file.
The name of the Lua IDE is “SciTE ”.
01.
Double click the icon of the SciTE on the computer desktop:

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

“- -“ symbol is used in the single line comment.


“- -[[ ]]- -“ symbol is used in the multi line comment.
The Lua compiler always ignores the comment.
Example 1.1
print("Hello World! ") -- print() is used to output contents
--[[
This is a “Hello World” program in Lua.
The Lua compiler always ignores the comment.
Lua is a scripting language
]]--
Output:
Hello World!
Explanation:
“ - - “ symbol is used in the single line comment.
“ - -[[ ]]- - “ symbol is used in the multi line comment.
Identifier
The identifier is the name of variable, constant, string, function, array,
collation…
Identifier consists of the letter from A to Z, from a to z, from 0 to 9, or
letter/number prefixed with an underline.
Lua identifier does not allow the use of special characters such as @, &, $,
# and % to define, and does not allow start with numbers.
Lua identifier is case sensitive. For example: jQuery and JQuery is two
different variable names.

The following identifiers are valid:


very_good ok_123 veryGood123 _good ok123Good

The following identifiers are invalid:


very@good ok%123 very&Good $good 123Good
Lua Reserved Keywords
Reserved Keywords cannot work as the name of variable, constant, string,
function, array, collation…
Reserved Keywords are only used in Lua itself.

The following is the Lua reserved keywords:


and break do else
elseif end false for
function if in local
nil not or repeat
return then true until
while goto

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.

The data types of Lua are as follows:


Type Description
nil Represents an invalid value or false
boolean Include two values: false or true
number A real number or a double-precision type
string A series of characters enclosed by double quotes
function Functions written in C or Lua
userdata Any C data structure stored in a variable
thread An independent path of execution within a program
table A special object containing multiple values
Check Data Type
We can use type() to check the data type of a value.
type(value)
Example 1.2
print(type ("R in 8 Hours"))
print(type (100 + 200))
print(type (false))
print(type (nil))
print(type (print))
Output:
string
number
boolean
nil
function
Explanation:
“type(value)” can check the data type of a value.
Variable
The variable is a container to store a value that will change any time. The
syntax to define a variable is:
variable = value
Example 1.3
num = 100
print(num)
a, b, c = 1, 2, 3
print(a,b,c)
x, y, z = 10, 20
print(x, y, z) -- “z” assigns no value, returns nil
Output:
100
1 2 3
10 20 nil
Explanation:
“num = 100” assigns a value 100 to variable “num”.
Nil
Nil represents a type that has no valid values. Printing an unassigned
variable will output a nil value. So if you assign a variable a nil value, that's
the same thing as removing it.
Example 1.4
print(x)
y = 100
print(y)
y = nil
print(y)
Output:
nil
100
nil
Explanation:
“print(x)” try to print a variable that has not yet defined.
“y = nil” is equal to remove the variable “y”.
Global & Local
The global variable is defined outside a code block;
A variable is a global variable by default.
The local variable is defined inside a code block.
A local variable need to explicitly declare by using “local”.
Example 1.5
a = 10 -- global variable
function block()
local b = 20 -- local variable
end
print(a)
print(b)
Output: 10 nil
Explanation:
“function block(){…}” is a code block.
“local b” is a local variable inside the code block.
“print(b)” cannot access the local variable inside the code block.
Hour 2
String
String consisted of a series of characters. The syntax is:
‘ string ’ -- enclosed by a pair of single quotes
“ string ” -- enclosed by a pair of double quotes
[[ string ]] -- enclosed by [[ symbol and ]] symbol
Example 2.1
string1 = 'Go in 8 Hours'
print(string1) -- Output : Go in 8 Hours
string2 = "Rust in 8 Hours"
print(string2) -- Output : Rust in 8 Hours
string3 = [[Scala in 8 Hours]]
print(string3) -- Output : Scala in 8 Hours
Explanation:
‘ string ’ is enclosed by a pair of single quotes.
“ string ” is enclosed by a pair of double quotes.
[[ string ]] is enclosed by [[ …… ]] symbol.
Escape Character
Escape characters are used to represent characters that cannot be displayed
directly, such as Return, Backspace…
\a bell
\b backspace
\f page chage
\n new line
\r enter
\t tab
\\ represent a slash
\' represent a single quote
\" represent a double quote
\0 null
\ddd octal characters
\xhh hexadecimal characters
For example:
string = "He said \' Hello! \' " -- use \'
print(string) -- Output : He said ' Hello ! '
String Length & Reverse
01.
The syntax to get the length of a string is:
string. len("arg")
02.
The syntax to reverse all character sequences of a string is:
string. reverse(“arg”)
Example 2.2
print(string.len ("JavaScript"))
print(string.reverse ("JavaScript"))
Output:
10
tpircSavaJ
Explanation:
“string. len("JavaScript")” gets the length of the “JavaScript”.
“string. reverse("JavaScript")” reverses all character sequences of the
“JavaScript”.
String Format
The string. format() function is used to generate a string with a specific
format.
string. format( %fm. data)
“fm” specifies the format. “data” is the data of the string.

The following is the format of the data:


Format Data
%c return a character from asii code
%d return an integer
%i return an integer
%o return an octal number
%x return an hexa number
%e return a scientific notation
%f return a float number
%s return a string
Example 2.3
print(string.format ("%c", 68)) -- output : D
print(string.format ("%d", 68. 000)) -- output : 68
print(string.format ("%8. 3d", 68)) -- output : 068
print(string.format ("%o", 68)) -- output : 104
print(string.format ("%x", 68)) -- output : 44
print(string.format ("%e", 68)) -- output : 6 . 800000e+01
print(string.format ("%8. 3f", 68)) -- output : 68 . 00 0
print(string.format ("%s", "Java")) -- output : Java
print(string.format ("%8s", "Java")) -- output : Java
print(string.format ("%8. 3s", "Java")) -- output : Jav
Explanation:
("%c", 68) means to output the asii code of the 68.
%8. 3d means that the number length is 8 (including spaces), only the first
three numbers are printed.
%8. 3f means that the number length is 8 (including spaces), the decimal
places is 3.
%8. 3s means that the string length is 8 (including spaces), only the first
three characters are printed.
#string, find() & sub()
“#string” gets the length of the string.
find() gets the start index and the end index of a string.
sub() extracts a substring from index1 to index2 in a string
Example 2.4
str = "TypeScript in 8 Hours"
print( #str )
print(string.find(str,"Script") )
print(string.sub(str, 5, 10) )
Output:
21
5 10
Script
Explanation:
“#str” gets the length of the string. The length is 21.
“find(str,"Script")” gets the start index and end index of a “Script”.
“sub(str, 5, 10)” extracts a substring from index 5 to index 10.
Connect & Repeat

string1 .. string2 connects two strings


rep(str, n) repeats the str n times

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

lower("string") converts the “string” to lowercase.


upper("string") converts the “string” to uppercase.
gsub("string","a","b")” replaces the “a” with the “b”.
Example 2.6
print(string.lower("JavaScript") )
print(string.upper("JavaScript") )
print(string.gsub("JavaScript","a","o") )
Output:
javascript
JAVASCRIPT
JovoScript 2
Explanation:
“lower("JavaScript")” converts the “JavaScript” to lowercase.
“upper("JavaScript")” converts the “JavaScrpt” to uppercase.
“gsub("JavaScript","a","o")” replaces the “a” with the “o”.
“2” in the output indicates that two letters has been replaced.
Character & ASII
A character can be converted to an asii code and …
an asii code can be converted to a character.
Their converting syntaxes are:
string. byte("character") -- convert to an asii code
string. char(asii_code) -- convert to a character
Example 2.7
print("The asii code of S character is: ",string.byte("S") )
print("The character of 83 asii code is: ",string.char(83) )
Output:
The asii code of S character is: 83
The character of 83 asii code is: S
Explanation:
“string. byte("S")” converts the character “S” to an asii code.
“string. char(83)” converts the asii code 83 to a character.
Arithmetical Operators

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

Operators Running Result


> greater than true or false
< less than true or false
>= greater than or equal true or false
<= less than or equal true or false
== equal true or false
~= not equal true or false

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

Operators Assume: A = true, B = false


and (A and B) returns false
or (A or B) returns true
not not (A) returns false, not (B) returns true
Example 2.10
A , B = true , false
print("A and B", A and B) -- output : A and B false
print("A or B", A or B) -- output : A or B true
print("not A", not A) -- output : not A false
print("not B", not B) -- output : not B true

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

In Lua, the for nested loop syntax is:

for startValue, endValue, step


do
for startValue, endValue, step -- nested loop
do
statements
end
statements
end
In Lua, the repeat...until nested loop syntax is :
repeat
statements
repeat -- nested loop
statements
until( condition )
until( condition )

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

The syntax to call a function is:


functionName()

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

To call a function, use “functionName (argument);”


functionName (argument );
Example 4.3
function myFunc(args ) -- define a function with args
print("Hello! ",args )
end
myFunc("My Friends ") -- call the function with arguments

Output: Hello! My Friends


Explanation:
“function myFunc(args )” defines a function with args, which are used to
receive the come-in parameter.
“myFunc("My Friends ")” calls the function and passes the parameter to it.
Return
“return” statement works inside a function.
“return” statement is used to return a value to the caller.
return result

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

function add( ... ) -- use three points 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 .

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

module = {} -- define a module


module. variable = "TypeScript in 8 Hours" -- define a variable
function module. func() -- define a function
print("Shell Scripting in 8 Hours")
end
return module -- return to the file that requires the module

Please save the file as “myModule.lua ”.


The following is another file that requires the myModule. lua.
require("myModule ") -- import the module file
print(module. variable) -- use the variable of the module
module. func() -- use the function of the module
Please save the file as “another.lua ”, and run it.
Output:
TypeScript in 8 Hours
Shell Scripting in 8 Hours
Explanation:
“myModule. lua” is a module.
“require("myModule ")” imports a module “myModule. lua”.
Garbage Collection
Lua can automatically manage memory. Lua runs a garbage collector to
collect all dead objects, and release memory.
However, at certain times we can manually tune the garbage collector for
better performance.
The garbage collector function is as follows:
collectgarbage("collect")
Do a complete garbage collection.
collectgarbage("count")
returns the total memory k bytes used by the Lua.
collectgarbage("restart")
Restart the automatic run of the garbage collector.
collectgarbage("interval")
Set the interval rate of the collector.
collectgarbage("step")
Run the garbage collector step by step.
collectgarbage("stop")
Stops running the garbage collector
Example 5.6
myTable = {"A", "B", "C"}
print(collectgarbage ("collect"))
print(collectgarbage ("count"))
myTable = nil
print(collectgarbage ("collect"))
print(collectgarbage ("count"))
collectgarbage ("stop")
Output:
0
23. 3095703125
0
23. 2080078125
Explanation:
“collectgarbage ("collect")” makes a full garbage collection.
“collectgarbage ("count")” counts how many K bytes of memory that Lua
has used.
“collectgarbage ("stop")” stops running the garbage collector.
MetaTable
MetaTable is used to define an operating mode of a table, and change the
action of a table. MetaTable is a helper of a table.
In Lua, any table has a metatable.
getMetatable() method gets a metatable of the table.
setmetatable() method sets a metatable of the table

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, a class can be regarded as a table.


“property = value” defines the Class’s property and the value.
“ClassName. __index = ClassName” makes Class’s __index point to itself
(a table), so that the Class’s metatable can be used.
Object
Object refers to a concrete something. For example: a car, a book, a dog, a
house, etc…

The syntax to create an object is:


obj = ClassName: constructor()

An object uses the “. ” symbol to access the properties of the class.


obj. property

An object uses the “: ” symbol to access the method of the class.


obj : method()

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

“function ClassName : constructor()” define a constructor.


“obj = {}” creates a table of the object.
“setmetatable(obj, ClassName)” sets a metatable of the obj table, so that the
obj can access the property and method of the class.
“ClassName. property = value” initializes the class’s property value.
Example 7.1

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()

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

House = {height = 0} -- define a class, namely a table


House. __index = House -- __index points to House
function House: constructor (myHouse, meter) -- constructor
myHouse = {} -- create a table of myHouse
setmetatable(myHouse, House)
House. meter = meter -- initialization
House. height = meter * 3. 2808399 -- initialization
return myHouse
end
function House: size ()
print("The height is 100 meters\n")
print("The height is ".. House. height.. " feet")
end
myHouse = House: constructor(nil,100) -- create an object
myHouse: size() -- the object accesses size()
Output: The height is 100 meters
The height is 328. 08399 feet
Explanation:
“House. __index = House” makes House’s __index point to itself (a table),
so that the House’s metatable can be used.
“setmetatable(myHouse, House)” sets a metatable of myHouse, so that
myHouse can access the property and method of House.
Inheritance
A parent class can be inherited by its child class. All properties and
methods of the parent class can be inherited by its child class. The syntax of
the inheritance is:
ChildClass = ParentClass : constructor()

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()

-- the following code is about inheritance


Boy = Person:new() -- child class inherits parent class
Boy. __index = Boy
function Boy: new() -- define a constructor
Jenson = {} -- create a table of Jenson
setmetatable(Jenson, Boy)
return Jenson
end
function Boy: say(greeting)
print(greeting)
end
Jenson = Boy. new() -- create an object
Jenson: say("Hello, All Over the World! ") -- the object accesses say()
Output:
Hello, My Friends!
Hello, All Over the World!
Explanation:
“Boy = Person: new()” means that the child class Boy inherits the parent
class Person.
Overriding
The method in the child class can override the method in the parent class, if
two method names, two parameters are the same.

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! ")

-- the following code is about inheritance


Boy = Person: new() -- child class inherits parent clas s
Boy. __index = Boy
function Boy: new()
Jenson = {}
setmetatable(Jenson, Boy)
return Jenson
end
function Person:say(greeting) -- the method in child class
print(greeting)
end
Jenson = Boy. new()
Jenson: say("Hello, All Over the World! ")
Output:
Hello, My Friends!
Hello, All Over the World!
Explanation:
“function Person:say(greeting)…end ” in the child class can override the
same method in the parent class, because their function names, arguments
are the same.
Coroutine
Coroutine is a subroutine which needs to work cooperatively.
Coroutine is a special thread that has following features:
1. Only one coroutine is allowed to run at any given time.
2. The running coroutine will only be suspended if it is explicitly requested
to be suspended.
The following is coroutine methods:
coroutine.create(function())
Create coroutine and return coroutine

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

Return “true ” if the coroutine methods run successfully.


Example 7.5
co = coroutine.create(function ( x, y ) -- create a coroutine
print("thread1", x, y)
coroutine.yield() -- suspend the thread1
print("thread2", y, x)
return x*y
end)
print("Resume thread1: ", coroutine.resume(co, 10, 2) )
print("Check thread1 status: ", coroutine.status(co) )
print("Resume thread2: ", coroutine.resume(co) )
print("Check thread2 running: ",coroutine.running() )
Output:
thread1 10 2
Resume thread1: true
Check thread1 status: suspended
thread2 2 10
Resume thread2: true 20
Check thread2 running: thread: 0x1e5d268 true
Explanation:
“co = coroutine. create(function ( x, y )” creates a coroutine.
“coroutine. yield()” suspends the current thread.
“coroutine. resume(co, 10, 2)” restarts the coroutine.
“coroutine. status(co)” checks the status of the current thread.
“coroutine. running()” checks which thread is running.
“thread: 0x6f5268” indicates that thread2 is running. Because thread1 has
been suspended, and only one thread is allowed to run at one time.
Return “true ” if the coroutine methods run successfully.
Hour 8
coroutine . wrap()

“coroutine. wrap()” is used to create a coroutine.


The difference of the coroutine. create() and coroutine. wrap() is:
“coroutine. create()” returns a coroutine or is resumed.
“coroutine. wrap()” returns a function or is called by a function.
Example 8.1
myFunc = function(num)
print("num = ", num)
coroutine. yield(num)
end
co = coroutine.create(myFunc)
print("The type of create(): ", type(co))
coroutine. resume(co, 10) -- run “coroutine . create(myFunc)”
coFunc = coroutine.wrap(myFunc)
print("The type of wrap(): ", type(coFunc))
coFunc(20) -- run “coroutine . wrap(myFunc)”
Output:
The type of create(): thread
num = 10
The type of wrap(): function
num = 20

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

function myFunc (str)


if type(str) ~= "string" then
error("The parameter is not a string")
end
end
myFunc( 100 )

Output: The parameter is not a string. (Error messages…)


Explanation:
The parameter (100) is a number.
“type(str) ~= "string"” checks the number if it is a string.
“error("The parameter is not a string") ” shows the error message if an
error occurs.
pcall()
“pcall()” is used to check a function whether it has any error.
pcall(function)
Example 8.6

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,

The Debug library in Lua contains the following functions.


debug():
Enter a user interaction mode and run each string command input by the
user. For example:
With simple commands and other debugging Settings, users can review
global and local variables, change the values of variables, evaluate
expressions, and so on
getfenv(object):
Returns the environment variable of the object.
gethook(optional thread):
Returns three values representing the thread’s hook settings: current hook
function, current hook mask, current hook count
getinfo ([thread,] f [, what]):
Returns a table about a function information.
debug.getlocal ([thread,] f, local):
Returns the name and the value of the local variable whose index is local
at the f layer of the stack.
getmetatable(value):
Return a metatable of a value.
getregistry():
Returns a registry
getupvalue (f, upper)
Returns the name and the upper value of the f function
sethook ([thread,] hook, mask [, count]):
Set a function as a hook function.
setlocal ([thread,] level, local, value):
Assigns value to the local variables of the level layer function on the
stack.
setmetatable (value, table):
Set the value as a metatable
setupvalue (f, upper, value):
Setups the name and the upper value of the f function
traceback ([thread,] [message [, level]]):
Returns running messages or returns the traceback information that calls
the stack.
Example 8.8
function myfunc ()
print(debug.traceback ("The Stack traceback is as follows: "))
print(debug.getinfo(0) )
end
myfunc ()
Output:
The Stack traceback is as follows:
stack traceback:
script. lua: 2: in function 'myfunc'
script. lua: 5: in main chunk
[C]: in ?
table: 0x192bd70
Explanation:
“debug. traceback()” returns returns the traceback information that calls the
stack. (The function name and the caller)
“debug. getinfo(0)” returns the information of the current function.
“(0)” represents the current function.
“(1)” represents the function that calls getInfo.
Lua
Questions & Answers
Questions
Please fill in the correct answers.

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")

read the specified number of characters.


fill in
e. g. io. read(10)
A. character
B. number
C. string
D. array

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.

ChildClass = ParentClass fill in constructor()


-- A ChildClass inherits a ParentClass
A. inherits
B. extends
C. :
D. ::

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

01. D 09. A 17. B


02. A 10. D 18. D
03. C 11. C 19. A
04. B 12. B 20. C
05. D 13. B 21. A
06. B 14. D 22. B
07. C 15. C 23. C
08. D 16. A 24. D

Source Code Download Link:


https://forms.aweber.com/form/31/1814179131.htm
Source Code D ownload
Recommended Books on Amazon
Advanced C++ in 8 Hours
Advanced Java in 8 Hours
AngularJs Programming
Awk in 8 Hours
BootStrap in 8 Hours
C# Interview Q&A
C# Programming
C++ Interview Q&A
C++ Programming
Dart in 8 Hours
Django in 8 Hours
Erlang in 8 Hours
Go in 8 Hours
Html Css Interview Q&A
Html Css Programming
Java Interview Q&A
Java Programming
JavaScript Interview Q&A
JavaScript Programming
JQuery Interview Q&A
JQuery Programming
Kotlin in 8 Hours
Linux Interview Q&A
Lua in 8 Hours
Matlab in 8 Hours
MySql in 8 Hours
Node . Js in 8 Hours
Perl in 8 Hours
Php Interview Q&A
Php MySql Programming
PowerShell in 8 Hours
Python Interview Q&A
Python Programming
R Programming
Ruby Programming
Rust in 8 Hours
Scala in 8 Hours
Shell Scripting in 8 Hours
Swift in 8 Hours
Tcl in 8 Hours
TypeScript in 8 Hours
Visual Basic Interview Q&A
Visual Basic Programming
Vue . Js in 8 Hours
Xml Json in 8 Hours

Source Code Download Link:


https://forms.aweber.com/form/31/1814179131.htm

You might also like