Greetings Community. Today, i'v decided to make a tutorial about LUA tables. In this tutorial, you'll find the whole information about it. it's easy just try to follow my tutorial step by step.
Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings of corse except nil.
Note: "Tables have no fixed size it can contain billions of rows "based on our need."
Lua uses a constructor expression "{}" to create an empty table. An example is shown below
mtaTable = {} -- simple table empty
mtaTable[1]= "MTA:SA" --simple table value assignment
There are in built functions for table manipulation.
1) table.concat (table [, sep [, i [, j]]]) : Concatenates the strings in the tables based on the parameters given.
local MTA = {"1","2","3","4","5","6"} -- simple table contain numbers.
outputChatBox(table.concat(MTA)) -- concatenated string of table.
=== > [[output : 123456]]
local MTA = {"1","2","3","4","5","6"} -- simple table contain numbers.
outputChatBox(table.concat(MTA,", ")) -- concatenate with a character.
=== > [[output : 1,2,3,4,5,6]]
local MTA = {"1","2","3","4","5","6"} -- simple table contain numbers.
outputChatBox(table.concat(MTA,", ", 2,3)) -- concatenate MTA (table) based on index.
=== > [[output : 2,3]]
2) table.insert (table, [pos,] value): Inserts a value into the table at specified position.
-- Example 1:
local MTA = {"Yellow","Blue","Red"} -- same table but this time contain some colors.
table.insert(MTA,"Green") -- insert an other name at the end of the table.
-- Result : MTA = {"Yellow","Blue","Red","Green"}
outputChatBox("Last color added "..MTA[4]) -- Green
-- Example 2:
table.insert(MTA,2,"Black") -- insert new color at index 2
outputChatBox("Color at index 2 is "..MTA[2]) -- Black
3) table.remove (table [, pos]) : Removes the value from the table.
table.remove(MTA)
outputChatBox("The previous last element is "..MTA[5]) -- nil
4) table.sort (table [, comp]) : Sorts the table based on optional comparator argument.
Sorting table is often required and the sort functions sort the elements in the table alphabetically. A sample for this shown below.
local MTA = {"Yellow","Blue","Red","Green"}
for k,v in ipairs(MTA) do
outputChatBox("Index: "..k..", Value:"..v)
end
--[[ Result
Index: 1, Value: Yellow
Index: 2, Value: Blue
Index: 3, Value: Red
Index: 4, Value: Green]]--
table.sort(MTA) -- using table.sort
for k,v in ipairs(MTA) do
outputChatBox("Index: "..k..", Value:"..v)
end
--[[ Result
Index: 1, Value: Blue
Index: 2, Value: Green
Index: 3, Value: Red
Index: 4, Value: Yellow]]--