Lua wrap()

krushnarout's avatar
Published Oct 17, 2023
Contribute to Docs

The wrap() function makes a coroutine and gives back a function. When that function is called, it resumes the coroutine.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours

Syntax

coroutine.wrap(function)
  • wrap() is a function in Lua that creates a coroutine and returns a function that, when called, resumes the coroutine.
  • It is similar to coroutine.create(), but instead of returning the coroutine itself, it returns a function that can be called multiple times to resume the coroutine.

Example

This example utilizes the wrap() function to execute a wrapped coroutine, printing a specific message.

function myCoroutine()
print("Hello from coroutine wrap!")
end
local wrappedCoroutine = coroutine.wrap(myCoroutine)
wrappedCoroutine()

This will output:

Hello from coroutine wrap!

All contributors

Contribute to Docs

Learn Lua on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours