OOP method and class variable collisions

Posted by Jedhi on Fri 25 Jan 2013 03:12 AM — 6 posts, 24,996 views.

#0

animals = {}

function animals:clone ()
  local new_table = {}
  
  for k, v in pairs (self) do
    new_table[k] = v
  end
  
  return new_table
end

function animals:setup (fields)
  self.fields = fields
end

function animals:display()
  tprint (self)
end

dog = animals:clone()
dog.name = "Harry"
dog.age = "5"

dog:display()


in this example everything works fine, but if i had there a method :name i could not assigne animal its name.

i see 2 solutions. add _ to every class method like

animals:_display() and animals:_name()

and store all animal details like that

dog.details.name = "Harry"

which approach is better?
Amended on Fri 25 Jan 2013 03:13 AM by Jedhi
Australia Forum Administrator #1
It's not clear what you are attempting to do here. Try reading the Programming in Lua book (available online for downloading) which goes into some of the object-oriented aspects of Lua.

http://www.lua.org/pil/
USA Global Moderator #2
This question actually has nothing to do with OOP. He's just complaining about how Lua lets you assign data over a function.

Quote:
which approach is better?

Whichever way makes you happy.
Amended on Fri 25 Jan 2013 06:18 AM by Fiendish
USA #3
Best? Neither. Use unique names. That said, do whichever you prefer. Functions are not different than text, numbers, boolean, or tables. They're all variables.
Australia Forum Administrator #4
Quote:

in this example everything works fine, but if i had there a method :name i could not assigne animal its name.


Are you using the same namespace (table) for both data and methods? If so, you might want to make another table (eg. properties) and put everything under that. That only stops you having a method called "properties" but everything else is then open for use.
USA #5
Here is how I do OOP in Lua:

http://pastebin.com/9n8b2PtF

Feel free to use the code any way you want.