Josh Posted July 3, 2019 Share Posted July 3, 2019 I wanted to better understand coroutines so I wrote this example. I discovered that Lua errors in coroutine functions do not get caught by the debugger for some reason. The program will just silently close with no error message. I am interested in somehow creating a stack of coroutines. Like this: self:AddCoroutine(MoveToPoint,10,0,0)) self:AddCoroutine(TurnToRotation,0,90,0)) self:AddCoroutine(MoveToPoint,10,0,5)) self:AddCoroutine(ChangeColor,1,0,0,1)) self:AddCoroutine(ChangeColor,1,1,1,1)) When one coroutine is completed, the next one on the stack would begin. So if you called the above code just once, it would cause the object to move to (10,0,0), then slowly rotate it by 90 degrees, then move it again, then fade the color to red, then fade back to white. Any ideas on this? I feel like it would be very powerful for games but it's hard to think about abstractly. function MoveToPoint(entity, targetpos, speed) while true do coroutine.yield() local currentpos = entity:GetPosition() local change = targetpos - currentpos local dist = change:Length() if dist <= speed then --We have reached our target entity:SetPosition(targetpos) break end --Keep moving towards the target currentpos = currentpos + change / dist * speed entity:SetPosition(currentpos) end end window = Window:Create("",0,0,1280,720) context=Context:Create(window,0) world=World:Create() local pivot = Pivot:Create() local dest = Vec3(10,0,0) --Create the coroutine co = coroutine.create(MoveToPoint) --Send coroutine parameters in the first call --The coroutine yields right away so it won't do anything else yet coroutine.resume(co, pivot, dest, 0.5) while coroutine.status(co) ~= "dead" do System:Print(pivot.position) coroutine.resume(co) end 1 Quote My job is to make tools you love, with the features you want, and performance you can't live without. Link to comment Share on other sites More sharing options...
Rick Posted July 3, 2019 Share Posted July 3, 2019 "The program will just silently close with no error message." Look at the definition of coroutine.resume() because it returns 2 values and 1 of them is if there is an error. I noticed the debugger doesn't show these so if there is an error I write it out to console so at least I can see the error. 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.