Dot and Colon

Lua provides two ways to implement functions within module tables. They are both very similar, one uses a dot  .  and the other a colon  : . These variations can be quite confusing for beginners. Especially because the bugs caused by improper usage of the syntax can be hard to spot and understand. Learning about the two formats will help you to prevent such bugs and properly utilize their functionality.

 

Dot Syntax

The dot syntax is pretty straightforward. Append the module’s name, followed by a dot ( module_name. ), to the beginning of the function’s name. This will make the function a child of the module.

The function can now be called through the module’s instance with the same format.

 

 

Colon Syntax

The colon syntax is a bit more complex in its functionality, but the syntax is almost the same as the dot. Append the module’s name, followed by a colon ( module_name: ), to the beginning of the function’s name. The function is now a child of the module, just as before. The difference here is that every call to the function will now require the first parameter to be a variable referencing the module itself (known as the self variable). It can be accessed inside the function using the “self” keyword.

You can also use the colon syntax to call a function that defines a self variable as its first parameter.

If you need to, you can also call it with the dot syntax, but you’ll need to pass a self variable as the first parameter manually.

 

The colon syntax is useful when you need to refer to other variables or functions within the same module. Otherwise, the dot syntax is sufficient.

It’s generally good practice to pick one syntax and remain consistent with it throughout the module. Mixing them up might be fun for a while, but if you want to use the module again later, you’ll need to figure out which format was used by any functions you call.