my personal notes
8.0 kB · 290 lines
Markdown
at main

📚 Lua Documentation for Absolute Beginners #

Welcome to Lua! This guide will introduce you to the core concepts of the Lua programming language in a simple, straightforward way. Lua is often used for scripting game engines (like Roblox) and extending applications, thanks to its lightweight and fast nature.

1. The Very Basics #

Comments #

Comments are lines of code ignored by the computer. They are essential for explaining what your code does.

Type Syntax Description
Single-line -- This is a comment Used for short explanations.
Multi-line --[[ This is a comment that spans multiple lines. --]] Used for longer explanations or temporarily disabling a block of code.

Variables #

A variable is like a named container that holds a value. You don't need to specify the type of value it holds.

Creating a variable (Assignment):

-- Create a variable named 'age' and assign the number 30 to it.
age = 30

-- Create a variable named 'name' and assign the string "Alice" to it.
name = "Alice"

-- Create a variable for a decimal number
pi = 3.14159

Local vs. Global Variables:

By default, any variable you create is Global (accessible everywhere). However, it's best practice to make variables Local (only accessible within the block of code they are defined in) to prevent conflicts and improve performance.

-- Global variable (accessible anywhere in the script)
global_message = "Hello"

-- Local variable (good practice!)
local local_score = 100

2. Fundamental Data Types #

Lua has eight basic types, but as a beginner, you'll mainly use the first four, plus the critical table type.

Type Description Example
nil Represents the absence of a value. If a variable exists but hasn't been assigned anything, it's nil. local x = nil
boolean Represents truth: either true or false. local is_game_over = true
number Represents all numbers (integers and floating-point/decimals). local count = 5, local price = 19.99
string A sequence of characters (text). Can use single or double quotes. local greeting = "Hi there"
table The most important type! It is the only complex data structure in Lua, used to create arrays, dictionaries, and custom objects. See Section 3
function A block of code designed to perform a particular task. See Section 5
userdata Data from C/C++ (You usually won't deal with this directly). N/A
thread Used for parallel execution (Advanced topic). N/A

3. Tables (The Foundation of Lua) #

In most languages, you have separate concepts for arrays (lists) and dictionaries (key-value maps). In Lua, you only have the table to do both!

3.1. Creating a Table #

You create a table using curly braces {}.

-- An empty table
local settings = {}

3.2. Tables as Arrays (Lists) #

Arrays store data in a numbered sequence. Crucially, Lua arrays start counting from 1, not 0 like many other languages.

-- Array/List (Uses numbered keys: 1, 2, 3...)
local colors = {"Red", "Green", "Blue"}

-- Accessing values (Remember: Lua starts at 1)
print(colors[1]) -- Output: Red

-- Changing values
colors[3] = "Yellow"
print(colors[3]) -- Output: Yellow

-- Adding to the end of a list (using the `#` length operator)
colors[#colors + 1] = "Purple"
print(colors[4]) -- Output: Purple

-- Getting the length
print(#colors) -- Output: 4

3.3. Tables as Dictionaries (Maps) #

Dictionaries store data using descriptive names (strings) instead of numbers as keys.

-- Dictionary (Uses string keys)
local player = {
    name = "Hero",
    health = 100,
    level = 5
}

-- Accessing values using dot notation (most common)
print(player.name)    -- Output: Hero

-- Accessing values using bracket notation (useful for keys with spaces)
print(player["health"]) -- Output: 100

-- Adding a new key-value pair
player.is_alive = true

3.4. Tables as Objects (Mixed Use) #

The real power of Lua is that you can mix arrays and dictionaries in the same table:

local game_data = {
    -- Array part (1, 2, 3, ...)
    "Map Loaded",
    "Player Joined",
    -- Dictionary part (string keys)
    status = "Active",
    time = 90
}

4. Control Structures #

Control structures allow your code to make decisions or repeat actions.

If/Else Statements (Making Decisions) #

local score = 85

if score >= 90 then
    print("A: Excellent!")
elseif score >= 70 then
    -- 'elseif' is a single word in Lua
    print("B: Good job.")
else
    print("C: Needs practice.")
end

Loops (Repeating Actions) #

A. While Loop (Repeat until condition is false) #

local countdown = 3

while countdown > 0 do
    print(countdown)
    countdown = countdown - 1
end
print("Blast Off!")

B. Numeric For Loop (Count from a start number to an end number) #

This loop runs a fixed number of times.

-- Syntax: for variable = start, end, step do ... end
for i = 1, 5 do
    print("Counting: " .. i) -- '..' concatenates (joins) strings
end
-- Output: 1, 2, 3, 4, 5

C. Generic For Loop (Iterating over tables) #

This is the standard way to look at every item in a list or dictionary.

  • For Arrays/Lists (using ipairs): Iterates numerically (1, 2, 3...).

    local items = {"Sword", "Shield", "Potion"}
    for index, value in ipairs(items) do
        print(index .. ": " .. value)
    end
    -- Output: 1: Sword, 2: Shield, 3: Potion
    
  • For Dictionaries/Maps (using pairs): Iterates over all key-value pairs.

    local stats = {HP = 100, MP = 50, Strength = 20}
    for key, value in pairs(stats) do
        print(key .. " is " .. value)
    end
    -- Output: HP is 100, MP is 50, Strength is 20 (Order may vary)
    

5. Functions #

A function is a reusable block of code that performs a specific task. They are essential for keeping your code organized.

Defining a Function #

You must use the function keyword to define one.

-- Define a function named 'greet'
function greet(name)
    -- This code runs when the function is called
    print("Hello, " .. name .. "!")
end

-- Call the function
greet("Charlie") -- Output: Hello, Charlie!

Functions that Return Values #

You use the return keyword to send data back from a function. Lua functions can return multiple values, which is a powerful feature!

function calculate_area(width, height)
    local area = width * height
    return area
end

local room_area = calculate_area(5, 10)
print("The area is: " .. room_area) -- Output: The area is: 50

Multiple Returns #

function get_player_stats()
    return "Warrior", 50, 80
end

-- Assign the multiple returned values to multiple variables
local job, strength, agility = get_player_stats()

print("Job: " .. job)         -- Output: Job: Warrior
print("Strength: " .. strength) -- Output: Strength: 50

6. A Simple Program Example #

This program shows how to combine variables, tables, and functions.

-- 1. Global constants (using ALL CAPS for convention)
local REQUIRED_SCORE = 50

-- 2. Define the main game table/object
local player = {
    name = "Newbie",
    current_score = 45,
    is_admin = false
}

-- 3. Define a function to check for victory
function check_victory(p)
    -- Check if the player is an admin (automatic win) OR has the required score
    if p.is_admin or p.current_score >= REQUIRED_SCORE then
        return true, "Congratulations, " .. p.name .. "! You won."
    else
        return false, "Keep going! Need " .. (REQUIRED_SCORE - p.current_score) .. " more points."
    end
end

-- 4. Execute the logic
print("--- Game Start ---")

-- Get the results from the function call (multiple returns)
local did_win, message = check_victory(player)

-- Use the results to print the outcome
if did_win then
    print("VICTORY!")
else
    print("TRY AGAIN")
end

-- Always print the message
print(message)