Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua arguments passed to function in table are nil

Tags:

lua

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!

like image 210
Frank W. Zammetti Avatar asked Dec 22 '11 05:12

Frank W. Zammetti


2 Answers

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

like image 199
Nicol Bolas Avatar answered Oct 14 '22 05:10

Nicol Bolas


Try

Frank = Person:newPerson("Frank");
like image 45
Oliver Avatar answered Oct 14 '22 04:10

Oliver