-
Notifications
You must be signed in to change notification settings - Fork 0
Component
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 recommendedComponents can't be instanced on their own. Instead, they need to be added to a Bin.
All components have a few built-in variables. They are capitalized to not clash with other, programmer-defined variables of the component.
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
endThe 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"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.
A shortcut for self.Bin.addListener(event, Component). Attaches the component as a listener to the given Event.
Returns the name assigned to the component.