Roblox Coroutine

Posted on

In Lua, coroutines are some of the most parts which are interesting and useful. But, they are still some of the most misunderstood concepts of Lua scripting. If you make a new coroutine, it is like making a new script in your place. You have to know that on Roblox, one of the biggest differences in making a new script and a new coroutine is that a new script is context does not need to be created. In several cases, it can save execution time.

These features of Lua will permit miltiple threads to run alongside each other without having to make separate script instances or have to wait for the current running code block tro finish. You may be curious how to create a Coroutine. Making this is fairly simple and the things that you need to begin is a function coroutine.create(). The one parameter of coroutine.create() will be the function you wish to run like this.

1. local newThread = coroutine.create (function()
2.         Print (“hola”)
3. end)

Currently, you have made your 1st coroutine and began a new thread. But nothing has happened, is it because you have not run it. To run your coroutine, you will need to use coroutine.resume() and the parameter will be the thread you made.

1. local newThread = coroutine.create (function()
2.        print (“hola”)
3. end)
4.
5. Coroutine.resume (newThread)

So, the output will be:

1. Hola

You may want to call parameters in your coroutine’s function, then what you will need to do that with is coroutine.resume () like so:

1. local newThread = coroutine.create (function (a, b, c)
2.         Print (a*b + c)
3. end)
4.
5. Coroutine.resume (newThread, 3, 5, 6)

And the output will be:

1. 21

Now, what is coroutine.wrap()? It can be used as a replacement for coroutine.resume() and coroutine.create(). You are able to use coroutine.wrap() on the function such as coroutine.create () but you will use the variable that you assign it to like a function. You are able to think of coroutine.wrap() as a function with a coroutine shoved in it. You can do as follows.

1. local newThread = coroutine.wrap (function()
2.       Print (“Hola”)
3. end)
4.
5. newThread ()

And the output will be:

1. Hola

In case you want to add in parameters, you can do it like you would any other function.

1. local newThread = coroutine.wrap (function (a, b, c)
2.      Print (a * b + c )
3. end)
4
5. newThread (8, 2, 1)

And the output will be like this:

1. 17

Actually, what are coroutines really useful for? You may have this kind of question on your mind. You have studied a couple of the coroutines functions. But, you may not know the aim of using them. One of the most useful things is creating loops and functions run at the similar time. Well, hopefully this information can help you who are still learning about Coroutine in Roblox. If you think that you are not satisfied with this, you can learn from any other resources.

Leave a Reply

Your email address will not be published. Required fields are marked *