Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

Quick Lua OOP Question
Started by Xorcist Oct 04 2019 10:37 AM

1 reply to this topic
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 18 posts
  • Corona SDK

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;

local function AttackRoll(self)
  --Look up some "self" values here
  --Do some attack logic here
  --Return string indicating the damage done etc...

function Monster:Attack()
  print(self.name .. ": " .. AttackRoll(self));

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");

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?

[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Contributor

  • 781 posts
  • Corona SDK

Roland Yonoba has some great lua libraries.  Check out his 30log OOP library, it might be just what you are looking for.


There is also develephant's Classy OOP plugin in the marketplace