Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What's the best way to extend classes?

Asked by 10 years ago

I want to have sub-classes that extend one super-class. If you are familiar with Java then I want to extend a super-class. If you aren't familiar with Java, this means that I have a bunch of classes of similar objects. They all share several of the same variables and methods invariably, but they also all have a few variables and/or methods specific to them. Here is an example of what I have so far:

-- This is the super-class
super = {}
super.new = function() -- initialize new instance of 'super'
    local self = setmetatable( {}, {__index = super} )

    -- general instance variables and methods go here

    return self
end

-- This is the sub-class
sub = setmetatable( {}, {__index = super} )
sub.new = function()
    local self = setmetatable( {}, {__index = sub} )

    -- specific instance variables and methods go here

    return self
end

Based off what I know about Lua classes and metatables and metamethods, this should work. When an instance of the class has a general method called on it, the instance will point to the sub-class because of __index = sub, and then if it can't find the method there (because it's part of the super-class), the index will be pointed to the super-class because of sub = setmetatable( {}, {__index = super} ).

Is this correct? Is there a better way?

Answer this question