lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I had to teach a class on Lua last year. I was surprised that the students could understand the concept of coroutines quite easily once presented as 'functions that you can pause and later resume'. On the other hand I think first-class functions with lexical scoping is a very important benefit of Lua. 

There were several gasps of comprehension in the class when I demonstrated the use of upvalues in creating independent counters:

function counter()
	local count = 0				
	return function()				-- wow, dynamically allocated anonymous functions + functions as return values
		count = count + 1			-- function closes over variable 'count'; becomes an upvalue
		return count
	end
end

c1 = counter()
c2 = counter()

print(c1())
print(c1())

print(c2())

print(c1())

I'm not sure that all the students really understood what was going on here. But they could see why it was useful. But then turning this into a coroutine, nobody seemed to find it strange:

function counter()
	for count = 1, math.huge do
		yield(count)
	end
end

c1 = create(counter)
c2 = create(counter)

print(resume(c1()))
print(resume(c1()))

print(resume(c2()))

print(resume(c1()))


(In general I found it useful to explain Lua by doing the same thing several times in very different ways.)

On Feb 1, 2011, at 5:05 AM, steve donovan wrote:

> On Tue, Feb 1, 2011 at 2:50 PM, Steve Litt <slitt@troubleshooters.com> wrote:
>> to salivate about them. How could I, within 5 minutes, demonstrate a wonderful
>> benefit of coroutines?
> 
> Look at
> 
> https://github.com/stevedonovan/lua-cookbook/blob/master/src/book/en_US/intro.md
> 
> and search for 'coroutines'.  It's the classic
> turn-a-recursive-function-into-an-iterator example.
> 
> steve d.
>