Running Lua code
Lesson 2.2
Write your first program, run it, and learn to read comments and error messages.
Three ways to run Lua
The quickest start. Open the official Lua demo, type code in the box and press Run. Nothing to install. It is perfect for this whole first part of the course.
Install Lua 5.4 and run a file from a terminal:
lua54 hello.lua
On Windows you can get a ready-made lua54.exe from the LuaBinaries project; on macOS use brew install lua, on Linux your package manager (sudo apt install lua5.4). The command may be called lua, lua5.4 or lua54. Run it without a file to get an interactive prompt where every line runs as soon as you press Enter.
When you make a mod, the Celestial SDK runs your scripts for you. clight run starts the game with your mod and reloads a script every time you save it. Part 2 of the course sets this up step by step.
A good code editor helps a lot. Visual Studio Code with the Lua extension (by sumneko) colours your code and points out mistakes as you type.
Your first program
print("Hello, world!")
Run it and you see:
Hello, world!
print is a function that shows text. The text between the quotes is a string. You can print several things at once; print puts a tab between them:
print("Health:", 20) --> Health: 20
print(2 + 3) --> 5
Comments
A comment is a note for humans. Lua ignores it. A short comment starts with -- and lasts until the end of the line. A long comment sits between --[[ and ]]:
-- This is a comment.
print("This runs") -- a comment after code
--[[
This is a long comment.
It can cover many lines.
]]
In this course, a comment that starts with --> shows what the line prints.
Statements and lines
Each instruction is a statement. Put one per line. Lua does not need semicolons, and spaces and line breaks are mostly up to you. These two programs do the same thing:
print("one") print("two")
print("one")
print("two")
The second one is easier to read, so write code like that.
Reading an error
Mistakes are normal. When Lua can’t run your code, it tells you where and why:
-- a mistake: the ) is missing
print("Hello"
input:2: ')' expected near <eof>
Read it from left to right: the file (input, or your file name), the line number (2), and the problem: Lua expected a closing ) but reached the end of the file (<eof>). The line number is the most useful part. Go there first.
Two kinds of errors
A syntax error, like the one above, means Lua can’t understand the code, so nothing runs. A runtime error happens while the program runs, for example when you do maths on something that isn’t a number. The lesson Error handling shows how to handle runtime errors.
Try it
Write a program that prints three lines: your name, your favourite block, and the result of 7 * 6. Add a comment above each line.
Show a solution
-- my name
print("Alex")
-- my favourite block
print("Copper Bulb")
-- some maths
print(7 * 6) --> 42
Recap: print shows values, -- starts a comment, and error messages tell you the line to look at.