Here’s a Lua cheat sheet covering key aspects of the Lua programming language:
Hello World
print("Hello, Lua!")
Variables and Constants
-- Variables
local x = 10
local name = "John"
-- Constants
local PI = 3.14
Data Types
Primitive Types:
number
,string
,boolean
,nil
Tables:
local person = {name = "Alice", age = 30, isStudent = true}
Functions:
local function addNumbers(a, b)
return a + b
end
Control Flow
if-else:
local x = 10
if x > 5 then
print("Greater")
else
print("Lesser")
end
for loop:
for i = 1, 5 do
print(i)
end
while loop:
local i = 0
while i < 5 do
print(i)
i = i + 1
end
Functions
function greet(name)
return "Hello, " .. name .. "!"
end
Tables
local fruits = {"apple", "orange", "banana"}
fruits[4] = "grape"
Nil and Default Values
local variable = nil
local defaultValue = variable or "default"
String Manipulation
local greeting = "Hello"
local name = "Alice"
local message = greeting .. ", " .. name .. "!"
Coroutines
local function myCoroutine()
print("Coroutine started")
coroutine.yield()
print("Coroutine resumed")
end
local co = coroutine.create(myCoroutine)
coroutine.resume(co)
Modules
-- Module in "mymodule.lua"
local M = {}
function M.add(a, b)
return a + b
end
return M
Usage:
local mymodule = require("mymodule")
print(mymodule.add(3, 4))
This cheat sheet covers some fundamental aspects of Lua. Lua is known for its simplicity and embeddability, often used in scripting and game development. For more detailed information, refer to the official Lua documentation.