Hello, it’s me again, another day, another… Anyway, I found this script that has the “self” word and a function without and end keyword? I am so confused… So, the documentation does a terrible job of explaining this script. nevertheless, could somebody give me an explanation? I tried looking for “self” explanations but they looked to hard to understand and to high level. I tried figuring it out by myself, how did I do? Any help would be appreciated!
Script:
local testButton = { --Creating a dictionary
enabled = true, --Keyword is set to true
changeEnabled = function(self, isEnabled) --Somehow creating a function without the end keyword????
self.enabled = isEnabled --Probably makes the dictionary enabled????
print(self.enabled) --I think it checks if the dictionary is enabled????
end
}
print(testButton.enabled) --Checks if the dictionary is enabled, probably...
testButton:changeEnabled(false) --disables changes?
self is merely a variable that is the table the function is attached to, if any. self automatically gets passed when constructed with the colon : operator.
local module = {}
-- colon ':' operator
function module:foo()
print(self) -- prints the module table it"self"
end
-- to call foo, you can use either way
module:foo()
module.foo(module)
Or you can define self if you want to construct using the dot . operator
-- dot '.' operator
function module.bar(self)
print(self) -- prints the module table it"self"
end
-- to call bar, you can use either way
module:bar()
module.bar(module)
It does have an end to finish the code block (line 5).
Ok, uhmm. Could explain what the :foo does in line 4? So from my understanding, the “self” keyword just prints the table? But what if it just in the script without any function or tables? Then it’s useless? I am also confused why the argument in “module.foo(module)” is module (first script). Then you don’t refer to it anymore?
You can construct it either way. These 2 are equivalent:
local t = {key = "Hello, World!"}
-- using the colon ':' operator, self automatically gets passed as an argument.
-- it is invisible in the constructor but it does exist in this scope.
function t:foo()
print(self.key) -- Hello, World!
end
-- using the dot '.' operator with the argument self is the equivalent of
-- constructing using the colon ':' operator.
function t.foo(self)
print(self.key) -- Hello, World!
end
In both cases, you can call using either methods:
-- calling using the ':' operator will automatically pass it"self",
-- aka 't' in this case.
t:foo()
-- meaning it is similar to running this line
t.foo(t)
-- if you call it without passing 't', self will equal nil
t.foo() -- will not work as expected if you rely on self
Oh, that makes a lot more sense, but I am just wondering, why are you naming the functions “foo”? I mean I’ve seen everyone else do it, so what does foo mean?