Skip to content

Instantly share code, notes, and snippets.

@zhum
Last active December 31, 2025 21:54
Show Gist options
  • Select an option

  • Save zhum/d3cc5adc20c5fac1e2da02748f8da107 to your computer and use it in GitHub Desktop.

Select an option

Save zhum/d3cc5adc20c5fac1e2da02748f8da107 to your computer and use it in GitHub Desktop.
Lua Cheat Sheet

LUA Cheat Sheet

Comments | Types | Standard functions | Tables | Exceptions | Functions | I/O | Regexp | Objects | System

Comments

--
or
--[[

--]]

Control

while cond do block end repeat block until cond if cond then block {elseif cond then block} [else block] end for var = start, fin, [, step] do block end -- var is CONST for var_1, ···, var_n in explist do body end -- var_X are CONT do ... end break

Types

local -- local variable, by default ALL variables are GLOBAL

Types: nil, boolean, number, string, userdata, function, thread, table

type(true)                -- "boolean"
tonumber(e [, base])      -- number or nil
tostring(e)               -- string
unpack (list [, i [, j]]) --> return list[i], list[i+1], ···, list[j]

Boolean operations: not and or

Number: 1 1.2 3e3 0xff

Operations: + - * / // (integer division) % (modulo) ^ (power)

Bitwise & | ~ (xor) >> << ~(unary NOT)

Comparision: < > <= >= == ~=

Math:

math.sin(math.pi / 2) --> 1.0
math.max(10.4, 7, -3, 20) --> 20
math.huge --> inf
math.floor(-3.3) --> -4
math.round(-3.3) --> -3
math.random()  --> [0,1)
math.tointeger(-258.0) --> -258

String: Immutable!! No encoding! Operations: .. (catenation) # (length)

[[]] or [===[]===] (BIG STRINGS, number of '=' should be the same)
tonumber("100101", 2)
tonumber(" 56   ")
tostring(10)
s = "[in brackets]"
string.sub(s, 2, -2) --> in brackets  (from 2 till -2 byte)
string.sub(s, 1, 1) --> [
string.sub(s, -1, -1) --> ]
string.char(97)  --> a
string.char(99, 100, 101) --> cde
string.byte("abc", 2)  -> 98
string.format("x = %d y = %d", 10, 20) --> x = 10 y = 20
string.format("x = %x", 200) --> x = c8
string.format("x = 0x%X", 200) --> x = 0xC8
string.format("x = %f", 200) --> x = 200.000000
utf8.len("résumé") --> 6
utf8.char(114, 233, 115, 117, 109, 233)  --> résumé
utf8.codepoint("résumé", 6, 7)           --> 109 233
utf8.codepoint(s, utf8.offset(s, 5))     --> 228

Standard functions

dofile ([filename])    -- execute filename or stdin as lua code
_G   -- read-only table of global variables
getfenv ([f]) -- Returns the current environment in use by the function.
              -- f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv
              -- If the given function is not a Lua function, or if f is 0, getfenv returns the global environment. The default for f is 1. 
setfenv (f, table) -- Sets the environment to be used by the given function.
                   -- f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv
                   -- setfenv returns the given function
                   -- As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values. 
rawequal (v1, v2)            -- no meta methods calls
rawget (table, index)        -- no meta methods calls
rawset (table, index, value) -- no meta methods calls

Tables

{}                          --> empty
x={"one","two"}             --> x[1] = "one", x[2] = "two"
a = {x = 10, 30, ["+"] = 4} --> a.x = 10; a["x"] = 10; a[1] = 30
t = {10, print, x = 12, k = "hi"}
for k, v in pairs(t) do     -- ipairs = index sorting
  print(k, v)
end
 --> 1 10
 --> k hi
 --> 2 function: 0x420610
 --> x 12

t = {10, 20, 30}; table.insert(t, 1, 15)  --> {15, 10, 20, 30}

unpack (tab [, i [, j]]) --  Returns the elements from the given table. This function is equivalent to
                         --  return tab[i], tab[i+1], ···, tab[j]
next (table [, index])   --  Allows a program to traverse all fields of a table. Returns next index.

Exceptions (kinda)

pcall (f, arg1, ···)
-- Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated
-- instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean)
-- which is true if the call succeeds without errors. In such case, pcall also returns all results from the call,
-- after this first result. In case of any error, pcall returns false plus the error message. 

error (message [, level]) -- Terminates the last protected function called and returns message as the error message

assert (v [, message]) -- raise error if v is false or nil

Functions

function foo2 () return "a", "b" end
x, y, z = 10, foo2()                       -- x=10, y="a", z="b"

function nonils (...)                      -- non-determined number of arguments
  local arg = table.pack(...)              -- ‘...’ can be passed further
  for i = 1, arg.n do                      -- number of args
    if arg[i] == nil then return false end -- access args
  end
  return true
end

v:name(args) is syntactic sugar for v.name(v, args)

select (index, ···) -- If index is a number, returns all arguments after argument number index
                    -- If string "#", select returns the total number of extra arguments it received

I/O

> print("hello", "Lua"); print("Hi")
  --> hello   Lua
  --> Hi
    
> io.write("hello", "Lua"); io.write("Hi", "\n")
  --> helloLuaHi

t = io.read("*all")         -- read the whole file
-- *line, *number, NN = read line, a number, up to NN chars
f=io.open("/etc/passwd", "r")
f:read()
-- f:write()
-- f:flush()
f:close()

io.lines([filename])  -- no filename = stdin
for line in io.lines(filename) do ... end

io.popen(prog [, mode]) -- mode = r, w
io.type(obj)            -- is obj a valid file handle? "file"/"closed file"/nil (nil = not a file handle)
file:seek([whence] [, offset]) -- whense = "set", "cur", "end"
file:setvbuf(mode [, size])    -- set buffering mode "no", "full", "line"
io.tmpfile()                   -- handle of empty new temp file

Regexp

Sym Meaning
. any
%a letters
%c control
%d digits
%l low case letters
%p punctuation
%s spaces
%u upper case letters
%w letters + digits
%x hex digits
%z \0
%bXY substring between BALANCED X and Y (e.g %b{})
( ) . % + - * ? [ ^ $ specials, should be escaped by %
+ 1 or more repetititons
* 0 or more repetititons, longest match
- like *, but SHOURTEST match (e.g. comment: /%*.-%*/)
? 0 or 1 repetititon
^ line start
$ line end
[%w_] letters + '_'
[^%s%p] NOT set (not spaces and punctuations)
[0-7] digits from 0 to 7
%W NOT set (not letters)
(...) capture
() (empty capture) returns POSITION in string, e.g. "flaaap" + "()aa()" -> 3, 5
beg, fin, match = string.find (s, pattern [, init [, plain]])    -- find pattern in s
-- beg/end = indexes, match = exact match, init = start search index, plain=true use EXACT match, not regexp

a, b, ... = string.match (s, pattern [, init]) -- return captures (or whole match if none), init = start index (def=1)

str = "12 {3{4 56} 78}"
x = string.match(str,"%b{}",5) --> example of %b. RETURNS '{4 56}'


new_s = string.gsub (s, pattern, repl [, n]) -- return s with all (or first n) pattern matches replaced
-- repl = string -> %0-9 replaced by captures
-- repl = table  -> FIRST capture is used as table key. No captures = whole match is a key
-- repl = func   -> call func with all captures (or whole match if there are none) as args

x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"

x = string.gsub("hello world", "%w+", "%0 %0", 1)
--> x="hello hello world"

x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"

x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"

x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
    return loadstring(s)()
    end)
--> x="4+5 = 9"

local t = {name="lua", version="5.1"}
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.1.tar.gz"

iter = string.gmatch (s, pattern) --> returns ITERATOR function, returning next match every call (or whole match every time)

Objects = tables+functions

lamp = {
  on = false
  turn_on = function(l) l.on = true end -- l = "self/this"
}
lamp.turn_on(lamp)      -- allowed
lamp["turn_on"](lamp)   -- allowed
lamp:turn_on()          -- common practice

function lamp:turn_off()
  self.on = false       -- better!
end

Literals

a = { 
  [f(1)] = g; -- a[f(1)] = g
  "x",        -- a[1] = "x"
  "y";        -- a[2] = "y"
  x = 1,      -- a[x] = 1
  f(x),       -- a[3] = f(x)
  [30] = 23;  -- a[30] = 23
  45          -- a[4] = 45
}

Reserved tables functions

  • __add(a, b), __sub(a, b), __div(a, b), __mul(a, b), __mod(a, b), __pow(a, b) -- arithmetic operations on tables
  • __unm(a) -- unary minus
  • __lt(a, b), __le(a, b), __eq(a, b) -- < <= ==
  • __len(a) -- "#a"
  • __concat(a, b) -- "a..b"
  • __call(a, …) -- "a()"
  • __index(a, i) -- "a[i]" in case when key i is missing
  • __newindex(a, i, v) -- "a[i] = v"
  • __gc(a) -- on garbage collection (element deletion)

Inheritance

Meta-table = parent table. All meta-table methods are available on childs. Meta-table can be updated on the fly.

childlamp = {
  brightness = 100
}
-- set meta-table
setmetatable(childlamp, lamp)
-- call parent methods!
childlamp:turn_on()
childlamp:turn_off()

getmetatable("") -- = meta-table of "string"
getmetatable(childlamp) -- = lamp

Table functions

  • table.concat (table [, sep [, i [, j]]]) Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.
  • table.insert (table, [pos,] value) Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.
  • table.maxn (table) Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.
  • table.remove (table [, pos]) Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.
  • table.sort (table [, comp]) Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

System

  • os.clock() Returns an approximation of the amount in seconds of CPU time used by the program.
  • os.date ([format [, time]]) If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following fields: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean). If format is not "*t", then date returns the date as a string, formatted according to the same rules as the C function strftime.
  • os.difftime (t2, t1) Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1.
  • os.execute ([command]) = C function system
  • os.exit ([code])
  • os.getenv (varname)
  • os.remove (filename) Can remove empty directories too
  • os.rename (oldname, newname) If this function fails, it returns nil, plus a string describing the error.
  • os.setlocale (locale [, category]) Sets the current locale of the program. locale is a string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored. If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string "C", the current locale is set to the standard C locale. When called with nil as the first argument, this function only returns the name of the current locale for the given category.
  • os.time ([table]) Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, see the os.date function). The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to date and difftime.
  • os.tmpname () Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. Use io.tmpfile for safety.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment