0.1.0 • Published 5 years ago
@rbxts/hook v0.1.0
hook
Connections, hooks, and validated messages, for your information-sending pleasure. Works best with @rbxts/t.
rbx-hook
is a small library that exposes three classes:
Connection
, a simple wrapper around a closure to imitate anRBXScriptConnection
,Hook
, a Garry's Mod-style hook system that executes a number of functions and returns the first non-nil value,- and
Message
, aRemoteEvent
wrapper that validates messages at runtime. Invalid data from exploiters just gets tossed, before even reaching your code!
To add to all that, all of these have excellent type inference capabilities,
making writing code with roblox-ts
even more fun!
Examples
Using Connection
like you'd expect:
import { Connection } from "@rbxts/hook";
const conn = new Connection(() => { print("Disconnected"); });
conn.disconnect();
Using a Hook
for render bindings:
import { RunService } from "@rbxts/services";
import { Hook } from "@rbxts/hook";
export const PreRenderInput = new Hook<[number], void>();
let frameNumber = 0;
RunService.BindToRenderStep("Hook:PreRenderInput", 50, () => {
frameNumber++;
PreRenderInput.call(frameNumber);
});
PreRenderInput.add(frame => {
print(`Frame ${frame}`);
});
Using Message
s to replicate a list of players' latencies:
import t from "@rbxts/t";
import { Message } from "@rbxts/hook";
import { Players, RunService } from "@rbxts/services";
/**
* Sent by the server on interval. Clients echo the number back.
*/
const Heartbeat = new Message("Heartbeat", t.number);
/**
* Sent from the server to the client on interval to update players'
* latencies.
*/
const LatencyList = new Message("LatencyList", t.array(
t.interface({
latency: t.number,
player: t.instanceIsA("Player"),
})));
if (RunService.IsServer()) {
const latencies = new Map<Player, number>();
Heartbeat.connect((ply, time) => {
const lat = math.max(0, tick() - time);
latencies.set(ply, lat);
});
spawn(() => {
while (true) {
wait(1);
Heartbeat.send(tick());
const msg = [];
for (const [player, latency] of latencies.entries()) {
msg.push({ player, latency });
}
LatencyList.send(msg);
}
});
Players.PlayerRemoving.Connect(ply => latencies.delete(ply));
} else {
Heartbeat.connect((ply, time: number) => {
Heartbeat.send(time);
});
LatencyList.connect((_, arr) => {
for (const [i, ply] of arr.entries()) {
print(`Player ${ply.player.Name} has a latency of ${ply.latency}s`)
}
});
}
0.1.0
5 years ago