All pastes #1276258 Raw Edit

ROBLOX LUA Basics of Coroutine

public lua v1 · immutable
#1276258 ·published 2008-12-04 21:41 UTC
rendered paste body
Coroutines... the always cool sounding LUA function... in computer programming, Coroutines were used to allow multiple processes to be performed at once. Such is the same in ROBLOX, where Coroutines can allow multiple functions to be running at once.Here is an example of a simple little ShadowHammer (a weapon seen in TurdTech beach, one of my places) WITHOUT coroutine:function Deteriorate(part)newCFrame = CFrame.new(part.Position+Vector3.new(math.random(-1,1),math.random(-1,1),math.random(-1,1))p = Instance.new("Part")p.Size = Vector3.new(1,1,1)p.CFrame = newCFramep.CanCollide = falsep.Parent = part.Parentfor i=1, 4 dop.Velocity = (p.Position-part.Position).unit*10wait()endp.Parent = nilendfunction doDamage(hit)h = hit.Parent:FindFirstChild("Ghost")if h~=nil thenfor i=1, 3 doDeteriorate(hit)endh:TakeDamage(3)endendscript.Parent.HammerEnd.Touched:connect(doDamage)now when you hit a humanoid, it wil do Function Deteriorate 3 times.... but the problem is... it will wait until p (the part) is removed before it starts again! we dont want that. so ill add a coroutine!function Deteriorate(part)newCFrame = CFrame.new(part.Position+Vector3.new(math.random(-1,1),math.random(-1,1),math.random(-1,1))p = Instance.new("Part")p.Size = Vector3.new(1,1,1)p.CFrame = newCFramep.CanCollide = falsep.Parent = part.Parentfor i=1, 4 dop.Velocity = (p.Position-part.Position).unit*10wait()endp.Parent = nilendfunction doDamage(hit)h = hit.Parent:FindFirstChild("Ghost")if h~=nil thenfor i=1, 3 docoroutine.resume(Deteriorate(hit))endh:TakeDamage(3)endendscript.Parent.HammerEnd.Touched:connect(doDamage)looks right? doesnt it? hehehe... WRONG! coroutine.resume() can be used to resume a function from its start. but you cant just do that and say it'll work... as it has to have a coroutine as a property! so in other words...function Deteriorate(part)newCFrame = CFrame.new(part.Position+Vector3.new(math.random(-1,1),math.random(-1,1),math.random(-1,1))p = Instance.new("Part")p.Size = Vector3.new(1,1,1)p.CFrame = newCFramep.CanCollide = falsep.Parent = part.Parentfor i=1, 4 dop.Velocity = (p.Position-part.Position).unit*10wait()endp.Parent = nilendfunction doDamage(hit)h = hit.Parent:FindFirstChild("Ghost")if h~=nil thenfor i=1, 3 docoroutine.resume(coroutine.create(Deteriorate),hit)endh:TakeDamage(3)endendscript.Parent.HammerEnd.Touched:connect(doDamage)Now its done! Looks too hard to see what i did? okay ill explain:coroutine.resume(coroutine.create(Deteriorate),hit)coroutine.resume() starts the coroutine we created using coroutine.create(). after that we can see 'hit' after. this is jsut basically the factor used in function Deteriorate() to find otu what 'part' is.I hoped this helped!---------- one of the greatest scripts you'll ever probably never get to meet, turdulator!