Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

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

1 reply to this topic
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

Xorcist

[GLOBAL: userInfoPane.html]
Xorcist
  • Observer

  • 17 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;
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?



[TOPIC: post.html]
#2

sporkfin

[GLOBAL: userInfoPane.html]
sporkfin
  • Contributor

  • 596 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




[topic_controls]
[/topic_controls]