How can self be accessed when the function is not declared with a :?

Say I’m storing my functions like this, without the : syntax:

local someModule = {}

someModule["SomeFunction"] = function()
	self:DoThing() -- Self is nil
end

return someModule

If possible, how can self be accessed without rewriting the function as

function someModule:SomeFunction()

or

local someModule = {}

someModule["SomeFunction"] = function()
	someModule:DoThing()
end

return someModule

How about if the function has no relation to the module at all?

game:GetService("Players").PlayerAdded:Connect(function(player)

end)

I’m pretty sure you could just

local module = {}
module.DoSomething = function(self)
    self.DoAnother()
end
1 Like

Self is still nil in this instance. This situation is kind of arbitrary, I just prefer the self syntax rather than accessing the outside functions through the module’s table directly.

Try replacing self as the module name? I’m not sure.

All : does is implicitly define self as the first passed function parameter and sets it to the scope of the function.

function module:Example(t)
    print(self)
    print(t)
end 

local x = module.new() -- not shown
x:Example("Hello, world!")

is the same as

function module.Example(self, t)
    print(self)
    print(t)
end

local x = module.new() -- not shown
x.Example(x, "Hello, world!")

https://www.lua.org/pil/16.html

A more flexible approach is to operate on the receiver of the operation. For that, we would have to define our method with an extra parameter, which tells the method on which object it has to operate.

function Account.withdraw (self, v)
  self.balance = self.balance - v
end

This use of a self parameter is a central point in any object-oriented language. Most OO languages have this mechanism partly hidden from the programmer, so that she does not have to declare this parameter (although she still can use the name self or this inside a method). Lua can also hide this parameter, using the colon operator.

function Account:withdraw (v)
  self.balance = self.balance - v
end
1 Like