What? no no no
calling given function with dot operator won't create anything by itself. But the function that created function so we can call it with dot operator and valid self reference will. Example:
Code:
-- Class
Foo = class();
function Foo:Constructor()
self.num = 0;
self.Bar = function( increment )
-- here we can access "self" because we take it from parent scope
self.num = self.num + increment;
end
end
-- Test init
print = Turbine.Shell.WriteLine;
-- Testing code
local instance1 = Foo();
-- those calls won't create anything and we must call this function with ".", ":" would break it
print(" ");
print("Testing . operator")
instance1.Bar( 1 );
instance1.Bar( 2 );
instance1.Bar( 3 );
print( " - " .. tostring( instance1.num ) );
print(" ");
print("Testing : operator")
success, message = pcall( function() instance1:Bar( 3 ); end );
if ( not success ) then
print( " - Error: " .. message );
end
print(" ");
print("Testing memory wastage")
local instance2 = Foo();
-- however here, "Bar" function would be created again, which leads to increased memory usage
if ( instance2.Bar ~= instance1.Bar ) then
print( " - functions are not same!" );
end
print(" ");
But in general you don't want to do this. When you need reference to "self" (which is just standardized argument name) use either ":" operator or put self as first argument. Example
Code:
Foo = class();
Foo.Constructor = function( self )
self.secret = "123456789";
end
Foo.Bar = function( this )
-- now there wouldn't be any "self" but "this" instead (holding the same reference).. it is against the standard, but it can come in handy sometime
Turbine.Shell.WriteLine( this.secret );
end
function Foo:Smth()
Turbine.Shell.WriteLine( self.secret );
end
local instance = Foo();
instance:Bar();
instance.Bar( instance );
instance:Smth();
instance.Smth( instance );