Components, behaviors, tweens and modules

Four tools for organizing a game as it grows: components (data an entity carries), behaviors (what an entity does), tweens (changing a property over time) and modules (libraries your scripts share).

Components

A component is a named bundle of data with defaults. Entities can carry it, and queries can select on it.

local Health = component("Health", { hp = 100, regen = false })

local crate = Part.new { name = "Crate" }
local data = crate:add(Health, { hp = 40 })   -- fields you name replace the defaults
data.hp -= 15                                  -- the data is a plain table: change it directly
print(crate:get(Health).hp)                    -- 25
print(crate:has(Health))                       -- true
crate:remove(Health)
MethodDoes
entity:add(component, fields?)Gives the entity the component. Returns its data.
entity:get(component)The entity's data, or nil.
entity:has(component)Whether it has it.
entity:remove(component)Takes it off. True when it had it.
component:count(), component:entities()How many entities carry it, and which.
component.added, component.removedSignals that fire with (entity, data).

The fields are checked: an unknown field is an error with a suggestion, and a value must have the same type as the default (hp = "lots" is an error). Adding a component twice is an error. A destroyed entity loses its components, and removed fires for each.

Components are data, so they are not saved or sent to players by themselves. Copy what matters into a part property or saved data.

Querying by component

has and without take lists of components and combine with class, within and where:

local Boss = component("Boss")

-- Every entity with Health that is not a Boss.
local targets = world:query { has = { Health }, without = { Boss } }
targets:each(function(e)
    e:get(Health).hp -= 5
end)

A query that names only has starts from the smallest of those components, so it costs what the answer costs, not what the world costs.

Behaviors

A behavior is what an entity does. Write it once and attach it to as many entities as you like: each gets its own copy, its own scope and its own parameters.

local Door = behavior("Door", {
    params = {
        open_transparency = { default = 0.7, min = 0, max = 1 },
        seconds = { default = 0.3, min = 0 },
    },
    start = function(self)
        self.open = false
        self.entity.clicked:connect(function()
            self:toggle()
        end)
    end,
    stop = function(self)
        print("the door at", self.entity.name, "is gone")
    end,
    toggle = function(self)
        self.open = not self.open
        self.entity.solid = not self.open
        self.entity:tween({ transparency = self.open and self.params.open_transparency or 0 }, self.params.seconds)
    end,
})

world:query { class = Part, where = function(p) return p.name == "Door" end }:each(function(door)
    door:attach(Door)                                  -- the defaults
end)
world.root:find("Vault"):attach(Door, { seconds = 1 })  -- one with its own parameters

The instance (self) has:

FieldMeaning
self.entityWhat the behavior is attached to.
self.paramsThe parameters, defaults filled in.
self.scopeA scope inside the entity's own.
self.behaviorThe behavior it came from.

Anything else you put in the definition (toggle above) is a method of the instance. start runs as a task when the behavior is attached, so it may sleep and wait. stop runs when the behavior ends.

It ends with the entity. Everything the behavior started in self.scope, and every connection it made, stops when the entity is destroyed. behavior:detach(entity) ends it early. behavior:on(entity) returns the instance on an entity, or nil.

Parameters

Each parameter is either a plain default (label = "spin", a string parameter) or a table with default, min, max, required and type. Attaching checks them:

part:attach(Door, { seconds = -1 })
-- Door.seconds must be at least 0 (got -1)

part:attach(Door, { secondz = 1 })
-- behavior Door has no parameter 'secondz' (did you mean 'seconds'?)

A behavior can be attached to an entity once. Attaching it again is an error.

Attaching is done from a script today. Placing behaviors in Polycarbonate's property panel is planned.

Tweens

entity:tween(properties, seconds, easing?) moves number and vector properties to new values over time. It runs in the entity's scope, so destroying the entity stops it.

local door = world.root:find("Door")
door:tween({ transparency = 0.7, position = door.position + vec(0, 4, 0) }, 0.5, "out")
EasingFeels like
linear (default)Steady.
inStarts slow.
outEnds slow.
inoutSlow at both ends.

The call returns a tween you can wait for or stop:

local t = door:tween({ transparency = 1 }, 1)
local arrived = t:wait()     -- true when it reached its target, false when it was stopped
t:cancel()                   -- stop where it is
t.finished:connect(function(completed) end)

Starting a tween on a property that another tween is already moving stops the earlier one. A tween ends at exactly the target you named.

Modules

A script that starts with --!module is a library. It does not run by itself. Another script loads it by name with require, and gets whatever the module returns:

--!module
-- A script named "Util"
local Util = {}

function Util.clamp01(x)
    return math.max(0, math.min(1, x))
end

return Util
--!server
local Util = require("Util")
print(Util.clamp01(1.5))   -- 1
  • The name is the script's name in Polycarbonate.
  • A module runs once, the first time it is required; every require of it returns the same value, so a module can keep state.
  • A module must return something. require of a module that returns nothing is an error.
  • Modules that require each other in a loop are an error that says so.
  • A module has its own scope. Libraries are plain values and functions; start tasks from the script that uses them.