Lua: Dot vs Colon Syntax Explained

In Lua both dot . and colon : separate identifiers. But when to use which?

Dot Syntax

Nothing out of the ordinary:

particles.transform.position = script.transform.position

In fact, besides the missing semicolon ; this would be legal C# code.

Colon Syntax

So why is it that sometimes we separate identifiers with a colon : as in this example?

particles.gameObject:SetActive(true)

Syntactic Sugar

It may become clearer when you know that the colon : syntax is just syntactic sugar for an otherwise slightly longer, more repetitive statement:

particles.gameObject.SetActive(particles.gameObject, true)
particles.gameObject:SetActive(true) -- same as above!

The colon : syntax tells Lua to pass the preceding type as the first argument to a method call.

That’s all there is to it!

Combined Example

In Luny, the colon syntax commonly denotes function calls on an instance of a C# object.

Here’s an example calling a static method Instantiate() with dot . syntax:

local go = gameobject.Instantiate(script.ExplosionPrefab)

The gameobject type is the static interface of the GameObject C# class. Instantiate returns an instance of a GameObject class, which we assign to the variable go.

We can then call instance functions on the go instance with the colon syntax:

particles = go:GetComponent(particlesystem)

But if we want to access one of its properties, it’s done with the dot . syntax:

local particleX = particles.transform.position.x

So whenever you deal with a property you know the colon syntax makes no sense.

Properties in Luny as in Unity are almost always in camelCase. Meaning they start with a lowercase letter. In Luny, static types are also entirely lowercase, mainly avoid name clashes in C# AND to not confuse them with properties. Whereas functions (Lua) and methods (C#) follow the PascalCase convention, starting with an uppercase letter.

When Colon Syntax Is Valid

You can only use the colon : syntax when the following is true:

  • Preceding the colon is a table or userdata variable.
  • Following the colon is a function call.
  • The function “operates on” (passes as first argument) the instance preceding the colon.

Leave a Reply

Your email address will not be published. Required fields are marked *