DE EN FR ES IT CZ

3. Lua in ten minutes

Lua in ten minutes

Four wooden blocks with symbols: dice, tick, fork in the road, circular arrow

Lua is a small, very readable language. Visionaire Studio uses Lua 5.4. These building blocks are enough to get started.

Variables and values

local attempts = 0          -- number
local name = "Pia"          -- text, in quotes
local open = false          -- boolean: true or false
local nothing = nil         -- "no value"

-- comments start with two minus signs

local means: the variable only exists in this script or this function. Only leave out local if a variable really should be visible everywhere.

Decisions

if attempts == 0 then
  print("First attempt")
elseif attempts < 3 then
  print("Not yet")
else
  print("That's enough")
end

Comparisons: == equal, ~= not equal, <, >, <=, >=. Combine them with and, or, not. A single = assigns, it does not compare.

Functions

function greeting(who)
  return "Hello, " .. who .. "!"
end

print(greeting("Cat"))   -- Hello, Cat!

Two dots .. join texts together. return hands back a result.

Lists and loops

local tools = {"screwdriver", "key", "torch"}

for i, t in ipairs(tools) do
  print(i .. ": " .. t)
end

print(#tools)   -- count: 3

In Lua, tables are lists and lookup tables at the same time. Counting starts at 1, not at 0.

Rule to remember
Upper and lower case matter. Values and values are two different things for Lua.

Your task
Write a function that adds two numbers and print the result with print.