dumb question, ready?

RawrRawr REGISTERED, Tester Posts: 511 Seed
edited June 2015 in Code
After including a script like PlaceableObject.lua, what happens to a default function after I write a function with the same name in my mod script?

function PlaceableObject:PickedUp() self.m_inInventory = true end
function TestMod:PickedUp() self.m_inInventory = false end

Who wins? Does the default run regardless?
Programmer, designer, artist.


  • RawrRawr REGISTERED, Tester Posts: 511 Seed
    See the other thing I noticed was that if I did the following:
    include("Scripts/Objects/PlaceableObject.lua") ... function TestMod:PickedUp() NKPrint("PickedUp called\n") end
    That print statement shows up twice in the console.
    Programmer, designer, artist.
  • Red AgliatorRed Agliator REGISTERED Posts: 307 Seed
    It depends on whether your script "inherits" from PlaceableObject.lua. If your script is a subclass of PlaceableObject.lua, or a sub-class of a sub-class of PlaceableObject.lua (such as Equipable, Grower, Trap, and so on). The subclass is set with a version of one of these lines at the top of your object's script:
    MyObject = Placeable.Subclass("MyObject")
    MyObject = EternusEngine.GameObjectClass.Subclass("MyObject")
    If you're familiar with object-oriented terms such as "parent class", "superclass", "class inheritance", "override the parent's version", then those rules (mostly) apply in the first case, where MyObject is a subclass of PlaceableObject.

    In the example you gave, TestMod:PickedUp() and PlaceableObject:PickedUp() only conflict if TestMod "inherits" from PlaceableObject (or from a subclass of PlaceableObject).
  • Red AgliatorRed Agliator REGISTERED Posts: 307 Seed
    edited June 2015
    Oh, and if you are familiar with object-oriented programming and inheritance, my understanding is that there are several cases in TUG's class system:

    You'd better ask someone who's used them, but I think it's something like "they're all called".

    All constructors are always called. So if you inherit from PlaceableObject, constructors from your object, from Equipable, and from PlaceableObject all get called, though I don't know the order.

    other functions
    The function is called on the lowest child object only. So if you want to run the parent's version, too (which you will in most cases), you will need something like:

    function TestObject:PickedUp(...) TestObject.__super.PickedUp(self, ...) -- your code here end

    Just don't use that if you inherit directly from GameObjectClass!

    I don't know whether it's 100% kosher, but I usually add a check to see whether the function exists in the parent class before I call it. (Especially when starting, I kept changing the parent class of various scripts, so it saves me from stupid mistakes.)

    if TestObject.__super.PickedUp ~= nil then TestObject.__super.PickedUp(self, ...) end
Sign In or Register to comment.