09/14/14, 08:34 AM | #1 |
|
ZO_Object design question
I have a problem with the behaviour of ZO_Object's two methods. It's confusing at best for me. Currently I'm under the impression that it's simply copied from Programming in Lua.
ZO_Object:Subclass returns setmetatable({}, {__index = BaseClass}). The returned empty table cannot be used as a metatable itself... yet. ZO_Object:New returns setmetatable({}, Class), and adds Class.__index = Class, so from now on the Class can be used as a metatable. Why does New, method that creates an instance, modify the class? Is there a reason to have a subclass incomplete until an instance is created? And if you're interested what led me to this question, I want to replace the class (metatable) of an existing object with a subclass (instead of overriding several methods one by one). I never call New on the subclass, so I have to add __index myself due to the current design. It's simple, but I just can't grasp the concept why ZO_Object:Subclass() doesn't return a ready-to-use thing. |
09/14/14, 04:08 PM | #2 | |||
|
What this does actually, is you first look in the table for the key. If it's not there, you look at __index for a function/table to go to. If it goes to another table, it'll first check that for the key then go to its metatable for __index and continue on down the line. This example will go up the chain and find the field "foo" in A: Lua Code:
:New returns an instance of the object. :Subclass is intended to be a class and not a particular instance that you would then call :New to create instances of. Functionally, though, they're equivalent because Lua doesn't have a different type/method for defining a class like say Java or C. If your object is foo, you could do something like Lua Code:
Alternatively, keep in mind the functions are stored on the table referenced by __index. If you define your functions on the particular instance of the object itself, they're put in the table itself rather than the metatable. This means it'll be overridden for that object and not the whole class. |
|||
09/14/14, 06:26 PM | #3 | |
|
Lua Code:
Now I want to subclass ZO_Stats, and change the class of STATS object to the subclass: Lua Code:
And the 3) point is what doesn't make any sense to me. What was the reasoning behind making :New add __index to the class, and not add it straight in :Subclass? |
|
09/14/14, 09:55 PM | #4 | |
|
Lua Code:
Personally, I'd probably use the alternate method I mentioned above: just define your functions directly on STATS itself. It's the same thing in effect without messing around with metatables (and is slightly more efficient). |
|
ESOUI » Developer Discussions » Lua/XML Help » ZO_Object design question |
«
Previous Thread
|
Next Thread
»
|
Display Modes |
Linear Mode |
Switch to Hybrid Mode |
Switch to Threaded Mode |
|
|