Sugar for `table.insert`ing a Task to a scope
A common convention with scope is adding tasks via table.insert:
table.insert(scope, RunService.Heartbeat:Connect(function(dt)
sessionTime:set(peek(sessionTime) + dt)
end)
It would be nice if there was a built-in function to add tasks directly:
-- name subject to bikeshedding
local function addTasks<Tasks...>(scope: Scope, ...: Tasks...): Tasks...
for index = 1, select("#", ...) do
table.insert(scope, select(index, ...)
end
return ...
end
Usage:
local connection = scope:addTasks(
RunService.Heartbeat:Connect(function(dt)
sessionTime:set(peek(sessionTime) + dt)
end)
)
I've considered this in the past. It could make some code nicer, but I'll have to mull over things some more once I get back from the States next weekend.
So generally I'm in favour of this.
Bikeshedding the name:
- not sure if "tasks" is necessary in the name, since this is just a generic append function
-
appendwould be a more descriptive verb -
includemight read better when this function is used inline -
addis super short but maybe too broad -
giveis what Maids historically have used, but this feels weird
I'd probably go for append or include.
Append:
local ins = scope:append(Instance.new("Part", workspace))
local conn, ins = scope:append(
RunService.Heartbeat:Connnect(doUpdate),
Instance.new("Part", workspace)
)
Include:
local ins = scope:include(Instance.new("Part", workspace))
local conn, ins = scope:include(
RunService.Heartbeat:Connnect(doUpdate),
Instance.new("Part", workspace)
)
I like the way include reads in user code (feels like it's more obvious that the value would be returned from it), so I'm leaning towards that.
Somewhat far-fetched suggestion for scope:insert as that's more Luau-like (and aligns with table.insert):
local ins = scope:insert(Instance.new("Part", workspace))
local conn, ins = scope:insert(
RunService.Heartbeat:Connnect(doUpdate),
Instance.new("Part", workspace)
)
Also suggesting use though sounds too close to the actual Use callbacks
local ins = scope:use(Instance.new("Part", workspace))
local conn, ins = scope:use(
RunService.Heartbeat:Connnect(doUpdate),
Instance.new("Part", workspace)
)
I like the scope:insert idea.
People already have to use the following:
local part1 = Instance.new("Part", workspace)
local part2 = Instance.new("Part", workspace)
local part3 = Instance.new("Part", workspace)
local part4 = Instance.new("Part", workspace)
table.insert(scope, part1 )
table.insert(scope, part2 )
table.insert(scope, part3 )
table.insert(scope, part4 )
So naturally, the syntax sugar for this should be scope:insert()
local part1, part2, part3 , part4 = scope:insert(
Instance.new("Part", workspace),
Instance.new("Part", workspace),
Instance.new("Part", workspace),
Instance.new("Part", workspace)
)
Will go with :insert(). We could perhaps augment this later with :remove() too.