A question about functions using colon wrapped in pcall()

I’m going to use DataStoreService:GetAsync() in this question.

What is really the difference between

pcall(DS.GetAsync, DS, userId)

and

pcall(function()
    DS:GetAsync(userId)
end)

Both functions do the same thing, just in different formats. What’s the difference between these two?

Both functions do the same thing, just in different formats.

Yes, that is the difference between these two. The first one is good practice because that is how pcalls are supposed to be used, whereas in the second one, you’re creating a new function just to call the actual function you want to pcall.

1 Like

In Object Oriented Programming, when you use a :, a hidden parameter called self is passed through, this seems to come out of thin air, however, heres an example of what I mean.

local tbl = {Enabled = true}

function tbl:ToggleEnabled()
  -- 'self' is the actual object that gets passed
  self.Enabled = not self.Enabled
end

Self is automatically passed when you use a :, however when you use a ., you need to pass the actual object you’re peforming the action on.

local tbl = {Enabled = true}

function tbl.ToggleEnabled(self) -- Notice how when you use a . self is not passed
  self.Enabled = not self.Enabled
end

This can be used in pcalls.

pcall(DataStore.GetAsync, DataStore, ...)

is the same as

DataStore:GetAsync(...)

You perform DataStore.GetAsync(DataStore) where self is the datastore.

1 Like