Skip to main content

Lua Cheatsheet

Pitfalls to Avoid When Learning Lua

  • Array indices start from 1 (unlike C, JavaScript, and other languages where they start from 0)
  • string.len does not return the number of characters in a string but the number of bytes
  • All uninitialized variables are nil, and assigning nil to a value in a table removes it from the table
  • Only nil and false are logically false; all other values, including 0, are logically true
  • Strings and numbers are automatically converted when performing mathematical operations or comparisons, e.g., a = '1' + 2
  • Two floating-point numbers (numbers with decimals) cannot be compared using the equality operator ==, e.g., if 89.7 == (3 * 29.9) then is incorrect
  • A floating-point number that can be fully represented as an integer is equal to its corresponding integer, e.g., 1.0 == 1

Common Runtime Errors

Error Message FragmentCauseSolution
attempt to perform arithmetic on aAttempted to perform arithmetic (+, -, *, /) on a non-numeric valueCheck if all inputs for arithmetic operations are numbers
attempt to compareAttempted to perform comparison (>, <, >=, <=) on invalid valuesCheck if both inputs for comparison operations are valid for comparison
attempt to concatenate aAttempted to concatenate (..) a non-string valueEnsure both values being concatenated are strings
attempt to call aAttempted to call a variable that is not a functionEnsure the variable being called is a function
attempt to index aAttempted to index (subscript operation) a non-table variableEnsure the variable being accessed as an array or associative array is a table
attempt to yield across a C-call boundaryAttempted to yield in a non-yieldable call blockWhen using require, ensure the required module does not call yieldable functions (marked with an exclamation mark in the manual) before returning. Also, avoid using yieldable functions in functions with C callbacks (marked with an exclamation mark in the manual).
invalid order function for sortingInvalid sorting function, usually due to unclear sorting logicDefine clear sorting rules when calling the sorting function to avoid contradictory rules (e.g., a > b and a < b both being true)
bad argument #1 to 'xxx' (number expected, got nil)The first argument to a function is of the wrong type, expecting a number but got nilFix the argument and pass the correct value
bad argument #2 to 'xxx' (number has no integer representation)The second argument to a function cannot be converted to an integerFix the argument and pass the correct value
bad argument #3 to 'xxx'The third argument to a function is invalidFix the argument and pass the correct value

Usage of os.date

FormatExampleDescriptionResult
%Y-%m-%d %H:%M:%Sos.date("%Y-%m-%d %H:%M:%S", 1487356783)A common date-time format2017-02-18 02:39:43
%Y-%m-%dos.date("%Y-%m-%d", 1487356783)A common date format2017-02-18
%aos.date("%a", 1487356783)Abbreviated weekday nameSat
%Aos.date("%A", 1487356783)Full weekday nameSaturday
%bos.date("%b", 1487356783)Abbreviated month nameFeb
%Bos.date("%B", 1487356783)Full month nameFebruary
%cos.date("%c", 1487356783)Standard date-time stringSat Feb 18 02:39:43 2017
%dos.date("%d", 1487356783)Day of the month, range 01 - 3118
%Hos.date("%H", 1487356783)Hour in 24-hour format, range 00 - 2302
%Ios.date("%I", 1487356783)Hour in 12-hour format, range 01 - 1202
%jos.date("%j", 1487356783)Day of the year, range 001 - 366049
%Mos.date("%M", 1487356783)Minute, range 00 - 5939
%mos.date("%m", 1487356783)Month, range 01 - 1202
%pos.date("%p", 1487356783)AM or PMAM
%Sos.date("%S", 1487356783)Second, may include leap second, range 00 - 6143
%wos.date("%w", 1487356783)Day of the week (Sunday is 0), range 0 - 66
%xos.date("%x", 1487356783)Standard date string02/18/17
%Xos.date("%X", 1487356783)Standard time string02:39:43
%yos.date("%y", 1487356783)Year without century17
%Yos.date("%Y", 1487356783)Year with century2017
%%os.date("%%", 1487356783)Percent sign%

Usage of the string Library

Basic Functions

FunctionDescriptionExampleResult
string.lenCalculate the length of a stringstring.len("abcd")4
string.repReturn n copies of string sstring.rep("abcd", 2)abcdabcd
string.lowerReturn the string in all lowercasestring.lower("AbcD")abcd
string.upperReturn the string in all uppercasestring.upper("AbcD")ABCD
string.formatFormat a stringstring.format("the value is: %d", 4)the value is: 4
string.subExtract a substring from a stringstring.sub("abcd", 2)bcd
string.sub("abcd", -2)cd
string.sub("abcd", 2, -2)bc
string.sub("abcd", 2, 3)bc
string.findFind a substring in a string (returns position)string.find("cdcdcdcd", "ab")nil
string.find("cdcdcdcd", "cd")1 2
string.find("cdcdcdcd", "cd", 7)7 8
string.matchFind a substring in a string (returns content)string.match("cdcdcdcd", "ab")nil
string.match("cdcdcdcd", "cd")cd
string.gsubReplace a substring in a stringstring.gsub("abcdabcd", "a", "z")zbcdzbcd 2
string.gsub("aaaa", "a", "z", 3)zzza 3
string.byteReturn the integer representation of a characterstring.byte("ABCD", 4)68
string.charConvert integer numbers to characters and concatenate themstring.char(97, 98, 99, 100)abcd

Basic Patterns

Character ClassDescriptionExampleResult
.Any characterstring.find("", ".")nil
%sWhitespace characterstring.find("ab cd", "%s%s")3 4
%SNon-whitespace characterstring.find("ab cd", "%S%S")1 2
%pPunctuation characterstring.find("ab,.cd", "%p%p")3 4
%PNon-punctuation characterstring.find("ab,.cd", "%P%P")1 2
%cControl characterstring.find("abcd\t\n", "%c%c")5 6
%CNon-control characterstring.find("\t\nabcd", "%C%C")3 4
%dDigitstring.find("abcd12", "%d%d")5 6
%DNon-digitstring.find("12abcd", "%D%D")3 4
%xHexadecimal digitstring.find("efgh", "%x%x")1 2
%XNon-hexadecimal digitstring.find("efgh", "%X%X")3 4
%aLetterstring.find("AB12", "%a%a")1 2
%ANon-letterstring.find("AB12", "%A%A")3 4
%lLowercase letterstring.find("ABab", "%l%l")3 4
%LUppercase letterstring.find("ABab", "%L%L")1 2
%uUppercase letterstring.find("ABab", "%u%u")1 2
%UNon-uppercase letterstring.find("ABab", "%U%U")3 4
%wAlphanumeric characterstring.find("a1()", "%w%w")1 2
%WNon-alphanumeric characterstring.find("a1()", "%W%W")3 4

Escape Character %

Character ClassDescriptionExampleResult
%Escape characterstring.find("abc%..", "%%")4 4
string.find("abc..d", "%.%.")4 5

Using [] to Represent Character Sets, - for Ranges, and ^ for Complement of Character Sets

Character ClassDescriptionExampleResult
[01]Match binary digitsstring.find("32123", "[01]")3 3
[AB][CD]Match AC, AD, BC, BDstring.find("ABCDEF", "[AB][CD]")2 3
[[]]Match a pair of square brackets []string.find("ABC[]D", "[[]]")4 5
[1-3]Match digits 1, 2, 3string.find("312", "[1-3][1-3][1-3]")1 3
[b-d]Match letters b, c, dstring.find("dbc", "[b-d][b-d][b-d]")1 3
[^%s]Match any non-whitespace characterstring.find(" a ", "[^%s]")3 3
[^%d]Match any non-digit characterstring.find("123a", "[^%d]")4 4
[^%a]Match any non-letter characterstring.find("abc1", "[^%a]")4 4

Using () for Capturing

Character ClassDescriptionExampleResult
()Capture stringstring.find("12ab", "(%a%a)")3 4 ab
string.find("ab12", "(%d%d)")3 4 12

Pattern Modifiers

ModifierDescriptionExampleResult
+Matches 1 or more occurrences, matches the moststring.find("aaabbb", "(a+b)")1 4 aaab
string.find("cccbbb", "(a+b)")nil
-Matches 0 or more occurrences, matches the leaststring.find("zzxyyy", "(xy-)")3 3 x
string.find("zzzyyy", "(x-y)")4 4 y
*Matches 0 or more occurrences, matches the moststring.find("mmmnnn", "(m*n)")1 4 mmmb
string.find("lllnnn", "(m*n)")4 4 n
?Matches 0 or 1 occurrencestring.find("aaabbb", "(a?b)")3 4 ab
string.find("cccbbb", "(a?b)")4 4 b

Common Usage of string.match

DescriptionExampleResult
Match Chinese charactersstring.match("男女abc123", "([^%w%p]+)")男女
Match English lettersstring.match("男女abc123", "(%a+)")abc
Match digitsstring.match("男女abc123", "(%d+)")123
Match English letters and digitsstring.match("男女abc123", "(%w+)")abc123

Usage of the math Library

Function NameDescriptionExampleResult
math.piPimath.pi3.1415926535898
math.absAbsolute valuemath.abs(-2012)2012
math.ceilCeilingmath.ceil(9.1)10
math.floorFloormath.floor(9.9)9
math.maxMaximum valuemath.max(2, 4, 6, 8)8
math.minMinimum valuemath.min(2, 4, 6, 8)2
math.sqrtSquare rootmath.sqrt(65536)256.0
math.modfInteger and fractional partsmath.modf(20.12)20 0.12
math.randomseedSet random seedmath.randomseed(os.time())
math.randomRandom numbermath.random(5, 90)
math.radDegrees to radiansmath.rad(180)3.1415926535898
math.degRadians to degreesmath.deg(math.pi)180.0
math.expExponential functionmath.exp(4)54.598150033144
math.logNatural logarithmmath.log(54.598150033144)4.0
math.sinSinemath.sin(math.rad(30))0.5
math.cosCosinemath.cos(math.rad(60))0.5
math.tanTangentmath.tan(math.rad(45))1.0
math.asinArcsinemath.deg(math.asin(0.5))30.0
math.acosArccosinemath.deg(math.acos(0.5))60.0
math.atanArctangentmath.deg(math.atan(1))45.0