Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The self keyword in Lua is used to refer to the current instance of an object or table being manipulated within a function. It is similar to the "this" keyword in other programming languages.

In Lua, functions can be defined as methods of a table. When a method is called on an instance of the table, it passes the instance as the first argument to the function. This argument is conventionally named "self" and is used to reference the instance within the function.

For example, consider the following code:

myTable = {
  value = 0,

  increment = function(self)
    self.value = self.value + 1
  end
}

myTable:increment()
print(myTable.value)

In this code, we define a table called "myTable" with a single property "value" and a method "increment". When "increment" is called using the syntax "myTable:increment()", Lua automatically passes "myTable" as the first argument to the function. We then use the "self" keyword to reference the "value" property of the instance and increment it by 1.

The output of this code will be "1", as we've incremented the value of "myTable.value" from 0 to 1.

In summary, the self keyword in Lua is used to reference the instance of a table being manipulated within a function. It allows for the creation of object-oriented code that can manipulate multiple instances of the same table in unique ways.