Hello! I’m trying to get back into the swing of developing on Roblox, and I randomly decided to look into object-oriented programming. It looks like the method that is most commonly taught is different than the one that I observed and picked up from studying other code. I’m hoping to learn why this difference is integral.
METATABLE METHOD
To have object-oriented programming most videos and forum tutorials recommend doing this: (contained within module script)
local Object = {}
Object.__index = Object
function Object.new(name, color)
local object = setmetatable({}, object)
object.Name = name
object.Color = color
return object
end
function Object:Speak()
print(self.Name)
end
METATABLELESS METHOD
However, the first form of classes I encountered (and what I have been replicating) looks like this:
local Object = {}
function Object.new(name, color)
local self = {}
local name = name
local color = color
function self.Speak()
print(name)
end
return self
end
Although both systems function practically identically, I understand that they have some notable differences – namely that the metatableless system does not allow the variables to be directly referenced or changed. With that in mind, I want to ask if there is a reason that the metatable method is taught? Is it better? If so, is there ever a reason to use the metatableless method?
Thanks! ^^