darkfrei wrote: ↑Wed Feb 24, 2021 1:52 pm
Is it the right way?
Seems correct at first glance.
The simplest explanation I can think of:
Code: Select all
function test.x()
-- you don't have access to "test" here.
end
If you want to access "test" in this function, you can write:
Code: Select all
function test.x(p)
-- you can pass "test" as parameter "p" to have access to it
end
--for example
result = test.x(test)
Now, you can of course name a parameter as you wish, so take the above example and rename "p" to "self":
Code: Select all
function test.x(self)
-- you can pass "test" as parameter "self" to have access to it
end
--for example
result = test.x(test)
Writing it this way all the time would be of course quite tedious, so for your convenience lua has a ":" operator:
Code: Select all
function test:x() -- exactly equivalent to function test.x(self)
-- this function has a hidden "self" parameter that you can access like every other ordinary parameter.
end
--for example
result = test:x() -- passes "test" as a hidden parameter, exactly equivalent to result = test.x(test)
Now, if you were calling a function similar to:
Code: Select all
function test:x()
[...]
local example = self.something
[...]
end
like this:
Then it will throw an error, because in the function definition there is a invisible "self" parameter, and you didn't pass it to the function so it will be nil. To fix this you can change the call to:
But the second one is of course preferred if you want to make your code more tidy.