Page 1 of 1

Coding style question: to use self.function or self:function when

Posted: Wed Apr 15, 2020 2:52 pm
by Bugala
This is a matter of coding style question.

I very often use self:function system to be able to access the self.

However, sometimes there is no need for : but I could as well use self.function.


As example I have this:

Code: Select all

myfunc.IDwasfound(ID)
	if ID > -1
		return(true)
	else
		return(false)
	endif
endfunction
This function clearly never needs : used, as it never will use the self and I can see no scenario where it would need a self, since this function is just meant to make it easier to read the code:

Code: Select all

myfunc:funcaboutsomething()
self:FindIDfromTable(nameofitem)
if self.IDwasfound = false then return(FALSE)
do all kinds of stuff...
endfunction
By otherwords, in some sense it would be better in this case hence to use only self.func instead of self:func.

But this can also lead to some trouble.

For if I have some Functions that use ARGs, meaning there can be variable amount of variables, then there is high chance for bugs, since I might declare function correctly as myfunc.function, but when I use it, I might accidentally call it with myfunc:Function, in which case the first ARG is not what I meant it to be, but will be self instead.

Therefore I am wondering should I simply keep using myfunc:fund on all places, even when not needed to avoid these kind of bugs from happening, which can also be hard to find and notice, or should I rather use . when there is no self and : only when self is included?

Any opinions? How do you yourself do?

Re: Coding style question: to use self.function or self:function when

Posted: Sun Apr 19, 2020 2:14 am
by SamuraiCrow
The first form with the dot represents a static function, also known as a class function. The second form represents a method which uses the self pointer. In fact passing the self pointer in as the first parameter in the first option is identical in function to the colon notation. It is just syntax sugar.