Skip to main content

Callbacks vs Methods

To begin, let's quickly define two Luau terms:

  1. A "callback" is a function that is called in the form of foo.bar().
  2. A "method" is a function that is called in the form of foo:bar().
    • The parameter self is implicitly passed as the value of foo.

However, in TypeScript, all functions inside of objects are called as simply foo.bar(). To decide whether or not a function call should compile using . or :, roblox-ts follows a simple set of rules:

Callbacks

  • Function declarations are considered callbacks.
function foo(bar: number) {}
const obj = { foo: foo };
obj.foo(123); // obj.foo(123)
  • Arrow function expressions are considered callbacks.
const obj = {
foo: (bar: number) => {}
}
obj.foo(123); // obj.foo(123)

Methods

  • Method declarations are considered methods.
const obj = {
foo(bar: number) {}
}
obj.foo(123); // obj:foo(123)
  • Function expressions inside of object literals are considered methods.
const obj = {
foo: function (bar: number) {}
}
obj.foo(123); // obj:foo(123)

Overrides

  • If a function has a parameter this: void, it is always considered to be a callback.
const obj = {
foo(this: void, bar: number) {}
}
obj.foo(123); // obj.foo(123)
  • If a function has a parameter this which is typed as anything except void, it is always considered to be a method.
declare const obj: {
foo: (this: typeof obj, bar: number) => void;
}
obj.foo(123); // obj:foo(123)