Confusion on Events

On the Roblox Developer website, they have the following code listed under the article about Events, specifically under the section going over how to use the Disconnect() function

 local points = Instance.new("NumberValue")
 points.Name = "Points"
 points.Value = 0
 local connection
 local function onPointsChanged(newPoints)
  print("Points: " .. newPoints)
 if newPoints >= 50 then
  -- Stop listening for changes if we have at least 50 points
  connection:Disconnect()
      end
 end
 connection = points.Changed:Connect(onPointsChanged)
 -- Trigger some changes
 points.Value = 25
 points.Value = 100
 points.Value = 0 -- Prints nothing because we called Disconnect()

They declare variable called connection but don’t initialize it. Then within the function, they call the Disconnect() function on it. How is that possible?

Although it seems as if the variable local connection has no value, it is being defined right below the local function onPointsChanged function.
(connection = points.Changed:Connect(onPointsChanged))
Since local connection is defined prior to it being called in the script (and “newPoints” is starting below 50), it can be called in this manor without erroring. Not sure if this answers all of the questions you had, if it didn’t then let me know.

1 Like

So when local connection is being initialized, what does the line of code points.Changed:Connect(onPointsChanged) return exactly?

The Connect method returns a RBXScriptConnection object. The connection object has a Disconnect method, which disconnects the event from the passed function (the passed function will no longer be called when the event occurs).

Thus, the connection variable is being set to the RBXScriptConnection object, so the connection can be disconnected if newPoints >= 50. Thus onPointsChanged will only be called upon points.Changed until newPoints >= 50, and then it will no longer be called.

3 Likes

Well since the code cuts off I can’t really tell you what it “returns”, however, “local connection” is being set to “points.Changed:Connect(onPointsChanged)”. It’d be the exact same as if you said something like;

local connection = points.Changed:Connect(onPointsChanged)
1 Like