Frank W. Zammetti
Frank W. Zammetti

Reputation: 1241

Lua arguments passed to function in table are nil

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!

Upvotes: 8

Views: 3833

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473447

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 :.

Upvotes: 11

Oliver
Oliver

Reputation: 29493

Try

Frank = Person:newPerson("Frank");

Upvotes: 10

Related Questions