Skip to main content

Class Factory

The module returns a callable table.

local Class = require("class")

Class(definition)

Creates a class from a definition table.

local Example = Class({
init = function(self)
self.ready = true
end,
})

Equivalent to Class:new(definition).

Class:new(definition)

Creates a class and prepares its metatable.

Definition fields

FieldDescription
initOptional constructor called for each instance.
__typeOptional readable type name. Defaults to "Class".
__includesOptional table, class, string, or list of includes.
methodsAny function fields become instance methods.

Generated instance fields

FieldDescription
__privatePer-instance table for private state.
__typeReadable type copied from the class.
__classDirect reference to the class table that created the instance.

Generated instance methods

MethodDescription
Is(expected)Returns whether the instance matches a class, parent class, or type name.
AssertIs(expected, name)Raises an error when the instance does not match expected.
DebugInfos()Returns formatted diagnostic information.

Class:is(value, expected)

Returns true when value matches expected.

local Player = Class({
__type = "Player",
})

local player = Player()

print(Class:is(player, Player))
print(player:Is(Player))

expected can be a class table or a string. Class-table checks are stricter and should be preferred for validation.

Class:assertIs(value, expected, name)

Validates a value and returns it when it matches the expected class.

player = Class:assertIs(player, Player, "player")

When validation fails, an error is raised with the expected and received type.

Class:registerClass(name, prototype, parent)

Creates a typed class from a prototype and optional parent.

local Registered = Class:registerClass("Registered", {
hello = function()
return "hello"
end,
})

The returned class has __type set to name and operator helpers enabled. Prototype and parent tables are included and tracked for type checks.