8

I'm trying to get a handle on how OOP is done in Lua, and I thought I had a simple way to do it but it isn't working and I'm just not seeing the reason. Here's what I'm trying:

Person = { };
function Person:newPerson(inName)
  print(inName);
  p = { };
  p.myName = inName;
  function p:sayHello()
    print ("Hello, my name is " .. self.myName);
  end
  return p;
end

Frank = Person.newPerson("Frank");
Frank:sayHello();

FYI, I'm working with the Corona SDK, although I am assuming that doesn't make a difference (except that's where print() comes from I believe). In any case, the part that's killing me is that inName is nil as reported by print(inName)... therefore, myName is obviously set to nil so calls to sayHello() fail (although they work fine if I hardcode a value for myName, which leads me to think the basic structure I'm trying is sound, but I've got to be missing something simple). It looks, as far as I can tell, like the value of inName is not being set when newPerson() is called, but I can't for the life of me figure out why; I don't see why it's not just like any other function call.

Any help would be appreciated. Thanks!

2 Answers 2

11

Remember that this:

function Person:newPerson(inName)

Is equivalent to this:

function Person.newPerson(self, inName)

Therefore, when you do this:

Person.newPerson("Frank");

You are passing one parameter to a function that expects two. You probably don't want newPerson to be created with :.

Sign up to request clarification or add additional context in comments.

Comments

10

Try

Frank = Person:newPerson("Frank");

2 Comments

I wish I could accept both yours and Nicol's answers as correct, you both got it precisely right... I'm giving it to you just because you answered first :) But thank you Nicol for explaining it too... it was, as I expected, something silly that I just flat-out forgot, not even something I didn't know. Thanks again, everything working as it should and how I want now :)
@ Schollii: Try to explain your answers in stackoverflow forum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.