Behavior #1
local function foo(n)
print(n)
end
for i = 1, 5 do
task.defer(foo, i)
end
warn("eof")
The above code prints the following:
15:46:35.564 eof - Edit
15:46:35.570 1 - Edit
15:46:35.570 2 - Edit
15:46:35.570 3 - Edit
15:46:35.570 4 - Edit
15:46:35.570 5 - Edit
which is to be expected, it’s deferring in the order they’ve been given.
But when I wanted to recycle the thread to avoid creating a new one every time I defer, I ran into this weird behavior:
local count = 0
local co = coroutine.create(function(...)
while true do
count += 1
print(`{count}: {coroutine.yield()}`)
end
end)
coroutine.resume(co)
for i = 1, 5 do
task.defer(co, i)
end
warn("eof")
Which prints:
15:55:02.542 eof - Edit
15:55:02.549 1: 5 - Edit
15:55:02.550 2: nil - Edit
15:55:02.550 3: nil - Edit
15:55:02.550 4: nil - Edit
15:55:02.550 5: nil - Edit
So now when we pass a suspended thread, it manages to run it the n amount of times in the correct order but only the last defer’s arguments are kept and all the others get voided which is very weird behavior.
Behavior #2
And here’s another voodoo magic behavior:
local count = 0
local co = coroutine.create(function(...)
while true do
task.wait()
count += 1
print(`{count}: {coroutine.yield()}`)
end
end)
coroutine.resume(co)
for i = 1, 5 do
task.defer(co, i)
end
warn("eof")
By adding a task.wait()
, the prints somehow becomes:
16:17:53.829 eof - Edit
16:17:53.841 1: nil - Edit
16:17:53.842 2: nil - Edit
16:17:53.842 3: 0.013875399999960791 - Edit
16:17:53.843 4: 0.0008567999993829289 - Edit
16:17:53.859 5: 0.01600220000000263 - Edit
The reason I didnt do an Expected Behavior section was because I dont really know what the engineers say the expected behavior should be. So this is just a pure bug report.