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

Is there anything like a "super" command?

Asked by 8 years ago

I've got a background of coding in Java thanks to my school computer science class. In Java, there is a keyword called super that allows you to use the functions from a higher class object in the plane of inheritance.

It's purpose is mainly to save space, not having to re-write code

So basically if you had an object B, which inherits the methods of object A, you could both override and use the methods of object A. Let's say object A has a method getNumber() that returns 100; object B could override getNumber() with return super.getNumber()*5; -- returning 500.

Here's an example of what I mean in lua. We will make a basic bank account, and a subclass of it called SpecialAccount which should only let you deposit 90% of what you normally would.

    Account = {balance = 0}

    function Account:new (o)
      o = o or {}
      setmetatable(o, self)
      self.__index = self
      return o
    end

    function Account:deposit (v)
      self.balance = self.balance + v
    end

    function Account:withdraw (v)
      if v > self.balance then error"insufficient funds" end
      self.balance = self.balance - v
    end

SpecialAccount = Account:new()

function SpecialAccount:deposit(v)
    self.balance = self.balance + v --Already implemented, could be replaced with a "super command"
    self.balance = self.balance -(v/10) -- Tax :)
end

s = SpecialAccount.new();
s:deposit(100);
print(s.balance); --prints 90

Any ideas? Or am I just limited to re-writing code?

1 answer

Log in to vote
2
Answered by
Unclear 1776 Moderation Voter
8 years ago

No, there isn't. Inheritance isn't part of Lua's design; what you've produced is the metatable hack for it.

Honestly, you're overthinking this. Just create your own super field for each class that refers to its parent class. Should be one or so more line of code, and you can have all of the space-saving you want.

1
Gosh I am overthinking this. Call it procrastination through learning :P randomsmileyface 375 — 8y
1
:) Unclear 1776 — 8y
1
This might be a bit overkill, but how would I implement that super command? I've tried SpecialAccount.super = Account; and adressing the functions with SpecialAccount.super.function(SpecialAccount, variables) but have found no success; randomsmileyface 375 — 8y
0
May you be able to elaborate with an example? It seems easier said than done randomsmileyface 375 — 8y
Ad

Answer this question