Lua Quick Reference
DR
Posted on January 5, 2024
Quick Links
Basics
Console Output & Comments
print("Hello, world!") -- This is a comment.
Variables
local a = "String type"
b = true -- global
c, d = 5, nil
print(type(c), type(d)) -- number nil
Strings
a = "Double"
b = 'Single'
c = [[
multiline
string
]]
string.upper(a) -- DOUBLE
string.lower(a) -- double
string.reverse(b) -- elgniS
string.len(b) -- 6
#b -- 6
a .. b -- DoubleSingle
Operators
Arithmetic
a, b = 10, 5
a + b -- 15
a - b -- 5
a * b -- 50
a / b -- 2
a ^ b -- 100000.0
a % b -- 0
-a -- -10
Relational
a, b = 4, 6
a == b -- false
a ~= b -- true
a > b -- false
a < b -- true
a <= b -- false
a >= b -- true
Logical
a, b = true, false
a and b -- false
a or b -- true
not b -- true
Conditionals
if condition then
statements()
elseif other_condition then
statements()
else
statements()
end
Loops
while
loop
i = 0
while i < 10
do
print(i)
i = i + 1
end -- returns 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for
loop
for i = 0, 10, 1
do
print(i)
end -- returns 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
repeat
loop
i = 0;
repeat
print(i)
i = i + 1
until i > 10 -- returns 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
break
statement
for i = 10, 0, -1
do
print(i)
if i == 5 then
break
end
end -- returns 10, 9, 8, 7, 6, 5
Functions
function average(num1, num2)
return (num1 + num2) / 2
end
print(average(10, 20)) -- 15.0
Tables
fruits = {"Banana", "Orange"}
print(fruits[1]) -- Banana
-- Removing elements
fruits[3] = "Apple"
table.remove(fruits) -- Apple
print(fruits[3]) -- nil
table.remove(fruits, 1) -- Banana
print(fruits[1]) -- Orange
print(#fruits) -- 1
-- Inserting elements
table.insert(fruits, "Mango")
table.insert(fruits, 2, "Papaya")
print(fruits[2]) -- Papaya
print(#fruits) -- 3
table.concat(fruits, " and ") -- Orange and Papaya and Mango
table.sort(fruits)
for key, value in ipairs(fruits) do
print(key, value)
end
--[[
1 Mango
2 Orange
3 Papaya
]]
Files
Implicit
-- Writing
file = io.open("test.txt", "w")
io.output(file)
io.write("This creates a file and writes this line at the top!")
io.close(file) -- true
-- Reading
file = io.open("test.txt", "r")
io.input(file)
print(io.read()) -- This creates a file and writes this line at the top!
io.close(file) -- true
-- Appending
file = io.open("test.txt", "a")
io.output(file)
io.write("Appending to the test file!")
io.close(file) -- true
Explicit
-- Writing
file = io.open("test.txt", "w")
file:write("This creates a file and writes this line at the top!")
file:close() -- true
-- Reading
file = io.open("test.txt", "r")
file:read() -- This creates a file and writes this line at the top!
file:close() -- true
-- Appending
file = io.open("test.txt", "a")
file:write("Appending to the test file!")
file:close() -- true
💖 💪 🙅 🚩
DR
Posted on January 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024