Search code examples
lualua-table

Object creation in lua


Which way is better?

This

Dog = {}                                   

function Dog:new()                        
  newObj = {sound = 'woof'}   
  self.__index =  self                     
  return setmetatable(newObj, self)
end

function Dog:makeSound()                  
  print('I say ' .. self.sound)
end

mrDog = Dog:new()                          
mrDog:makeSound()

or this

Dog = {}                                  

function Dog:new()                         
  newObj = {sound = 'woof'}
  return setmetatable(newObj, {__index = self})       
end

function Dog:makeSound()                   
  print('I say ' .. self.sound)
end

mrDog = Dog:new()                          
mrDog:makeSound()

The first one is how everyone does it but the second one is less confusing and make more sense to me

Is there any issue in second one?


Solution

  • In the first snippet you have a single metatable for all instances of your class while in the second snippet each instance has its own metatable.

    Why have an extra table for every instance if one does the job? Also you have the problem that you cannot change the behaviour of a class without modifying each instances metatable.

    Let's say you wanted to change what happens if you convert a Dog instance to a string.

    In the first snippet you just implement Dog.__tostring and you're done. In the second snippet you would have to get the metatable of each instance first.

    At the end it's a question of personal preference.

    In both your snippets you're creating a global instance. You need to make newObj local!