1. Values and variables
A program works with values. Lua has only a few kinds.
Numbers
Use brackets to say what happens first: (1 + 2) * 3 is 9, and 1 + 2 * 3 is 7.
Text
Text is called a string. Write it in double or single quotes.
Join strings with two dots. Numbers join too:
# in front of a string gives its length:
True and false
These two values are called booleans. Comparisons give them:
Equal is two equals signs, and not equal is ~=. Both catch out people who come from other languages.
Nothing
nil is the value that means "nothing here". A name you never gave a value is nil.
You will meet nil often: a search that finds nothing gives nil, and so does a field nobody filled in.
Variables
A variable is a name for a value. Make one with local:
Change it by assigning again, this time without local:
health = health - 25 reads oddly as maths. Read = as "becomes": health becomes what it was, minus 25. There is no += or -= in Lua.
Always write local
Without local, a name is global: every script in the game can see it and change it.
Two scripts that both use a global called score will overwrite each other, and the bug that follows is hard to find. Write local every time you make a variable.
Names
A name is letters, digits and underscores, and does not start with a digit. The engine's own names start with a capital (Input, Vec3, OnUpdate). A common habit is to start your own local variables with a small letter, so the two are easy to tell apart.
Several at once
Lua can assign several variables in one line:
That is also how to swap two values:
Turning one kind into another
In a game
The engine adds one more kind of value you will use all the time, a vector of three numbers:
A position, a direction, a scale and a colour are all Vec3 values.
Try it
- Make variables for a player's name, level and gold. Print one line that says
Mira is level 3 with 250 gold. - A potion heals 30. Start
healthat 55, drink a potion and print the result. - What does
print(10 / 4, 10 // 4, 10 % 4)show? Guess, then run it.
Next: decisions and loops.