Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programming in lua, objects

Tags:

lua

Sample code:

function Account:new (o)
  o = o or {}   -- create object if user does not provide one
  setmetatable(o, self)
  self.__index = self
  return o
end

taken from:

http://www.lua.org/pil/16.1.html

What is the purpose of the:

self.__index = self

line? And why is it executed every time an object is created?

like image 774
anon Avatar asked May 03 '10 22:05

anon


People also ask

Does Lua have object-oriented programming?

While Lua isn't an object-oriented language, it's possible to emulate the behavior of objects or classes via the practice of object prototyping. In Lua, we do this by using tables as objects.

Is Lua procedural or object-oriented?

Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.

Can you make classes in Lua?

Lua does not have the concept of class; each object defines its own behavior and has a shape of its own. Nevertheless, it is not difficult to emulate classes in Lua, following the lead from prototype-based languages, such as Self and NewtonScript. In those languages, objects have no classes.

What does three dots mean in Lua?

The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .


1 Answers

As others have said, self (the Account table) is used as a metatable assigned to the objects created using new. Simplifying slightly (more info available at the links provided) when a field is not found in 'o', it goes to the 'Account' table because o's metatable says to go to Account (this is what __index does).

It does not, however, need to be executed every time an object is created. You could just as easily stick this somewhere:

Account.__index = Account

and it would work as well.

The somewhat longer story is that if an object o has a metatable, and that metatable has the __index field set, then a failed field lookup on o will use __index to find the field (__index can be a table or function). If o has the field set, you do not go to its metatable's __index function to get the information. Again, though, I encourage you to read more at the links provided above.

like image 125
David Haley Avatar answered Sep 20 '22 07:09

David Haley