Colon notation

From ComputerCraft
Jump to: navigation, search

Oftentimes, functions are associated with certain objects (usually tables), with the intention of performing an operation with such an object. We call these functions methods. While method invocations are just a subset of regular function invocations, Lua provides syntactic sugar to simplify these. The only difference between a method invocation and a function invocation is that the object that the method is supposed to operate on is passed as the first parameter (often called self). Thus, the expression x.f(x, ...) can be rewritten as x:f(...). The latter syntax is called colon notation, and is often preferred over the former. However, there is absolutely no difference in how either of these terms are evaluated. Which one should be used depends purely on preference.

String Example

local str = "Hello World"
-- these two examples are equivalent

Table Example

local tbl = {
  increment = function(self)
    self.x = self.x + 1
  x = 0

-- methods can also be defined like this. when using the colon, the first parameter can be omitted, and is automatically called "self"
function tbl:decrement()
  self.x = self.x - 1

-- these two examples are equivalent