Lua
Coroutines
Cooperative multitasking with coroutines.
By EZ4Code Team
coroutinegenerator
Code
-- Generator: yield values one at a time
function range(a, b, step)
step = step or 1
return coroutine.wrap(function()
for i = a, b, step do
coroutine.yield(i)
end
end)
end
for v in range(1, 10, 2) do
print(v) -- 1, 3, 5, 7, 9
end
-- Producer-consumer
function producer()
for i = 1, 5 do
coroutine.yield(i * 10)
end
end
local co = coroutine.create(producer)
while coroutine.status(co) ~= "dead" do
local ok, val = coroutine.resume(co)
if val then print(val) end -- 10, 20, 30, 40, 50
endExplanation
Lua coroutines are cooperative (not preemptive) — they yield control explicitly. coroutine.create returns a thread; resume runs until the next yield; status checks 'suspended'/'running'/'dead'. coroutine.wrap is a convenience that returns an iterator function. Use coroutines for generators, state machines, and async patterns (Lua 5.3+ doesn't have true threads).
More Lua Snippets
Tables (Arrays and Maps)
Tables are Lua's only data structure — used as arrays and maps.
Metatables and OOP
Implement OOP and operator overloading via metatables.
Modules
Create reusable modules in Lua.
String Manipulation
Pattern matching and string functions in Lua.
File I/O
Read and write files in Lua.
OOP with Inheritance
Implement class inheritance using metatables.