Garry's Mod Wiki

Coding - Tables

What Are Tables?

Tables are basically variables that hold 2 different things, Keys and Values

This is an extremely basic explaination but there is so much more to them than what is here

Keys

Keys are identifiers for values, generally keys represent the order of things aka

[1]

[2]

[3]

[4]

[5]

but keys can be strings if needed

["String1"]

["String2"]

["String3"]

Values

Values are any form of data type, even other tables!

Table Example

table1 = { [1] = "Value", [2] = "Value" } for k,v in pairs(table1) do -- for key and value in pairs, aka if both of them exist in the table table1 do the following print(k .. " " .. v) end returns 1 Value 2 Value

Usage of table. functions

Fruits = { "Apple", "Orange", "Banana", "Pineapple" } Veggies = { "Pepper", "Tomato" } table.Merge(Fruits, Veggies) print(table.concat(Fruits," ")) Pepper Tomato Banana Pineapple
Fruits = { "Apple", "Orange" } Veggies = { "Pepper", "Tomato" } table.Add(Fruits, Veggies) print(table.concat(Fruits," ")) Apple Orange Pepper Tomato

Usage of "pairs"

Names = {"John","Mary","Mark",Den"} for key,value in pairs(Names) do print(key.." - "..value) end 1 - John 2 - Mary 3 - Mark 4 - Den

Usage of "ipairs"

Names = {[2] = "John", [1] = "Mary",[4] = "Mark",[3] = "Den"} for key,value in ipairs(Names) do print(key.." - "..value) end 1 - Mary 2 - John 3 - Den 4 - Mark

Usage of "RandomPairs"

Names = {"John","Mary","Mark","Den"} for key,value in RandomPairs(Names) do print(value) end Den Mary Mark John

Usage of "SortedPairs"

Names = {"John","Mary","Mark","Den"} for key,value in SortedPairs(Names) do print(value) end Den John Mark Mary

Page Links


Special Pages


Wikis

?

Render Time: 34ms

Session 0
DB GetPage 2
Generate Html 7
SaveChanges 11
Render Body 0
Render Sidebar 12