This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Xenthera's profile picture

Oop And Meta Tables

Started by Xenthera, 15 November 2013 - 04:13 PM
Xenthera #1
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.
H4X0RZ #2
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())
Kingdaro #3
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 on 15 November 2013 - 09:02 PM
theoriginalbit #4
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…
AgentE382 #5
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.