Lua Programming Language: Guide to Lua Coding for Kids
Chào mừng bạn đến với pgdgiolinhqt.edu.vn trong bài viết về Lua chúng tôi sẽ chia sẻ kinh nghiệm chuyên sâu của mình cung cấp kiến thức chuyên sâu dành cho bạn.
Tables are used for storing a very large set of data. A table is a Lua that includes the data type to store values like numbers, Booleans, strings, functions, and many more. We can access and manipulate the data easily.
These are more lists that contain the indexes of objects, arrays, and more. To indicate the tables, we use the curly braces {} as shown here:
local p = {}
print(p)
Expected Output:
table: 0035AE18
Once the table is been created it behaves as either an array or a dictionary. This concept we are going to learn is below.
Lua Arrays
Arrays are simply a list of order values that are compiled in a table. This can include strings, numbers, Booleans, functions, and so on.
To make an array, we have to start by assigning a name to it of our own choice. it is useful for storing collections of data such as a group of players with special permissions.
- Creating Arrays
To successively store the data, with commas separating them, in a Lua table to build an array. Any non-nil type, including Boolean, number, string, function, user data, or another table, can be a value for an array.
To assign a table to the data by adding an “=” in between, and write a pair of curly brackets.
For Example:
local randArray = {}
Then we place all of the values inside the array. We can add more variety to our table but we have to make sure to separate each value by adding commas in-between them.
For Example:
local randArray = {“Brightchamps”, 10, “welcome to the brightchamps”, 17}
Lua scripting uses 1-based indexing for arrays so each value in the array has an index or number that is assigned to it. For example, the first value is 1, the second value is 2, the third value is 3, and so on.
- Reading an element from Arrays
To print a specific part of the array, we have to write the table name in the print function and then the index of the value, the in-between square brackets [].
For Example:
local randArray = {“Brightchamps”, 10.1, “welcome to the brightchamps”, 17}
print(randArray[1])
the output will be the first string:
“Brightchamps”.
- Writing Into Arrays
The value of an array and its index can be redefined or rewritten by making use of the index number in the brackets ([pos]) that is followed by the = operator and then specifying the value.
For Example:
local randArray = {“Brightchamps”, 10.1, “welcome to the brightchamps”, 17}
randArray [2] = 12345
randArray [4] = “New string”
print(randArray [2])
print(randArray [4])
Expected Output:
12345
New string
Inserting Items at the end of an array using the methods or the function so the LUA uses the table.insert() function to add elements or values into the array.
To Add the new item into the array using this syntax t[#t+1].
For Example:
local randArray = {“Brightchamps”, 10.1, “welcome to the brightchamps”, 17}
table.insert(randArray, “New string”)
randArray [#randArray +1] = “Another new string”
print(randArray [5])
print(randArray [6])
Expected Output:
New string
Another new string
If we want to insert an item in between the start and the end by specifying the position value as a second argument of the table.insert() function.
So this will insert the new item and push the item that is present with one index position ahead.
For Example:
local randArray = {“Brightchamps”, 10.1, “welcome to the brightchamps”, 17}
table.insert(randArray, 2, “NEW ITEM #2”)
print(randArray [1])
print(randArray [2])
print(randArray [3])
Expected Output:
Brightchamps
NEW ITEM #2
10.1
- Iterating Over an Arrays
Arrays can be iterated over or looped through in the following two ways:
-
- By making use of the built-in ipairs() function for a loop.
For Example:
local TArray = {“this is a string”, 3.9, workspace.part, “New string here”}
for i, value in ipairs(TArray) do
print(i, value)
end
Expected Output:
this is a string
3.9
workspace.part
New string here
-
- By Getting the array length using the # operator and looping it from 1 to that length of the array.
For Example:
for ii = 1, #testArray do
print(ii, TArray[index])
end
Expected Output:
this is a string
3.9
workspace.part
New string here
Removing Items from Arrays in Lua
If we want to remove an item from the array so the LUA provides a function called a table.remove().
This function will help us to remove the item at the specified position and move an item down one index position.
For Example:
local randArray = {“Brightchamps”, 10.1, “welcome to the brightchamps”, 17}
table.remove(randArray, 2)
print(randArray [1])
print(randArray [2])
Expected Output:
Brightchamps
Welcome to the brightchamps
- Dictionaries
Dictionaries are the extension of an array. As we know the array stores an ordered list of items, and a dictionary stores a value set of key-value pairs.
Key Value
FruitName mango
FruitColor yellow
Sour false
- How to Create Dictionaries
To create a dictionary, we have to keep remember that each key is followed by = and then the value we have to write, and each key-value pair is separated with a comma.
For Example:
local testD = {
FruitName = “mango”,
FruitColor = “yellow”,
Sour = false
}
The keys are not limited to string names but a key also may be an Instance, so the key must be declared by surrounded by the brackets ([key])
For Example:
local p = Instance.new(“Part”)
local testD = {
PType = “Block”,
[p] = true
}
- Reading From the Dictionaries
To read it from a dictionary, add a pair of brackets after it specifies the reference and then specifies the key name.
For Example:
local p = Instance.new(“Part”)
local testD = {
PType = “Block”,
[p] = true
}
print(testD[“PType”])
print(testD[p])
Expected Output:
Block
true
The String keys like PType must be surrounded with the quotes as in testD[“PType”]. Non-string keys like [p] should not be surrounded by quotes.
- Writing Into the Dictionaries
The value of a new or the existing dictionary key can be defined by indicating the key name in the square brackets [key] that should be followed by = and then the value in it.
For Example:
local testD = {
FruitName = “mango”,
Sour = false
}
testD [“FruitName”] = “Banana”
testD [“Sour”] = false
testD [“FruitCount”] = 20
print(testD [“FruitName”])
print(testD [“Sour”])
print(testD [“FruitCount”])
Expected Output:
Banana
False
20
- Iterating Over the Dictionaries
Dictionaries can be iterated or read over with the help of the built-in pairs() function in a for a loop.
For Example:
local testD = {
FruitName = “mango”,
FruitColor = “yellow”,
Sour = false
}
for key, values in pairs(testD) do
print(key, values)
end
Expected Output:
FruitNamemango
FruitColoryellow
Sourfalse
Note: using the ipairs() function in the array, dictionary iteration happens via the pairs() does not necessarily return items in the same order as it is mentioned in the dictionary.
- Removing Key-Value Pairs
To remove a key-value pair from the dictionary, we have to set its value to nil. The following example completely erases the key-value pair from the dictionary.
For Example:
local testD = {
FruitName = “mango”,
FruitColor = “yellow”,
Sour = false
}
testD [“Sour”] = nil
for key, value in pairs(testD) do
print(key, value)
end
Expected Output:
FruitName mango
FruitColor yellow
- Tables as References
If we have stored a table in a new variable, at that time copy of that table is not created but the variable becomes a reference that is a pointer to the original table or a variable.
It means any changes to the original table will be reflected in the references.
For Example:
local originalA = {10, 20}
local arrayR = originalArray
print(“Original values:”, originalA[1], originalA[2])
print(“Reference values:”, arrayR[1], arrayR[2])
originalA[1] = 1000
originalA[2] = 2000
print(“Reference values:”, arrayR [1], arrayR[2])
Expected Output:
Original values: 10 20
Reference values: 10 20
Reference values: 1000 2000