Using Callbacks in Code

Using Callbacks in Code

2 min

Callbacks are write-only members of objects that are set to functions. You cannot invoke a callback directly — Roblox will internally trigger the callback function, and pass to it relevant information your callback handler/function will need.

Notable Callbacks

  • DataModel/OnClose, which fires before the game shuts down and gives scripts a chance to save data
  • MarketplaceService/ProcessReceipt, which is used to handle developer products purchases
  • RemoteFunction/OnClientInvoke which is invoked when the server calls RemoteFunction:FireClient(player, …) or RemoteFunction:FireAllClients(…).
  • RemoteFunction/OnServerInvoke which is invoked when a client calls RemoteFunction:InvokeServer(…)
  • BindableFunction/OnInvoke which is invoked when a script calls BindableFunction:Invoke(…)


To set a callback, you assign it to a function:

local bindableFunction = Instance.new("BindableFunction")
bindableFunction.OnInvoke = function()
	return 1337

Callbacks are write-only, meaning you cannot get the value of a callback.

local bindableFunction = Instance.new("BindableFunction")

OnInvoke is a callback member of BindableFunction; you can only set the callback value, get is not available

To invoke the callback, in this case, you’ll use BindableFunction:Invoke(). All of the arguments you pass to :Invoke() will be passed to the callback function, and then the return value from the callback function will be returned to the caller of :Invoke().

local bindableFunction = Instance.new("BindableFunction")
bindableFunction.OnInvoke = function(n)
	return 2 * n


Produces: 84


Suppose you want to make a BindableFunction and bind it to a function that receives two arguments, let’s say, the Name of a part and its Size, and that creates a Part, puts it in the Workspace, and gives it the Name and the Size passed to the function.

You would first create the BindableFunction:

local func = Instance.new("BindableFunction", script.Parent)

And you would then connect it to your function, using the OnInvoke callback:

local func = Instance.new("BindableFunction", script.Parent)
func.OnInvoke = function(name, size)
	local part = Instance.new(**Part**)
	part.Name = name
	part.Size = size
	part.Parent = workspace

Now, you can just call the BindableFunction like this, and it will create the part:

BindableFunction:Invoke("Brick", Vector3.new(50, 50, 50))
  • coding
  • security