Show Menu
Cheatography

Lua Scripting 5.1 Cheat Sheet by

Types

number
string
boolean
table
function
userdata
thread
nil
Variable type can be obtained with type(v­ari­able)
Note: Table index starts at 0, but can be extended to 0 or negative numbers

Arithmetic Expres­sions

Sum
+
Negati­on/­Sub­tra­ction
-
Product
*
Division
/
Modulo
%
Power
^

Relational Expres­sions

Equal to
==
Not equal to
~=
Less than
<
Greater than
>
Less than or equal to
<=
Greater than or equal to
>=

Logical Operators

not
and
or
Even though Lua does not have a Ternary operator (condition ? truevalue : falsev­alue), we can use and and or to achieve a similar effect:
value = (condition and truevalue) or falsevalue

In this case and returns truevalue when the condition is true and falsevalue otherwise

Tables

Tables are used with the table[key] syntax
Example:
> t = {foo="b­ar"} -- Same as t={["fo­o"]=­"­bar­"}
> t.foo
bar

They can also be used as arrays
a = {1, 2, 3}

But in this case, index starts at 1
a = {[0]=1, [1]=2}
Tables can be extended to index 0 or even negative numbers

Table size can be found with:
> a = {1, 2, 3}
> # a
3

Functions and modules

Functions
value = function(args) body end
function functi­onName(args) body end

Functions can be used as arguments:
function f(f2, arg1) f2(arg1) end

Return skips other code below it

Modules
A common module declar­ation usually is:
local mymodule = {}
function mymodu­le.f­oo() print("­bar­") end
return mymodule

As tables can have functions assigned to a key.

To import it, just do:
> module = requir­e("m­ymo­dul­e")
> module.foo()
bar

Also, you can make private functions by putting local in front of the function declar­ation.
 

Math Library

math.a­bs(­number)
math.a­cos­(ra­dians), math.a­sin­(ra­dians), math.a­tan­(ra­dians)
math.c­eil­(nu­mber), math.f­loo­r(n­umber)
math.c­os(­rad­ians), math.s­in(­rad­ians), math.t­an(­rad­ians)
math.d­eg(­rad­ians), math.r­ad(­deg­rees)
math.e­xp(­num­ber), math.l­og(­number)
math.m­in(­num1, num2, ...), math.m­ax(­num1, num2, ...)
math.s­qrt­(nu­mber)
math.r­and­om(), math.r­and­om(­upper), math.r­and­om(­lower, upper)
math.r­and­oms­eed­(seed)
math.huge --represents infinity
math.pi
On trigon­ometric calcul­ations, the number is expressed as radians.
On math.r­andom() lower and upper are inclusive.
math.huge can be also repres­ented with -math.huge

Control Structures

if/else statement
if (condi­tion1) then
block
elseif (condi­tion2) then
block
else
block
end

while loop
while (condi­tion) do
block
end

repeat loop
Like while loop, but condition is inverted
repeat
block
until (condi­tion)

Numeric for loop
for variable = start, stop, step do
block
end

Iterator for loop
for var1, var2, var3 in iterator do
block
end

Table Library

table.c­on­cat­(table [, sep [, i [, j]]])
Concat­enate the elements of a table to form a string. Each element must be able to be coerced into a string.
table.f­or­eac­h(t­able, f)
Apply the function f to the elements of the table passed. On each iteration the function f is passed the key-value pair of that element in the table. Apply the function f to the elements of the table passed. On each iteration the function f is passed the key-value pair of that element in the table. Deprecated
table.f­or­eac­hi(­table, f)
Apply the function f to the elements of the table passed. On each iteration the function f is passed the index-­value pair of that element in the table. This is similar to table.f­or­each() except that index-­value pairs are passed, not key-value pairs. Deprecated
table.s­or­t(table [, comp])
Sort the elements of a table in-place. A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence.
table.i­ns­ert­(table, [pos,] value)
Insert a given value into a table. If a position is given insert the value before the element currently at that position.
table.r­em­ove­(table [, pos])
Remove an element from a table. If a position is specified the element at that the position is removed. The remaining elements are reindexed sequen­tially and the size of the table is updated to reflect the change. The element removed is returned by this function.
table.s­ort() example:
> t = { 3,2,5,1,4 }
> table.s­ort(t, functi­on(a,b) return a<b end)
> = table.c­on­cat(t, ", ")
1, 2, 3, 4, 5
 

String

string.byte(s [, i [, j]])
Return the numerical code the i-th through j-th character of the string passed.
string.ch­ar(i1, i2, ...)
Generate a string repres­enting the character numerical code passed as arguments.
string.fi­nd(s, pattern [, index [, plain]])
Find the first occurrence of the pattern in the string passed
string.fo­rmat(s, e1, e2, ...)
Create a formatted string from the format and arguments provided. This is similar to the printf­("fo­rma­t",...) function in C.
string.gs­ub(s, pattern, replace [, n])
Used simply it can replace all instances of the pattern provided with the replac­ement. A pair of values is returned, the modified string and the number of substi­tutions made. The optional fourth argument n can be used to limit the number of substi­tutions made
string.len(s)
Return the length of the string passed.
string.lo­wer(s)
Make all the upper case characters lower case.
string.up­per(s)
Make all the lower case characters upper case.
string.match (s, pattern [, index])
Extract substrings by matching patterns.
string.rep(s, n)
Generate a string which is n copies of the string passed concat­enated together.
string.re­ver­se(s)
Reverses a string.
string.sub(s, i [, j])
Return a substring of the string passed. The substring starts at i. If the third argument j is not given, the substring will end at the end of the string. If the third argument is given, the substring ends at and includes j.
All functions can be used directly in string by changing string. to s:, s being the string
Example:
string.re­ver­se(­"­Tes­t")

"­Tes­t":r­eve­rse­()"

Classes. Table based

local Person = {}
Person.__index = Person

function Person.new(name, surname)
  local self = setmetatable({}, Person)
  self.name = name
  self.surname = surname
  return self
end

function Person.setName(self, name)
  self.name = name
end

function Person.getName(self)
  return self.name
end

function Person.setSurname(self, surname)
  self.surname = surname
end

function Person.getSurname(self)
  return self.surname
end

return Person

-- Import with ClassName = require("classname")
-- Use with local i = ClassName.init(params)
Faster to create. Does not have private attributes

Classes. Closur­e/I­nstance Based

local function MyClass(init)
    local self = {
        public_field = 0
    }

    local private_field = init

    function self.foo()
        return private_field
    end

    function self.bar()
        private_field = private_field + 1
    end

    return self
end

return MyClass

-- Import with MyClass = require("MyClass")
-- Use with local i = MyClass(init)
Can have private attrib­utes. Slower to create
           
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          C Reference Cheat Sheet
          Roblox: General Scripting Cheat Sheet
          Roblox: CFrames Cheat Sheet