No history yet

Introduction to Lua

Meet Lua

Lua is a scripting language known for being lightweight and easy to embed in other applications. This flexibility makes it a popular choice for game development, where it's often used to control character behavior, manage game events, and define user interfaces.

Lua is a lightweight, high-level, programming language designed to be embedded in other applications and is usually a popular choice for game scripting because it's easy to learn and use.

Its syntax is simpler than many other languages. Comments, which are notes for humans that the computer ignores, start with two hyphens.

-- This is a single-line comment.

--[[ 
This is a multi-line comment.
It can span several lines.
]]

Like other languages, you use variables to store information. Think of them as labeled boxes where you can keep data. You create a variable by giving it a name and assigning it a value.

local score = 100
local playerName = "Alex"

The local keyword makes the variable accessible only within its current block of code. It's a good practice to use local variables whenever possible to avoid accidentally changing values elsewhere in your script.

Data Types

Lua handles several types of data. The most common ones are numbers, strings (text), booleans (true/false), and nil.

Data TypeDescriptionExample
numberAny numeric value, including integers and decimals.10, 3.14
stringA sequence of characters, enclosed in quotes."Hello, world!"
booleanRepresents logical values.true, false
nilRepresents the absence of a value.local emptyVariable

nil

noun

A special type that represents the absence of a useful value. A variable that has not been assigned a value is nil.

The most powerful data structure in Lua is the table. A table can hold a collection of values, and you can access those values using keys. It can act as an array, a dictionary, or even an object.

In Lua, tables are the only built-in data structure. They can be used to represent everything from simple lists to complex records.

Here’s how you can create a simple list-style table, also called an array.

-- An array of numbers
local highScores = {1500, 1200, 950}

-- Accessing an element (indices start at 1)
print(highScores[1]) -- Outputs: 1500

Notice that array indices in Lua start at 1, not 0 like in many other programming languages.

You can also use tables as dictionaries (or hash maps), with custom keys.

-- A dictionary-style table
local player = {
  name = "Alex",
  level = 5,
  isOnline = true
}

-- Accessing values using keys
print(player.name)      -- Outputs: Alex
print(player["level"]) -- Outputs: 5

Control Flow

Control flow statements let you direct the execution of your script. You can make decisions with if statements and repeat actions with loops.

An if statement runs a block of code only if a certain condition is true. You can add elseif and else to handle other conditions.

local health = 75

if health > 90 then
  print("Full health!")
elseif health > 50 then
  print("Doing okay.")
else
  print("Health is low!")
end

Loops are for repeating a task. A while loop continues as long as its condition is true.

local countdown = 3

while countdown > 0 do
  print(countdown)
  countdown = countdown - 1
end

print("Liftoff!")

A for loop is great for running code a specific number of times or for iterating over the elements in a table.

-- Numeric for loop
for i = 1, 3 do
  print("Loop number: " .. i)
end

-- Generic for loop for tables
local fruits = {"apple", "banana", "cherry"}
for index, value in ipairs(fruits) do
  print(index, value)
end

In the table loop, ipairs is an iterator that goes through the numeric indices of a table in order.

Functions and Modules

Functions are reusable blocks of code that perform a specific task. You define a function to organize your code and avoid repetition.

-- Define a function that takes two numbers and returns their sum
function add(a, b)
  return a + b
end

-- Call the function
local result = add(5, 3)
print(result) -- Outputs: 8

As scripts get larger, you can organize related functions into separate files called modules. A module is just a Lua file that returns a table containing the functions you want to share. This helps keep your code tidy and reusable across different parts of a project.

Imagine you have a file named math_utils.lua:

-- math_utils.lua
local utils = {}

function utils.add(a, b)
  return a + b
end

function utils.subtract(a, b)
  return a - b
end

return utils

You can then use these functions in another file by using the require keyword.

-- main.lua
local myMath = require("math_utils")

local sum = myMath.add(10, 5) -- 15
local difference = myMath.subtract(10, 5) -- 5

print(sum, difference)

With these building blocks, you can start writing simple yet powerful scripts in Lua.

Time to check what you've learned.

Quiz Questions 1/6

What is the primary purpose of the local keyword when declaring a variable in Lua?

Quiz Questions 2/6

In Lua, array indices traditionally start at 1, not 0.

That covers the core concepts of Lua. You now have a solid foundation for scripting.