Roblox Wiki
Advertisement
Roblox Wiki

A callback is a member of a class that a function can be assigned to, which is called internally by the engine in certain situations. Callbacks act similar to events. However, unlike an event, the function assigned can return values. The function cannot be retrieved in Lua, therefore it cannot be called, and can only be set.

Unlike events, there can only be one function assigned to a callback member, whereas an event can have multiple connections. Multiple assignments will override the current function.

Usage[]

Callbacks are not very intuitive to use for users who have not used them before, since they are very rarely used.

Callbacks can be used like this:

Object.Callback = func

In the code above, Object is an object, Callback is the name of a callback belonging to the object's class, and func is a function that will be set as the callback. The function can accept parameters that will be given by internal code and can return values to the internal code for various uses.

Example[]

Let's imagine a simple example: 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 light iconPart dark iconPart, puts it in the Workspace light iconWorkspace dark iconWorkspace, and give it the Name and the Size passed to the function. The callback will then return the part.

You would first create the BindableFunction:

local func = Instance.new('BindableFunction')
func.Parent = script.Parent

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

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

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

local part = BindableFunction:Invoke("Brick", Vector3.new(50, 50, 50))

Note that unlike regular events, the created Part can be returned and used like a method call.

Advertisement