Coroutineها در لوا
برنامهنویسی همروند با coroutine.create، resume و yield
Coroutine چیست؟
Coroutine (کوروتین) تابعی است که میتواند متوقف و از سر گرفته شود! فرق آن با thread معمولی: کوروتینها همزمان نیستند — در هر لحظه فقط یکی اجرا میشود.
کوروتینها برای: تولیدکنندهها (generators)، iteratorهای پیچیده و کارهای مرحلهای عالی هستند.
چهار تابع اصلی
| تابع | کار |
|---|---|
coroutine.create(f) | ساخت کوروتین از تابع |
coroutine.resume(co, ...) | اجرای ادامه کوروتین |
coroutine.yield(...) | توقف و بازگرداندن مقادیر |
coroutine.status(co) | وضعیت: suspended/running/dead |
مثال ساده
local co = coroutine.create(function()
print("شروع")
coroutine.yield() -- توقف اینجا
print("ادامه")
end)
coroutine.resume(co) -- شروع چاپ میشود
coroutine.resume(co) -- ادامه چاپ میشود
print(coroutine.status(co)) -- dead
تبادل داده با yield و resume
local co = coroutine.create(function(a, b)
local c = coroutine.yield(a + b) -- ارسال نتیجه، دریافت جدید
coroutine.yield(c * 2)
end)
local ok, sum = coroutine.resume(co, 10, 5)
print("مجموع:", sum) -- 15
coroutine.resume(co, 100)
coroutine.wrap — سادهتر
-- wrap یک تابع معمولی برمیگرداند
local gen = coroutine.wrap(function()
for i = 1, 5 do
coroutine.yield(i * i) -- هر بار یک مربع
end
end)
print(gen()) -- 1
print(gen()) -- 4
print(gen()) -- 9
مثال عملی: تولیدکننده فیبوناچی
local function fibGen()
return coroutine.wrap(function()
local a, b = 0, 1
while true do
coroutine.yield(a)
a, b = b, a + b
end
end)
end
local fib = fibGen()
for i = 1, 10 do
print(fib())
end
کوروتینها در بازیسازی خیلی کاربردیاند: صحنههای سینمایی، دیالوگهای مرحلهای و AI همه با کوروتین نوشته میشوند!
این مبحث بخشی از دوره آموزش کامل لوا است.