So I think I’m pretty solid on indexing and metatables, but I’m coming from a world of more traditional OOP. And I keep feeling like there is a minor disconnect at times. What I would like to do, is have a class with a public method that calls a private method that can still reference self (without function duplication).
This is a quick sample I threw together, and I assume this is okay, but is it “best practice”?
Monster = {}; Monster.\_\_index = Monster; function Monster:new(name) local this = { name = name }; setmetatable(this, self); return this; end local function AttackRoll(self) --Look up some "self" values here --Do some attack logic here --Return string indicating the damage done etc... end function Monster:Attack() print(self.name .. ": " .. AttackRoll(self)); end return Monster;
I can use it like this, and it appears to work just fine:
local Monster = require("monster"); local orc = Monster:new("orc"); local goblin = Monster:new("goblin"); orc:Attack(); goblin:Attack();
Neither orc nor goblin can directly call AttackRoll(), which is expected.
And I realize that orc:Attack() is actually calling through to Monster:Attack() passing along the orc or goblin tables as self. So I’m actually in the Monster table at that point, which is why I needed to directly pass self along to the “private” function.
But it still feels weird to me. Is there a better way to be handling this?