Catalog / Lua Cheatsheet
Lua Cheatsheet
A comprehensive cheat sheet for the Lua scripting language, covering syntax, data structures, control flow, functions, metatables, and common APIs.
Lua Basics
Syntax and Comments
Single-line comment: |
|
Multi-line comment: |
|
Variables: |
|
Assignment: |
|
Multiple assignment: |
|
Data Types
Nil: |
|
Boolean: |
|
Number: |
|
String: |
|
Table: |
Associative array (object) |
Function: |
First-class citizen |
Operators
Arithmetic: |
Relational: |
Logical: |
String Concatenation: |
Length Operator: |
Control Flow
Conditionals
|
Example: |
|
Loops
While Loop: |
|
For Loop (numeric): |
|
For Loop (generic): |
|
Repeat-Until Loop: |
|
Loop Control
Break: |
Exits the current loop. |
Return: |
Exits the current function. |
Tables and Functions
Tables
Table Creation: |
|
Adding Key-Value Pairs: |
|
Accessing Values: |
|
Arrays (Tables with Numeric Indices): |
|
Functions
Function Definition: |
|
Calling a Function: |
|
Anonymous Functions: |
|
Variable Arguments: |
|
Scope
Global: |
Accessible everywhere. |
Local: |
Accessible only within its scope (e.g., function or block). |
Metatables and Object Orientation
Metatables
Setting a Metatable: |
|
Common Metamethods: |
|
Example: |
|
Object Orientation
Creating a Class: |
|
Constructor: |
|
Methods: |
|
Usage: |
|
Common APIs
String Library
string.len(s): Returns the length of the string |
string.sub(s, i, j): Extracts a substring from |
string.find(s, pattern, init, plain): Searches for the first occurrence of |
string.gsub(s, pattern, repl, n): Replaces occurrences of |
string.format(formatstring, …): Returns a formatted string using the given format string and arguments. |
string.upper(s), string.lower(s): Converts the string |
Table Library
table.insert(t, pos, value): Inserts |
table.remove(t, pos): Removes the element at position |
table.sort(t, comp): Sorts the elements of table |
table.concat(t, sep, i, j): Concatenates the strings in table |
Math Library
math.random(m, n): Returns a pseudo-random number. If called without arguments, returns a float between 0 and 1. If called with two integer arguments |
math.abs(x): Returns the absolute value of |
math.floor(x), math.ceil(x): Returns the largest integer less than or equal to |
math.sqrt(x): Returns the square root of |
math.sin(x), math.cos(x), math.tan(x): Trigonometric functions (x in radians). |
math.pi: The value of pi. |