Learn Lua

Lua is the language game scripts are written in. It is small: the whole language fits in an afternoon, and that afternoon is these six pages.

This course is for people who have not programmed before, and for people who know another language and want the differences. It teaches Lua 5.4 as the engine runs it, using examples from games.

PageWhat it covers
1. Values and variablesNumbers, text, true and false, nil, local
2. Decisions and loopsif, and, or, while, for
3. FunctionsWriting your own, arguments, results
4. TablesLists and records, the one data structure Lua has
5. Objects and scriptsself, the colon, and how a script file works
6. Mistakes everyone makesA checklist, and a cheat sheet for people coming from other languages

A place to try things

Every example on these pages can be run. Set up a scratch script once:

  1. Open any project in the editor. A new one from the Empty template will do.
  2. In the Hierarchy, press + and Create Empty. Name the entity Scratch.
  3. In the inspector, press Add Component, choose Scripts, then press New script.
  4. Open Assets/Scripts/Scratch.lua in your code editor and replace its contents with:
-- file: Scratch.lua
local Scratch = {}

function Scratch:OnStart()
	print("Hello from Lua")
end

return Scratch
  1. Press Play in the editor and look at the Console panel. It says Hello from Lua.

To try an example, paste it between function Scratch:OnStart() and end, save the file and press Play again. print writes to the Console.

Do not worry about the lines around your code yet. Page 5 explains them.

How to read the examples

Text after -- is a comment. Lua ignores it. The examples use comments to show what a line gives:

print(2 + 3)   --> 5

Read --> as "this prints".

One rule before you start

Lua cares about upper and lower case. print works and Print does not. Speed and speed are two different names.

Start with values and variables.