Jump to content

Coroutines


Karoffe

Recommended Posts

I want an explanation of what a coroutine is

And what does it do,

An example of it working and explaining what does this example do..

Please don't give me any links I've read all about it and still can't use it :(

I know I was kinda rude when askin these things but I am really strained about this :)

Thanks in advance

Link to comment
  • MTA Team

Basically does a coroutine allow you to make a pause in a function and continue it later.

You could for example create objects in a coroutine, yield and then delete them after the yield instantly.

When you run that coroutine it will create the objects and then halt. Whenever you run that function again it will delete the objects.

  
simpleCoroutine = coroutine.wrap( 
    function () 
        local objects = {} 
  
        for i = 1, 25 do 
            objects[#objects + 1] = createObject(1234, 0.0, 0.0, 0.0) or nil 
        end 
  
        coroutine.yield() 
  
        for index, object in pairs(objects) do 
            if isElement(object) then 
                destroyElement(object) 
            end 
        end 
  
        objects = nil 
    end 
) 
  
addEventHandler("onResourceStart", resourceRoot, simpleCoroutine) 
addEventHandler("onResourceStop", resourceRoot, simpleCoroutine) 
  

Link to comment
  • MTA Team

I wrapped the coroutine with a second coroutine and an infinite loop. You can now resume 'dead' coroutines.

You have to use createCoroutine instead of coroutine.wrap

function createCoroutine(callback) 
    return coroutine.wrap( 
        function () 
            while true do 
                local ct = coroutine.create(callback) 
                repeat 
                    coroutine.resume(ct) 
                    coroutine.yield() 
                until coroutine.status(ct) == "dead" 
            end 
        end 
    ) 
end 

Link to comment

Seriously, what does that even mean, "coroutines are useless"? Coroutines are the way to separate the procedure that's performed in steps (rather than all at once) from the rest of the program. If they are useless, aren't functions useless as well?

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...