Walid

[TUT] Lua Tables

Recommended Posts

Sans_titre_1.png

 

Sans_titre_7.pngSans_titre_8.pngSans_titre_9.png

 

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

 

rep.png

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 
 

man.png

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]]--
 
Edited by Walid
  • Thanks 3

Share this post


Link to post
Good Job dude :)

Thank you everyone.

Everyone? xD Its Only Me lol anyway np

Yeh i know i mean you and SkatCh anyways enjoy. :P

Share this post


Link to post

Cool dude but what's difference between pairs and ipairs?

Share this post


Link to post

Not always, ipairs is used for numeric indexed tables.

Like this one:

myTable = { "A", "B", "C" } 

Share this post


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

Share this post


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 
end 
  
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 
end 
  

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

Share this post


Link to post

What's more, 'pairs' is a little bit faster than 'ipairs'. It was proved in some thread few mouths ago.

Share this post


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.

Share this post


Link to post

Oke so ipairs ignores alphabetical indexing while pairs does both..

Thanks <3

Share this post


Link to post
Oke so ipairs ignores alphabetical indexing while pairs does both..

Thanks <3

Exactly

Share this post


Link to post

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.

Example:

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 ); 
end 
  
--[[ 
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 
    end 
    table.sort(keys,cmp) 
    local data = { } 
    for _, k in ipairs ( keys ) do  
        table.insert ( data, { k, t[k] } ) 
    end  
    return data 
end 

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; 
            break; 
        end  
  
        if ( v[2]:lower() == data.jobRank:lower() ) then  
            isNext = true; 
        end  
    end  
  

Share this post


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

Share this post


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

output chatbox isn't working

Why?

Share this post


Link to post
function output()
  for _, name in ipairs(playerName) do
	outputChatBox(name)
	outputDebugString( "Working" )
  end  
end
addCommandHandler("table2", output)

 

Share this post


Link to post

@Gravestone use for i=1,x do! (much faster)

function output()
   for i=1, #playerName do
      outputChatBox(playerName[i])
      outputDebugString( "Working" )
   end  
end
addCommandHandler("table2", output)

@External Your code working fine

Edited by Walid

Share this post


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.