Re: Need Critique on Tutorial Series on Making Arkanoid-type Game.
Posted: Sun Dec 18, 2016 10:40 am
This is my take on this: viewtopic.php?f=14&t=83241&p=207041#p207041noway wrote:`setmetatable(o, self)` sets Class as the metatable for an each new class object.For example in your tutorial it's:
Code: Select allI believe "self.__index = self" doesn't do anything in this case.Code: Select all
function Class:new( o ) o = o or {} setmetatable(o, self) self.__index = self ..... return o end
Now the code above will probably work... well, kinda...
but if you tried to implement any sort of inheritance then you'll be left scratching your head.
You probably want something like:
`self.__index = self` sets `__index` metamethod in the Class to point to Class itself.
To have inheritance you just type `SubClass = Class:new()` and then proceed to define SubClass methods.
You don't even need to define the new constructor for the SubClass.
The code I use is from Programming in Lua.
Below are relevant excerpts (full text: Classes, Inheritance; also found in 3ed, p. 165 ):Let us go back to our example of a bank account. To create other accounts with behavior similar to Account, we arrange for these new objects to inherit their operations from Account, using the __index metamethod. Note a small optimization, that we do not need to create an extra table to be the metatable of the account objects; we can use the Account table itself for that purpose:
(When we call Account:new, self is equal to Account; so we could have used Account directly, instead of self. However, the use of self will fit nicely when we introduce class inheritance, in the next section.)Code: Select all
function Account:new (o) o = o or {} -- create object if user does not provide one setmetatable(o, self) self.__index = self return o end
The constructor being part of the class (and the class being called "self" in the constructor), redefining the __index metatable in each constructor call, and doing that AFTER setting the metatable for the instances... it just seems wrong to me.