Learn/Lua/1. Hello, output
Lesson 1 of 8
Sign in

Lua, lesson 1

Hello, output

Lua is a small scripting language. You don't need a main function or any boilerplate: Lua reads your file from the first line to the last and runs each statement as it goes.

print writes a value to the screen and then starts a new line. Text in quotes is a string. Lua accepts single quotes ('hi') and double quotes ("hi") with the same meaning.

Printing several values

You can pass print more than one value. Watch out: it separates them with a tab character, not a space.

When you want full control, join the pieces yourself with the concatenation operator .. (two dots). Numbers are turned into text automatically when you concatenate them:

io.write: printing without a new line

print always ends the line. does not. It writes exactly what you give it, so you add yourself when you want a line break:

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

Ticket stub

Press Ctrl Enter or Check to test your code.

io.write
"\n"

io.write belongs to the io library, which handles input and output. The dot means "the write function inside io".

Escape sequences

Inside a quoted string, a backslash starts an escape: \n is a new line, \t is a tab, and \" puts a double quote inside a double-quoted string. For text that spans several lines, Lua also has long strings between double square brackets, where escapes are not processed:

Comments

How a Lua program runs

Lua first checks the whole file for syntax mistakes, such as a missing end or a quote that is never closed. If it finds one, it reports the line number and runs nothing. Otherwise it starts at the top. If something goes wrong while running, for example calling a function that does not exist, Lua stops at that line and prints an error message with the line number.

Further reading

  • Lua 5.5 Reference Manual: print
  • Lua 5.5 Reference Manual: io.write
  • Lua 5.5 Reference Manual: Lexical conventions (strings, comments)

Write a program that prints exactly these two lines:

The program reads no input.

Print this ticket stub. The middle line must be written with one io.write call that receives four separate strings: "Row ", "F", ", Seat " and "12\n".

print("Hello, World!")
print("Lua runs one line at a time.")
print("Total:", 42)      -- Total:<tab>42
print(1, 2, 3)           -- 1<tab>2<tab>3
print("Total: " .. 42)   -- Total: 42
io.write("Loading")
io.write("...")
io.write("done\n")       -- Loading...done
io.write("a", "b", "\n") -- ab   (no tabs between pieces)
print([[Line one
Line two]])
-- Two dashes start a comment that runs to the end of the line.

--[[ A long comment
     can span several lines. ]]
print("Comments are ignored") -- even after code
Hello, World!
I am learning Lua.
== CINEMA ==
Row F, Seat 12
Enjoy the film!