Skip to content

Component

CrispyBun edited this page Feb 8, 2025 · 9 revisions

Overview

Components are what defines the behavior of objects in Compost.

All components inherit from the base Component type, which has some base built-in methods, but actual behavior of a component is defined by the programmer.

If a component has an init method, it will be used as its constructor, and similarly, a destruct method can be used as its destructor.

Components can be created by passing a table with its definition into the compost.createComponent() (or compost.component()) function. It's recommended to name the components as well for any error messages to be readable.

-- components.Health

---@class Component.Health : Compost.Component
---@field health number
local Health = {}

function Health:init(health)
   self.health = health
end

function Health:getHealth()
    return self.health
end

return compost.component(Health, "Health") -- Naming components isn't required, but is highly recommended

Components can't be instanced on their own. Instead, they need to be added to a Bin.

Variables

All components have a few built-in variables. They are capitalized to not clash with other, programmer-defined variables of the component.

component.Bin

This variable should not be changed, only read. It stores the bin which the particular instance of the component belongs to. The component can use this to interact with and/or call methods of other components attached to the same bin.

local Sound = require 'components.Sound'

function Health:damage()
    local soundComponent = self.Bin:getComponent(Sound)
    if soundComponent then soundComponent:play("hurt") end
end

component.Name

The name of the component, mainly used for debugging purposes. Can be nil.

This can either be set manually as a static variable (set the Name field of the component definition directly), or by passing the name as a second argument when creating the component with compost.createComponent().

Health.Name = "Health"

component.Events

A table of events this component defines and announces. Can be nil.

This is more of a convention, as events can technically be defined anywhere. More information and examples can be found on the Event page.

Methods

addBinListener(event)

A shortcut for self.Bin.addListener(event, Component). Attaches the component as a listener to the given Event.

getComponentName()

Returns the name assigned to the component.

Getting started

tba

Types

Bin

Component

Clone this wiki locally