Jump to content

[TUT] Lua Tables


Recommended Posts





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.


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) 
--[[ 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) 
--[[ Result 
Index: 1, Value: Blue 
Index: 2, Value: Green 
Index: 3, Value: Red 
Index: 4, Value: Yellow]]--
Edited by Walid
  • Like 1
  • Thanks 3
Link to post
Cool dude but what's difference between pairs and ipairs?

Simply :

* ipairs:

loop only number indexes "start from 1 index" and only in order.

* pairs:

Loop all.

for more information check Solidsnake14 link

Link to post

However, for those who still did not understand the differences between pairs and ipairs;

local numerical = {"A", "B", "C"} 
for index, value in ipairs(numerical) do 
    print(index.." => "..value) -- 1 => A 
local alphabetical = {"A", ["two"] = "B", three = "C"} -- Alphabetical indexing can be done either with brackets or rawly (as I've done with three). Though it will be necessary to utilize brackets if you wish adding special characters to these. 
for key, value in pairs(alphabetical) do 
    print(key.." => "..value) -- 1 (numerical indexing) => A 

Also note that, ipairs will ignore alphabetical indexes. Whilst pairs will, as Walid stated above, gather both types, numerical and alphabetical ones.

Link to post

the speed difference between ipairs and pairs is negligible "really really small". i already tested it pairs was faster than ipairs by 0.0000000339seconds. only when you have tables nearing 15k keyvalues.

Link to post
  • 2 weeks later...

I'd just like to point out that 'pairs' don't loop in order of the table either, just because there are some scripts that want to loop the table in order.


local myTable = {  
    ["Index 1"] = "Some random information", 
    ["Another Key?"] = "Some random information ", 
    ["Should be index 3"] = "Some random information", 
    ["Master Race"] = "Some random information", 
    ["Madex"] = "Some random information", 
for index, value in pairs ( myTable ) do 
    print ( index..": "..value ); 
Expected printout: 
Index 1: Some random information 
Another Key?: Some random information 
Should be index 3: Some random information 
Master Race: Some random information 
Madex: Some random information 
-- There's a slight chance it could be in that order, but most likley it won't be 
-- There may be some algorithm that randomises them, but I don't know what it would be  
Real print-out (Example): 
Another Key?: Some random information 
Index 1: Some random information 
Madex: Some random information 
Master Race: Some random information 
Should be index 3: Some random information 

But if you do need to loop a table with non-numerical keys for whatever reason, you can use this function:

function foreachinorder(t, f, cmp) 
    local keys = {} 
    for k,_ in pairs(t) do 
        keys[#keys+1] = k 
    local data = { } 
    for _, k in ipairs ( keys ) do  
        table.insert ( data, { k, t[k] } ) 
    return data 

The only argument you need to worry about is t which is just the table you want to loop.

You'll need to do some experimenting to see how it works, because I'm not sure how to explain it.

Here's how I used it in my gamemode:

local jobRanks = { 
    ['fisherman'] = { 
        [0] = "Deck Hand", 
        [20]= "Net Baiter", 
        [75]= "Line Thrower", 
        [100]="Line Roller", 
        [140]="Boat Captain", 
        [200]="Experienced Fisherman", 
        [270]="Underwater Trap Setter" 
   -- Some other code... Skipping to the point 
    local isNext = false; 
    for _, v in ipairs ( foreachinorder ( jobRanks['fisherman'] ) ) do  
        if ( isNext ) then  
            data.nextRank = v[2]; 
            data.requiredCatches = v[1] - data.caughtFish; 
        if ( v[2]:lower() == data.jobRank:lower() ) then  
            isNext = true; 

Link to post

Yes ipairs gives the numerical indexes in order. Buti pprefer using pairs when the order of index is not needed like

weapons = { 
["weapon"] = "model id" 

In such table i perfer pairs

Link to post
  • 1 month later...
local playerName = {}
local playerSkin = {}
function player()
	local playerName2 = getPlayerName( source )
	table.insert(playerName, playerName2)
addEventHandler("onPlayerLogin", root, player)
function output()
	outputDebugString( "Working" )
addCommandHandler("table2", output)

output chatbox isn't working


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...