Garry's Mod Wiki

Revision Difference

Beginner_Tutorial_Tables#524865

<cat>Dev.GettingStarted</cat> <title>Coding - Tables</title> # 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 ```lua 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 ```lua Fruits = { "Apple", "Orange", "Banana", "Pineapple" } Veggies = { "Pepper", "Tomato" } table.Merge(Fruits, Veggies) print(table.concat(Fruits," ")) Pepper Tomato Banana Pineapple ``` ```lua Fruits = { "Apple", "Orange" } Veggies = { "Pepper", "Tomato" } table.Add(Fruits, Veggies) print(table.concat(Fruits," ")) Apple Orange Pepper Tomato ``` ## Usage of "pairs" ```lua Names = {"John","Mary","Mark",Den"} 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" ```lua 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" ```lua Names = {"John","Mary","Mark","Den"} for key,value in RandomPairs(Names) do print(value) end Den Mary Mark John ``` ## Usage of "SortedPairs" ```lua Names = {"John","Mary","Mark","Den"} for key,value in SortedPairs(Names) do print(value) end Den John Mark Mary ```