hi, im pretty new to OOP and i have a big question:
if i do:
local Values = {}
Values.__Index = {}
setmetatable(Values,Values.__Index)
function Values.__Index:AddValueIndex(name)
if not table.find(Values, tostring(name)) then
table.insert(Values,tostring(name))
end
end
what is the differentes with:
local Values = {}
function Values:AddValueIndex(name)
if not table.find(Values, tostring(name)) then
table.insert(Values,tostring(name))
end
end
This is not how it’s supposed to be, it’s supposed to be like this:
local Values = {}
Values.__Index = Values
setmetatable(Values, Values)
function Values:AddValueIndex(name)
if not table.find(Values, tostring(name)) then
table.insert(Values, tostring(name))
end
end
Since Values.__Index points to itself it would be unnecessary to .__Index.
Personally I don’t do OOP in Lua as it is overrated, and I don’t like reinventing the wheel with classes for something I can do in like 5 seconds in another language.
Most people find they can write better code with OOP, but I write pretty decent code even without it but I recommend trying it nonetheless.
This doesn’t make sense. The point of __index is for instances of the class to redirect to the original class definition so that methods can be called without listing them all in every object.
local class = {}
class.__index = class
function class.new()
local instance = {}
setmetatable(instance, class)
return instance
end
function class:method()
end
local instance = class.new()
instance:method()
OOP is meant to mimic class creation in Java since there isn’t native support for creating custom classes. What you end up needing or wanting classes for depends on what kind of systems you’re approaching, but generally the idea is to keep methods for new objects consistent and allow you to work with custom objects the same way you do with Roblox objects.
OOP isn’t necessarily good. It depends on what you make of it. Someone will tell you it’s good, others the opposite. You decide whether you think you’ll need it or not. Personally I don’t actually use it or force it into my codebase but every now and again I’ll have a crack at it just for the heck of it in a prototyping build of a game.
0.0004 seconds is far too small for the human to even notice. Optimising code that doesn’t need optimisation is known as premature optimisation. Doing this could even be counterproductive.
“Premature optimization is the root of all evil.”
- Donald Knuth