The world

Everything in a game is an entity: a part, a light, a sound, a group, a player. Scripts reach them through the global world.

Entities

An entity has a class (Part, Spawn, Light, Sound, Group, Player), and the class decides its properties, signals and methods. Every class extends Entity, so everything has a name, a parent, a destroying signal and the methods destroy, children, find, is_a and watch. The API reference lists all of them.

The API reference marks place properties as saved and networked properties as replicated. A property can be both. Replicated properties are the ones a game server sends to every player's game when a script changes them, read straight from the world: an entity's name and parent, a part's pose, size, color, transparency, anchored, solid, shape, material, friction, elasticity, mass and ladder, a light's color, brightness, range and angle, and a sound's asset, volume, looped and playing. A player who joins late receives the parts that changed since the place loaded as they are now. A property that is not replicated stays on the server, so a script on a player's game does not see a server script's change to it. The labels have no effect on when scripts run or when the editor publishes a place.

A part's shape changes its rendered mesh and collider. Use "Block", "Ball", "Cylinder" or "Wedge". Set material to "Concrete", "Wood" or "Grass" for tiled surfaces, or "Plastic" for the default surface.

A loose part (anchored = false) also reads its physical settings from the part: mass in kilograms (0 works it out from the size), friction (0 is ice, 0.6 is normal) and elasticity (how much it bounces). Changing any of them, or size, shape, solid or anchored, rebuilds the part's body in place, so a part that was falling keeps its place but not its speed. ladder = true marks a part a character climbs while inside it. A Light shines every way; give it an angle above 0 and a rotation and it becomes a spot light along its front (-Z) with that cone half-angle in degrees.

The game builds each part's body, collider and look from these properties as they are in the world at that moment, so anything a script sets takes effect on the next sync, a few ticks at most.

Spawn extends Part and represents a spawn marker saved in a place. A session chooses its starting spawn from the loaded place. Editing or creating a marker during the session changes the part without changing that choice.

Place settings

Use world.root to read the saved Workspace settings, such as gravity and camera_fov. Use world.lighting to read the saved lighting settings, such as clock_time and sky_model. The engine owns one of each. These fields report the place configuration and are read-only in scripts.

Making one

Constructible classes take a table of properties:

local platform = Part.new {
    name = "Platform",
    position = vec(0, 10, 0),
    size = vec(8, 1, 8),
    color = rgb(80, 160, 255),
    anchored = true,
}

Everything you do not name takes its default. The properties are checked before the entity exists, so a mistake leaves nothing half made:

Part.new { name = "Door", colour = rgb(255, 0, 0) }
-- Part has no member 'colour' (did you mean 'color'?)

A new entity is in the world straight away, hanging from world.root. Name a parent to put it somewhere else:

local house = Group.new { name = "House" }
local door = Part.new { name = "Door", parent = house }

Reading and changing properties

Properties are plain fields:

print(platform.position)           -- vec(0, 10, 0)
platform.position = vec(0, 20, 0)  -- moves it; everyone sees it
platform.color = rgb(255, 0, 0)
platform.transparency += 0.1       -- compound assignment works

Every assignment is checked. A value of the wrong type, out of range, or not finite is an error that says what is wrong:

platform.transparency = 2
-- Part.transparency must be between 0 and 1 (got 2)

Colors are vectors with each component from 0 to 1. rgb(255, 128, 0) and hex("#ff8000") make them from the usual 0 to 255 values.

Handles are values

An entity in your script is a small value, not a copy of the thing. It is cheap to pass around, compares with ==, and works as a table key:

local seen = {}
part.touched:connect(function(other)
    if not seen[other] then
        seen[other] = true
        print("first time touching:", other.name)
    end
end)

The same entity is always the same value. After an entity is destroyed its handle stays valid to test but not to use:

local victim = Part.new {}
victim:destroy()
print(victim.alive)    -- false
print(victim.name)     -- error: this Part was destroyed

A handle never points at some other entity that took over the slot.

Parents and children

print(#house:children())          -- how many are directly inside
print(house:find("Door"))         -- the first child with that name, or nil
door.parent = world.root          -- move it

find looks at direct children only. Names need not be unique, and when several children share a name the first one is returned. A parent with thousands of children answers find from an index, so it is cheap to call every frame. A parent loop (a.parent = b when b is under a) is an error.

Destroying

house:destroy()    -- the house and everything under it

Destroying fires destroying first, just before the entity goes, and ends the entity's scope: any task you started with entity.scope stops. The root of the world cannot be destroyed.

Which class is it?

if thing:is_a("Part") then ... end    -- true for a Part, false for a Light
print(thing.class)                    -- "Part"

Queries

A query asks the world a question and gives you the answer as one object you can act on in bulk:

-- Every Part within 30 studs of a point.
local near = world:query {
    class = Part,
    within = { center = vec(0, 0, 0), radius = 30 },
}

print(near:count())
OptionMeaning
classThe class to look for. Subclasses count: class = Entity is everything. Omitted: everything.
within{ center = vec, radius = n }: only entities whose position is that close.
hasA list of components: only entities that carry all of them.
withoutA list of components: leave out entities that carry any of them.
whereA function (entity) -> boolean that decides the rest.
MethodDoes
query:count()How many were found.
query:first()The first, or nil.
query:entities()The found entities as a list.
query:each(fn)Calls fn(entity) for each.
query:set(property, value)Sets one property on all of them in a single call.
query:read(property)A list of one property of each.

Acting on a set at once

Setting a property on a hundred parts in a loop makes a hundred calls. set makes one:

-- Slow: a call per part.
near:each(function(part)
    part.transparency = 0.5
end)

-- Fast: one call for all of them.
near:set("transparency", 0.5)

set and read check the value once, and return the query so calls chain: near:set("color", rgb(255, 0, 0)):set("transparency", 0.5).

Filtering with a function

local fragile = world:query {
    class = Part,
    where = function(part) return part.name:sub(1, 5) == "Glass" end,
}
fragile:set("solid", false)

Raycasts

A raycast asks what a line runs into. world:raycast returns the first solid part along it, or nil:

local hit = world:raycast {
    origin = turret.position,
    direction = vec(0, 0, 1),     -- any length; only the way it points matters
    max = 100,                    -- studs; the default is 500
    ignore = turret,              -- an entity, or a list of them, the ray passes through
}

if hit then
    print(hit.entity.name, hit.distance)   -- what, and how far
    print(hit.position, hit.normal)        -- where, and which way the surface faces
end
OptionMeaning
origin, directionWhere the ray starts and which way it goes. Required. The direction cannot be zero.
maxHow far it reaches, in studs. Default 500.
ignoreAn entity or a list of entities to pass through.
whereA function (entity) -> boolean: only parts it accepts can be hit.

world:raycast_all { ... } takes the same options and returns every hit, nearest first, so a shot can go through things.

Parts with solid = true are hit where they really are, turned as they are turned. A ray that starts inside a part hits it at distance 0.

Players are hit too, as a box about their body (1.6 studs across and 5 tall). hit.entity is then the Player. A dead player (health 0) is not hit. To shoot through yourself, pass ignore = player; to hit only parts, use where = function(e) return e:is_a("Part") end.

local hit = world:raycast { origin = gun, direction = aim, max = 300, ignore = shooter }
if hit and hit.entity:is_a("Player") then
    hit.entity.health -= 25
end

Vectors

Positions, sizes, rotations and colors are vectors. They are a built-in value: making one allocates nothing.

local a, b = vec(1, 0, 0), vec(0, 1, 0)
print(a + b, a * 3, -a)
print(a:dot(b), a:cross(b))
print(a:length(), (a + b):unit())
print(a:lerp(vec(3, 0, 0), 0.5))      -- halfway
print(a:distance(vec(4, 4, 0)))
print(a.x, a.y, a.z)
MethodReturns
v:dot(w)the dot product
v:cross(w)the cross product
v:length()the length
v:distance(w)the distance to w
v:unit()the same direction with length 1
v:lerp(w, t)the point t of the way from v to w
v:floor(), v:abs()each component rounded down, or made positive
v:min(w), v:max(w)the smaller or larger of each component

rotation is an XYZ Euler vector in degrees. The world stores the orientation as a quaternion, so reads and watch callbacks can return equivalent angles. For example, a turn of 450 degrees about Z reads as about 90 degrees.

Time

time() is the number of seconds since the game started. world.frame fires every simulation step with the time since the last. See Signals, scopes and time for sleep, timers and tasks.