lua basic
lua basic
and examples. You can copy and paste this into a PDF or document to follow along as you
learn.
1. Introduction to Lua
What is Lua?
Basic Syntax:
• Lua is case-sensitive.
-- This is a comment
Variables
Data Types
1. String – Text data.
3. Operators
Arithmetic Operators
local a, b = 5, 2
print(a + b) -- Addition
print(a - b) -- Subtraction
print(a * b) -- Multiplication
print(a / b) -- Division
print(a % b) -- Modulus
print(a ^ b) -- Exponentiation
Relational Operators
print(5 == 2) -- false
Logical Operators
4. Control Structures
if-else Statement
local age = 18
print("Adult")
else
print("Minor")
end
for Loop
for i = 1, 5 do
print("Value: " .. i)
end
while Loop
local count = 1
count = count + 1
end
repeat-until Loop
local i = 1
repeat
print("Repeat: " .. i)
i=i+1
until i > 3
5. Functions
Defining Functions
function greet(name)
end
Anonymous Functions
return a + b
end
Arrays
for i = 1, #fruits do
print(fruits[i])
end
local person = {
name = "Alice",
age = 25
Iterating Tables
local mt = {
__add = function(a, b)
end
setmetatable(obj, mt)
setmetatable(obj2, mt)
8. Error Handling
Using pcall
end)
9. Advanced Concepts
Coroutines
local co = coroutine.create(function()
for i = 1, 3 do
print("Step: " .. i)
coroutine.yield()
end
end)
coroutine.resume(co)
coroutine.resume(co)
Modules
myModule.lua
local myModule = {}
function myModule.sayHello(name)
end
return myModule
Main File
local time = 10
time = time - 1
end
print("Game Over!")
Key Takeaways