Created
April 2, 2022 04:54
-
-
Save sayhisam1/b7855d06a37defe2f878ba5c599dcb0d to your computer and use it in GitHub Desktop.
Matter useBatchedEvent.lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ReplicatedStorage = game:GetService("ReplicatedStorage") | |
local Matter = require(ReplicatedStorage.Packages.Matter) | |
local Llama = require(ReplicatedStorage.Packages.Llama) | |
local t = require(ReplicatedStorage.Packages.t) | |
local Queue = require(script.Parent.Queue) -- grab from Matter source code | |
local function cleanupData(data) | |
data.connection:Disconnect() | |
table.clear(data) | |
end | |
-- Batches together events for multiple instances | |
-- Removes extra overhead from repeated topo calls | |
local function useBatchedEvent(instances: {}, event: string) | |
instances = Llama.Dictionary.fromLists(instances, instances) | |
local storage = Matter.useHookState(event, function(state) | |
for _, data in pairs(state.connections) do | |
cleanupData(data) | |
end | |
end) | |
if not storage.connections then | |
storage.connections = {} | |
end | |
for instance, data in pairs(storage.connections) do | |
if not instances[instance] then | |
cleanupData(data) | |
storage.connections[instance] = nil | |
end | |
end | |
for _, instance in pairs(instances) do | |
if not storage.connections[instance] then | |
local data = {} | |
local queue = Queue.new() | |
data.connection = instance[event]:Connect(function(...) | |
print(event, instance, "listen", ...) | |
queue:pushBack(table.pack(...)) | |
end) | |
data.queue = queue | |
storage.connections[instance] = data | |
end | |
end | |
local currentInstance: Instance, currentData: {} = next(storage.connections, nil) | |
return function() | |
local arguments = nil | |
while currentData ~= nil and arguments == nil do | |
arguments = currentData.queue:popFront() | |
if arguments == nil then | |
currentInstance, currentData = next(storage.connections, currentInstance) | |
end | |
end | |
if arguments then | |
return currentInstance, unpack(arguments, 1, arguments.n) | |
end | |
end | |
end | |
return t.wrap(useBatchedEvent, t.tuple(t.values(t.Instance), t.string)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment