Events¶
Scripts react to what happens in the game in two ways:
- A signal runs functions on one machine: the server, or one player's
client. Built-in signals such as
Collider.Touched,Chat.MessageSentorComponent.User.Addedare signals. - A message from
Nettravels between the server and clients, such as a player's request to buy an item or the server's report of a hit.
A signal never crosses the network: a signal that fires on a client runs only that client's functions, and one that fires on the server runs only the server's. To reach the other side, send a message.
Listen to a signal¶
Signals of an entity's components, such as a part's Touched, connect through
the entity's On method. Pass the signal from the Component namespace and
the function to run:
-- Server script in a part.
self:On(Component.Collider.Touched, function(other: Entity)
local player = Players.Of(other)
if player then
print(player.Name .. " touched " .. self.Name)
end
end)
Signals of systems and component handles, such as
Chat.MessageSent or
Component.User.Added, have their own
Connect method. Each call runs on
its own thread, so the function may call task.wait, and an error in one
function does not stop the others.
-- Server script.
Component.User.Added:Connect(function(player: Entity)
print(player.Name .. " joined")
end)
Once runs a function the next time
the signal fires and then disconnects it.
Wait pauses the script until the
signal fires and returns true followed by its values, or false when the
seconds you pass run out. Wait cannot pause Update or another callback
that must return at once; call it from the top of the script or from
task.spawn.
Entity and component signals¶
Pass Entity.ChildAdded, Entity.ChildRemoved or Entity.Destroyed to On
to follow the tree; Entity lists them all. A
component field's Changed signal runs a function each time the field
changes:
-- Server script.
local npc = Prefabs.Spawn("Character")
local character = npc.Character
npc:On(Component.Character.State.Changed, function()
if character then
print(character.State)
end
end)
A component handle's Added and Removed signals fire for every entity that
gets or loses the component, such as Component.User.Added for every player
who joins; see ComponentHandle.
Stop listening¶
On, Connect and Once return a
Connection; call its
Disconnect to stop the
function. Connected reads
false once the connection has ended. A connection also ends when the script
stops or when the entity that owns the signal is destroyed, so a script does
not need to clean up its connections before it is removed.
Let scripts react to each other¶
A component that you define is also a way for scripts to talk on the same
machine: one script adds it to an entity, and another connects to its Added
signal. Define the component once, in a module that both scripts require, so
they share the same handle:
-- Server script scripts/Door.server.luau, attached to a door part.
local DoorState = require("./DoorState.server")
self:On(Component.Collider.Touched, function(other: Entity)
if Players.Of(other) and not self:Has(DoorState.Open) then
self:Add(DoorState.Open)
end
end)
-- Server script scripts/Alarm.server.luau, attached to another part.
local DoorState = require("./DoorState.server")
DoorState.Open.Added:Connect(function(door: Entity)
print(door.Name .. " opened")
end)
self:Remove(DoorState.Open) fires the handle's Removed signal. A module
whose name ends in .server.luau stays on the server; see
Sharing code with require.
Which side a built-in signal fires on¶
Some built-in signals fire on one side only. The first time a script connects to one on the other side, Output prints a warning:
- Pointer and interface signals, such as
PressedandReleasedof a button, fire only on the player's client. - To act on a player's button press on the server, spawn an
InputActionwithReplicated = truefrom a server script. ItsPressedsignal then fires on the server with the player who pressed it; see Replicated input actions.
Engine errors lists the warning texts.
Send messages between server and clients¶
A message is a named type of data with a fixed set of typed fields. Its direction is either to the server, from client scripts, or to clients, from the server.
Declare a message¶
Net.ToServer declares a message from
clients to the server, and Net.ToClients
one from the server to clients. Each returns a handle that you pass to every
other Net call. The server and the clients must declare each message with
the same name and fields, so declare them once in a module that both sides
require, and require it when the script loads:
-- scripts/ShopMessages.luau
return {
Buy = Net.ToServer("Buy", {
Item = "",
}),
Notice = Net.ToClients("Notice", {
Text = "",
}),
}
-- Server script scripts/autorun/Shop.server.luau
local ShopMessages = require("@scripts/ShopMessages")
Net.On(ShopMessages.Buy, function(player: Entity, data: { Item: string })
Net.SendTo(player, ShopMessages.Notice, {
Text = "Bought " .. data.Item,
})
end)
-- Client script scripts/autorun/Shop.client.luau
local ShopMessages = require("@scripts/ShopMessages")
Net.On(ShopMessages.Notice, function(data: { Text: string })
print(data.Text)
end)
Net.Send(ShopMessages.Buy, { Item = "Speed" })
A declaration that disagrees with an earlier one of the same name, or a message name that a component already uses, is an error.
Fields¶
Each field's value in the declaration sets its type, and the value itself is only an example:
- a number, such as
0; - a boolean, such as
false; - a string, such as
""; - a
Vector3, such asVector3.Zero; Field.Entityfor an entity, orField.List(Field.Entity)for a list of entities.
An entity that the receiving side does not have, because it was destroyed or
exists only on the sender's client, arrives as nil. In a list it stays nil
at its index, so loop over a list with a numeric for rather than ipairs.
A message with no fields takes no data. Otherwise the data table must hold a value of the right type for every declared field, and no other keys.
Send a message¶
A client script calls Net.Send to send a
message to the server. A server script picks who gets it:
Net.SendTosends to one player or a list of players;Net.SendAllsends to every player;Net.SendExceptsends to every player except one player or a list of players;Net.SendNearsends to every player whose area of interest covers a position or an entity.
A client has a byte budget for the messages it sends in one tick. Net.Send
returns false when a message does not fit, and
Net.Budget returns how many bytes are left.
Receive messages¶
Net.On runs a function once for each message
that arrives, and Net.Once only for the next
one. On the server, the function gets the player who sent the message and then
the data table. The server fills in the player from the connection the message
arrived on, so a client cannot send a message in another player's name. On a
client, the function gets only the data table. Both return a
Connection.
Reliable and Timing¶
An optional third argument to Net.ToServer or Net.ToClients sets how the
message travels:
Reliableistrueby default: every message arrives, in order.Reliable = falsemessages may be lost, which suits state that the next message replaces anyway, such as an aim direction.Timing, onNet.ToServeronly, is"Arrival"by default: the server handles the message when it arrives. WithTiming = "Input", the server holds the message until it applies the player input the client had made when it sent the message, so a shot lines up with the player's movement."Input"needsReliable = true.
How it works¶
Net calls send nothing at once. The engine collects the messages of a tick
and sends them together at the end of the tick, in one packet per player
instead of one per message, which is why the send budget counts bytes per
tick.
A reliable message to clients runs on a client when the client draws other players and moving parts at the server tick the message was sent on. The client draws those a short time behind the server (see Server and clients), so an effect the server sends for a hit lines up with where the client shows the players involved.