Garry's Mod Wiki

Cheat Sheet

Lua Cheat Sheet

Comments

-- This is a single line comment. The Lua compiler will ignore this line completely. --[[ This is a multi-line comment. Anything between these pairs of square brackets will be ignored by the compiler. ]] --[[ You can also use multi-line comments for in-line comments, if you want ]] ---- // Garry's Mod Lua supports using C-style comments, but they are not available in other forms of Lua and will appear as errors in many editors. /* This is a C-style multi-line comment. */

Variables

-- Local variables local myVariable = 5 -- A local variable holding a number. myVariable = 10 -- Variables can be re-used to hold a different value myVariable = "Hi!" -- Variables can even be re-used to hold a different type of data. (This can make your code confusing!) -- Global variables MY_VARIABLE = 2.15 -- Global variables are just like local variables but they're accessible from everywhere, even other addons!

Data Types

--[[ Nil ]]-- -- Nil is a placeholder value representing a lack of data much in the same way that the number 0 represents a lack of quantity nil --[[ Strings ]]-- "I'm a string!" 'I\'m also a string!' -- Note that we use the escape character "\" in "I'm" to avoid ending the string prematurely -- You can join (Or "Concatenate") strings together with ".." to make them into a single string "Hello" .. " " .. "World!" -- This will create the string "Hello World!" --[[ Numbers ]]-- 15 0.56 8.3e10 -- This is the same as (8.3 * 10^10) or 83000000000 8.3e+10 -- This is the same as 8.3e10 but you can specify that it has an exponent of positive 10 if you want 8.3e-10 -- This is the same as 0.00000000083 --[[ Booleans ]]-- true false --[[ Functions ]]-- -- A global function function YellMessage( message ) local loudMessage = string.upper( message ) .. "!" print( loudMessage ) end -- A local function local function AddNumbers( a, b ) return a + b end -- Functions are just a data type like any other local SubtractNumbers = function( a, b ) return a - b end -- functions can return multiple values local function SquareAndCube( a ) return a^2, a^3 end --[[ Tables ]]-- local myTable = {} -- An empty table -- Tables can store data sequentially using automatically-assigned numerical keys starting from 1 (Called an "Index" or "Indices") myTable = { 100, -- This is index 1 5, -- This is index 2 200, -- This is index 3 } -- Table keys and values can be any data type myTable = { ["My Key"] = "My Value!", -- A string key and a string value [2] = true, -- A number key and a boolean value [false] = function() -- A boolean key and a function value print( "Howdy!" ) end, [function() -- A function key and a boolean value print( "Hello!" ) end] = true } -- Table keys and values can be changed, added, and removed at any time myTable[ "My Key" ] = "A new value"