Jump to content




Oop And Meta Tables


  • You cannot reply to this topic
4 replies to this topic

#1 Xenthera

  • Members
  • 170 posts

Posted 15 November 2013 - 05:13 PM

What's the benefit of using Meta Tables with the Object Oriented aspect of lua?

For example,

Object Class
objectClass = {}
	objectClass.new = function(...)
	   newObject = {}
	   newObject.getVariable = function(self)
		   return self.variable
	   end
	   return newObject
   end
return objectClass
Main File
object = require('objectClass') -- The way I do it in love2d
myObject = object.new(...)
myObject:getVariable()
...etc

That's object oriented, and works fine.
I personally am not a big fan of metatables and try to avoid them wherever possible.

#2 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 15 November 2013 - 06:51 PM

When you use metatables, you can make it "faster" because it's only creating the functions one time. And you can use the __call method ehich looks kinda cool :D
local BaseClass = {}
BaseClass.__index = BaseClass
BaseClass.__call = function(...)
  return BaseClass.new(...)
end
BaseClass.getType = function()
  return "BaseClass"
end
BaseClass.new = function()
  return setmetatable({},{__index=BaseClass})
end
setmetatable(BaseClass,BaseClass)

--# Usage example
local class = BaseClass()
print(class.getType())


#3 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 15 November 2013 - 10:01 PM

Metatables are almost never necessary depending on what you're doing. They exist to essentially allow you to emulate different OO-related constructs commonly found in other languages. You're free to code without them if you want.

Edited by Kingdaro, 15 November 2013 - 10:02 PM.


#4 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 15 November 2013 - 11:12 PM

As freack100 attempted to state the major advantage of using metatables is being able to implement metamethods, meaning that you objects can respond to mathematical operators such as + - * / which are __add __sub __mul __div and all the other various metamethods we have available...

#5 AgentE382

  • Members
  • 119 posts

Posted 17 November 2013 - 01:04 PM

Also, metatables are useful for inheritance and storing hidden data.

However, you can do whatever you need without metatables, using normal tables and closures.





3 user(s) are reading this topic

0 members, 3 guests, 0 anonymous users