'What does 'o = o or {}' do in Lua?
As I understand from docs, we don't have classes in Lua. Lua does not have the concept of class; each object defines its own behavior and has a shape of its own.
So a simple emulation of classes in Lua, following the lead from prototype-based languages, such as Self and NewtonScript would be something like.
function Account:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
What I don't understand here is what does o = o do and why do we need to use setmetadatatable and the next line index = self.
What does it do and why do we need them?
Also self.o = o was pretty much understood, but o = o, wouldn't that create any conflict?
Solution 1:[1]
A = B or C is commonly used idiom, relying on short-circuit evaluation of logic operators. If the first operand B is not null or false, then the A gets value of B, and the other operand is not evaluated. If the B is null or false, then the A gets value of C.
In this particular application of the idiom the o gets default value of new empty table when the parameter o wasn't given, because the missing parameter evaluates to null value.
The parameter o is a local variable, so all the effects of assigning anything to it will stay local to the Account:new() function.
Solution 2:[2]
For the first line, see Vlads answer.
setmetatable(o, self) assigns self as the metatable of o. self can now contain a set of metamethods to add functionality to o (see link for more information).
__index is the metamethod called when o does not contain an indexed key. It can also be another table. In this example, __index is set to self, so if you attempt to index a nil value in o, it will look in self instead. If you only call Account:new(), self is Account.
Example from you link: you have an deposit function in Account. After you created your object o = Account:new() you can now call o:deposit(). This will look in o for deposit, fails, then looks in __index=Account for deposit, succeeds, calls it.
If you do not set the metatable, or __index, calling o:deposit() will result in an attempt to call a nil value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad |
| Solution 2 |
