Jump to content

[TUT] Lua Table


Recommended Posts

Lua tables are a fundamental data structure that allows you to store key-value pairs and create complex data structures. Tables in Lua are versatile and can contain values of different types. Let's dive into a detailed explanation with examples :

Table Creation:
To create a table in Lua, you use curly braces { } and separate the elements with commas. Here's an example:

local table = {1, 2, 3, 4, 5} -- table crt

In the above example, we created a table named table and populated it with values 1, 2, 3, 4, and 5.

Accessing Table Elements:

You can access table elements by using square brackets [ ]. Indices in Lua start from 1. Here's an example:

-- Accessing table elements
print(table[1]) --output :  1
print(table[3]) --output :  3

In the above example, we access the value at the 1st index (1) and the 3rd index (3) of the table.

Adding Elements to a Table:
To add a new element to a table, you specify the index and the value. If the specified index already exists in the table, the value will be overwritten. Here's an example:

-- Removing elements from a table
table[3] = nil

In the above example, we remove the element at the 3rd index of the table.

Getting the Size of a Table:
To get the size of a table (i.e., the number of elements), you can use the # operator. Here's an example:

-- Getting the size of a table
print(#table) -- 5

In the above example, we print the size of the table using the # operator.

Table Iteration:
You can iterate over the elements in a table using the ipairs or pairs functions. ipairs provides index-based iteration, while pairs provides key-based iteration. Here's an example:
 

-- Table iteration
for index, value in ipairs(table) do
  print(index, value)
end

In the above example, we iterate over the table using ipairs and print the index and value of each element.


+---------------------------------------------------+
|                    Game Settings                   |
+---------------------------------------------------+
|     Difficulty:            |        Hard           |
|     Sound Volume:          |        80%            |
|     Controls:              |   Keyboard & Mouse    |
|     Graphics Quality:      |        High           |
+---------------------------------------------------+

In the above example, an ASCII art representation is used to display a Lua table representing game settings. The table consists of different elements representing various game settings.

Here's the Lua code that represents the table:
 

local gameSettings = {
  difficulty = "Hard",
  soundVolume = "80%",
  controls = "Keyboard & Mouse",
  graphicsQuality = "High"
}

In the Lua code, a table named "gameSettings" is created, and different elements representing game settings such as difficulty, sound volume, controls, and graphics quality are added to the table.
 

 

local person = {
  name = "Eren",
  age = 20,
  occupation = "Software Engineer",
  country = "Germany"
}

local tableFormat = [[
+-----------------------+
|      Person Info      |
+-----------------------+
| Name:         %s |
| Age:          %d |
| Occupation:   %s |
| Country:      %s |
+-----------------------+
]]

local formattedTable = string.format(tableFormat, person.name, person.age, person.occupation, person.country)
print(formattedTable)

In the example above, we create a Lua table named "person" and populate it with some sample information about a person. We then define a string format named "tableFormat" which represents an ASCII table structure. We use placeholders like %s and %d to indicate the places where the values from the "person" table will be inserted. Finally, we use the string.format function to fill in the format with the data from the "person" table and store it in the variable "formattedTable". We print the "formattedTable" to display the final result.
I explained string methods in the previous tutorial, here is the link:
string methods LINK

Output : 

+-----------------------+
|      Person Info      |
+-----------------------+
| Name:         Eren |
| Age:          20 |
| Occupation:   Software Engineer |
| Country:      Germany |
+-----------------------+

Nested Tables:
Tables can contain other tables, allowing you to create nested or multidimensional data structures. Here's an example:
 

-- Nested tables
local team = {
  name = "Team A",
  players = {
    { name = "Eren", age = 20 },
    { name = "Emily", age = 27 },
    { name = "Angela", age = 23 }
  }
}

print(team.name) -- Team A
print(team.players[2].name) -- Emily

In the above example, we created a table named team with two elements: name and players. The players element is a nested table that contains information about individual players. We access the name element of the team table and the name of the player at the 2nd index of the players table.

Table Insertion and Removal:
Lua provides various functions for inserting and removing elements from tables. Here's an example that demonstrates these operations:
 

-- Table insertion and removal
local fruits = {"apple", "banana"}

table.insert(fruits, "orange") -- Insert an element at the end
table.insert(fruits, 2, "grape") -- Insert an element at the 2nd index

table.remove(fruits, 1) -- Remove the element at the 1st index

for index, fruit in ipairs(fruits) do
  print(index, fruit)
end

In the above example, we start with a table named fruits containing two elements. Using table.insert, we add an element at the end and another element at the 2nd index. Then, using table.remove, we remove the element at the 1st index. Finally, we iterate over the modified fruits table and print the index and value of each element.

Table Concatenation:
Lua allows you to concatenate tables using the .. operator. Here's an example:
 

-- Table concatenation
local table1 = {1, 2, 3}
local table2 = {4, 5, 6}

local mergedTable = {}

for _, value in ipairs(table1) do
  table.insert(mergedTable, value)
end

for _, value in ipairs(table2) do
  table.insert(mergedTable, value)
end

for index, value in ipairs(mergedTable) do
  print(index, value)
end

In the above example, we have two tables named table1 and table2. We create an empty table named mergedTable and use table.insert to concatenate the elements from table1 and table2 into mergedTable. Finally, we iterate over mergedTable and print the index and value of each element.
 


for MTA:SA

Player Information:
Lua tables can be used to store player information in MTA:SA. Below is an example of a player table that contains details such as the player's name, level, and score:
 

local player = {
  name = "Eren",
  level = 5,
  score = 1000
}

In the above example, we create a table named "player" and populate it with the player's name, level, and score.

Vehicle List:
Lua tables can be utilized to store data related to vehicles in MTA:SA. Here's an example of a vehicle table that includes the model names and colors of the vehicles:
 

local vehicles = {
  { model = "Infernus", color = {255, 0, 0} },
  { model = "Bullet", color = {0, 0, 255} },
  { model = "Sultan", color = {0, 255, 0} }
}

In the above example, we create a table named "vehicles" and store each vehicle as a separate table with its model name and color data. Colors are represented using RGB values.

NPC (Non-Player Character) List:
Lua tables can be used to store in-game NPCs in MTA:SA. Here's an example of an NPC list table that includes the model IDs and coordinates of the NPCs:
 

local npcs = {
  { model = 23, x = 100, y = 200, z = 10 },
  { model = 56, x = 150, y = 250, z = 15 },
  { model = 89, x = 200, y = 300, z = 20 }
}

In the above example, we create a table named "npcs" and store each NPC as a separate table with their model ID and coordinates.
 


I hope you will like it

  • Like 3
Link to comment
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...