Please enable JavaScript to use CodeHS

Lua Documentation

Basics

Printing to Console

-- Use the print() function to print text to the console
print("Hello")
print("world.")
-- Result:
-- Hello
-- world.

-- Concantenate strings and variables using ".." 
local species = "Martian"
print("Greetings " .. species)
-- Result:
-- Greetings Martian

Comments

We use comments to describe what specific blocks of code do in plain language (not code). Comments are not actually executed. Instead, they are just there to help us read the code.

We can make multiline comments with "--[[comment]]" and single line comments with "--".

--[[
This program will ask the user for two numbers.
Then it will print their sum.
]]
print("Enter a number: )
local numberOne = tonumber(io.read())
print("Enter a second number: )
local numberTwo = tonumber(io.read())
print("Sum: " .. (numberOne + numberTwo))

-- This program adds 1 and 2
local added = 1 + 2
print(added)

Variables

We use variables to store values. We can use and alter these values throughout our program.

-- Initialize a variable
local myVarName = 5

-- Assign a new value to an existing variable
myVarName = 10

-- Print the value of a variable
print(myVarName)    -- prints "10"
print("The value is: " .. myVarName)    -- prints "The value is 10"

User Input

We can use input from the user to control our code using the io.read() command. First, use a print statement to ask the user a prompt. Then, use io.read() to collect the input from the user. We can store the input in a variable so that we can use the input in our program.

Note that values input by the user are stored as a string.

-- This program gets the name from the user
print("What is your name?")
local name = io.read()
print("Hello" .. name .. "!")

-- Use the tonumber() function to convert user input to a number
print("Enter a number: ")
local num = tonumber(io.read())

Math

Use mathematical operators to alter values.

-- Operators:
+	Addition
-	Subtraction
*	Multiplication
/	Division
^   Exponentiation
%	Modulus (Remainder)
()	Parentheses (For order of operations)

-- Examples
var z = x + y
var w = x * y

-- Increment (add one)
x = x + 1

-- Decrement (subtract one)
x = x - 1

-- Exponentiation
local squared = 5 ^ 2
print(squared)   -- prints 25

-- Modulus
local z = 10 % 4    -- 10 / 4 = 2 remainder 2
print(z)            -- prints 2

Random Numbers

You can generate random numbers using the math.random(low, high) command.

-- You need to include this command to enable randomness
math.randomseed(os.time())

-- Generates a random integer between low and high, inclusive
math.random(low, high)

-- Example: This simulates rolling a 6-sided die
local roll = math.random(1, 6)

Functions

A function is a block of reusable code that is used to perform a single task. We use functions in our code to break our program into smaller parts, make our program more readable, and to avoid creating repetitive code.

Naming Functions: You should name functions based on what they do. Names should also use the lower camel case convention.

Defining Functions: Defining a function is the same as creating a function. Inside the function definition, you tell the computer what commands to execute when the function is called.

Calling Functions: Calling a function is telling the computer to execute the code inside of the function definition. Call a function by writing the function name followed by parentheses. Important note: In Lua, you have to define a function before you call it!

-- Defines a function that adds two numbers together
local num1 = 10
local num2 = 12
local function addNumbers()
    local sum = num1 + num2
    print("Sum: " .. sum)
end

-- Calls the function
addNumbers()
-- Result: prints "Sum: 22"

Returning Values in Functions

We can use the return command to have a function give a value back to the code that called it.

-- We add a return statement in order to use the value of the 
-- sum variable in our program
local function addNumbers()
    local sum = num1 + num2
    return sum
end

local num1 = 10
local num2 = 12
local x = addNumbers() 
-- x is assigned the value returned by the addNumbers function (22)

Using Parameters with Functions

We can use parameters to input information into a function. This makes our functions more general and versatile. To create parameters, you include them in the function definition. Then, when you call the function, you need to include arguments, or values for the parameters.

-- In this program, parameters are used to input two numbers
local function addNumbers(numOne, numTwo)
    local sum = numOne + numTwo
    return sum
end

-- We call the function with arguments, 
-- or values inside the parentheses
-- This program will print '7'
print(addNumbers(3, 4))

Control Structures

Booleans

A Boolean is either a true or false value. You create a boolean variable by assigning it the value of either true or false. Note that there are no quotation marks because a boolean value is not a string.

local myBoolean = true
local anotherBoolean = false

Logical Operators

Use logical operators to check multiple conditions at once or one condition out of multiple. Logical operators evaluate to booleans.

--  Not Operator
local y = true
local x = not y 	-- x is assigned the opposite of y, or false

-- And Operator: Evaluates to true if all operands are true
local x = true
local y = false
local z = x and y   -- z is assigned the value of false

-- Or Operator: Evaluates to true if at least one operand is true
local x = true
local y = false
local z = x or y    -- z is assigned the value of true

-- You can combine many booleans!
local x = true
local y = false
local z = true
local lotsOfBooleans = x and (y or z)   -- evaluates to true

Comparison Operators

Comparison operators compare the operands on either side of the operator and decide their relationship. Comparison operators evaluate to booleans.

x == y      -- is x equal to y
x ~= y      -- is x not equal to y
x > y       -- is x greater than y
x >= y      -- is x greater than or equal to y
x < y       -- is x less than y
x <= y      -- is x less than or equal to y

--Example:
local grade = 80
local isPassing = grade >= 70 
print(isPassing)    -- Prints true because 80 is greater than 70

If/Else Statements

Use an if/else statement to tell the computer to make a decision between multiple conditions. If the first condition is false, the computer will skip to the next condition until it finds one that is true. If no conditions are true, the commands inside the else block will be performed.

-- If Statement
if BOOLEAN_EXPRESSION then
	-- code to execute if true
end

-- If/Else Statement
if BOOLEAN_EXPRESSION then
	-- code to execute if true
 else 
	-- code to execute if false
end

-- Some example conditionals:

-- Checks if a number is negative
local x = -1
if x < 0 then
	print("x is negative.")
end

-- Checks if a color is a primary color
local color = "purple"
if color == "red" or color == "blue" or color == "yellow" then
	print("Primary color.")
else
	print("Not a primary color.")
end

For Loops

Use a for loop to repeat a block of code a fixed number of times.

-- General for loop structure:
for i = 1, COUNT, INCREMENT do
    -- Code to repeat COUNT number of times
end

-- This for loop will print "Hello" fives times 
for i = 1, 5 do
	print("Hello")
end

-- This example prints numbers 0-10
for i = 0, 10 do
	print(i)
end

-- You can also include an increment value
-- This prints the odd numbers from 1-11
for i = 1, 11, 2 do
    print(i)
end

While Loops

While loops repeat a block of code until a condition becomes false.

-- General while loop structure:
while BOOLEAN_EXPRESSION do
	-- code to repeat until
	-- BOOLEAN_EXPRESSION is false
end

-- This while loop counts down from 15 to 10
local i = 15
while i > 9 do
	print(i)
	i = i - 1
end

-- Use a break statement to exit out of a loop
while true do
    -- code to repeat
    if condition then
        break
    end
end

Data Structures

Arrays

An array is a way to store multiple values or data under one variable name. In Lua, arrays start with an index of 1. You can add items, remove items, and alter items within an array.

-- Create an empty array
local arr = {}

-- Create an array with values
local arr = {1, 2, 4}

-- An array can have any type (x is a variable)
local arr = [4, "hello", x]

-- Access an element in an array with arr[index]
local firstElem = arr[1]

-- Assign an index in an array a new value
arr[3] = 9

-- Add an item to an array as the last item
table.insert(arr, item)

-- You can also specify where to add the item in the list
table.insert(arr, index, item)

-- Remove the last item in an array
table.remove(arr)

-- Remove an item at a specific index
table.remove(arr, index)

-- Length of an array
local length = #arr

-- Loop over an array
for i = 1, #arr do
    local item = arr[i]
    print(item)
end