Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 32 ยท Getting Started

Your First Lua Program

Write and run your first Lua program: print and io.write, comments, statements and newlines, running a file with lua, and using the interactive REPL.

Every language lesson starts with printing a line of text, and Lua is no exception. But a first program is also a good moment to learn how Lua reads your file: what a statement is, how comments work, what the interpreter does with line breaks, and the two ways to write output, print and io.write. You will also see how to run code from a file and from the interactive prompt.

If you have not read it yet, Introduction to Lua explains why the runnable examples here are JavaScript stand-ins while the Lua code blocks are read-only.

Hello, world

Create a file named hello.lua with one line in it.

LUA
print("Hello, world!")

Run it from a terminal in the same folder.

Terminal
lua hello.lua

The output is:

Text
Hello, world!

print is a built-in function. Parentheses hold its arguments, and "Hello, world!" is a string. Strings can use double quotes or single quotes; both mean the same thing, and Strings covers all the forms.

Comments

A comment is text the interpreter ignores. A line comment starts with two dashes and runs to the end of the line. A block comment starts with --[[ and ends with ]].

LUA
-- this is a line comment
print("visible")   -- a comment after code

--[[
  This is a block comment.
  It can span several lines.
]]

--[==[
  Add equals signs to the brackets when the comment
  itself contains ]] inside it.
]==]

A handy trick: put an extra dash in front of a block comment, ---[[, and the opener becomes a line comment, so the code that follows is active again. Programmers use it to switch a section on and off with one keystroke.

Statements and newlines

A Lua program is a sequence of statements run in order. Unlike C or JavaScript, Lua does not need semicolons. A newline is just whitespace, so the interpreter decides where a statement ends by reading the grammar.

LUA
local a = 1
local b = 2
print(a + b)

You may add semicolons if you like, and you may put several statements on one line.

LUA
local x = 10; local y = 20; print(x * y)

There is one famous trap with lines that start with an opening parenthesis. Because newlines are not separators, Lua can read the next line as a continuation of the previous one.

LUA
local f = print
(f or print)("hello")
-- parsed as: local f = print(f or print)("hello")
-- print returns nothing, so calling its result is an error

In ordinary code this is rare, but if you ever start a line with (, put a ; before it to be safe.

print can take any number of arguments of any type. It separates them with a tab character and ends with a newline. It converts each value to text with tostring, so nil and booleans print as words.

LUA
print("one", "two", 3)       -- one	two	3
print(nil, true, false)      -- nil	true	false
print(10 / 2)                -- 5.0
print(10 // 2)               -- 5
print()                      -- prints an empty line

The gap in the first output is a tab, not spaces. Notice that 10 / 2 prints 5.0: in Lua 5.4 the / operator always gives a float. Numbers and the math Library explains the integer and float subtypes.

io.write in detail

io.write is the other way to print. It belongs to the io library, accepts only strings and numbers, adds no tabs between arguments and adds no newline at the end. That makes it the right tool when you build a line piece by piece or want exact formatting.

LUA
io.write("Loading")
for i = 1, 3 do
  io.write(".")
end
io.write("\n")        -- you add the newline yourself
-- output: Loading...

Passing a table or nil to io.write raises an error ("bad argument #1 to 'write'"), while print happily shows them. A good rule: use print for quick checks and debugging, io.write for exact output.

print or io.write?

print Tabs between values, newline at the end.
io.write Exact text only, no extras.
Any type print shows nil, booleans and tables.
Strings and numbers io.write accepts only these.

Pick print for debugging and io.write for precise output.

1 / 2

The interactive prompt

Typing lua with no file starts the read-eval-print loop, or REPL. You type a line, Lua runs it and shows the result. In Lua 5.3 and later, you can type an expression and the REPL prints its value.

Text
$ lua
Lua 5.4.7  Copyright (C) 1994-2024 Lua.org, PUC-Rio
> 2 + 3
5
> print("hi")
hi
> x = 10
> x * 2
20

(Your version number may differ.) Leave the prompt with Ctrl+D on macOS and Linux or Ctrl+Z then Enter on Windows, or by calling os.exit(). The REPL is great for trying out small ideas, including any function you are unsure about.

You can also run a single command with lua -e "print(1 + 1)", check the version with print(_VERSION) (it shows Lua 5.4), and pass arguments to your script, which it reads from the global table arg.

LUA
-- run with: lua args.lua apple banana
print(arg[0])        -- args.lua
print(arg[1])        -- apple
print(#arg)          -- 2

Stand-ins you can run

The two stand-ins below model print and io.write in JavaScript. A small helper converts values the way Lua's tostring does for nil and booleans, so you can see how the two functions differ. The JavaScript here is only a model; in real Lua you would run the lua command.

JS print versus io.write (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in imitates how Lua reads a program as a list of statements, ignoring comments. It is a tiny line reader, not a real Lua parser, but it shows how -- comments disappear before anything runs.

JS Stripping comments (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common beginner errors

  • Forgetting end. Blocks such as for, if and function end with the word end. A missing one gives "'end' expected near ".
  • Using != instead of ~=. Lua's not-equal operator is ~=.
  • Using + for joining strings. Use ..; + is for arithmetic only.
  • Capitalizing print. Names are case-sensitive, so Print("x") fails with "attempt to call a nil value (global 'Print')".

Error messages in Lua name the file and line, for example hello.lua:3: ..., which makes them easy to follow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What separates the values in print("a", "b")?

    print puts a tab between its arguments and a newline at the end.
  2. 2. Which line is a valid single-line Lua comment?

    Two dashes start a comment that runs to the end of the line. Block comments use --[[ and ]].
  3. 3. What does io.write("a", "b") output?

    io.write writes exactly the strings and numbers you give it, with no separators and no newline.
  4. 4. How do you start the interactive Lua prompt?

    Running the lua command without a script starts the REPL, where each line is run immediately.

Summary

  • print converts values with tostring, separates them with tabs and adds a newline.
  • io.write writes only strings and numbers, with no separators and no newline.
  • -- starts a line comment; --[[ ... ]] is a block comment.
  • Semicolons are optional, and a newline does not by itself end a statement; start a line with ; if it begins with (.
  • lua file.lua runs a script, lua starts the REPL, and arg holds command-line arguments.

Next: store values in Variables and Types.