Hello so I have been getting into object oriented programming for a while now but am struggling to understand how to use it in my projects and also the keyword self though I am using it somehow.
To give a better understanding here is what I mean :
Please note that I am really new to this and many things or all might be wrong so please correct me.
the self keyword basically just refers to the table/object that you are creating the function in. This allows you to easily change the properties/values that you have inside of the table/object. You can only use self when you use : to create a function. Ex:
local engine = {}
function engine.new()
local self = setmetatable({}, engine)
self.IsOn = false
return self
end
function engine:ChangeEngineState()
if self.IsOn == false then
self.IsOn = true
else
self.IsOn = false
end
end
return engine
Notice how I use : in the ChangeEngineState() function. This is so I can use self. If I did this instead:
function engine.ChangeEngineState()
if self.IsOn == false then
self.IsOn = true
else
self.IsOn = false
end
end
The script wouldn’t know what “self” is and would throw an error. Feel free to ask any more questions!
Not really sure what you mean by the first question, maybe try to explain it a little bit better. But for your second question yes, the way you are setting the properties in the metatable is correct. As long as it works it is correct. I personally like to define the table as “self” and set the properties from there. I believe the most standardized way to do this is how you’ve done it but to drop a line every property just to make it more readable like this:
local engine = {}
function engine.new()
local self = setmetatable({
IsOn = false; -- You can use , or ; here it doesn't matter I just personally use ;
Fuel = 100;
IsBroken = false;
MaxSpeed = 200;
}, engine)
return self
end
return engine