[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Custom loops with continue semantics. was : continue/repeat...until 	false dichotomy
- From: Pierre-Yves Gérardy <pygy79@...>
- Date: Thu, 18 Feb 2010 12:03:13 +0100
You can implement your own loops with break an continue semantics in
plain Lua using functions (and this is tested and works, unlike the
kludge I posted the other day).
The syntax is not exactly elegant, but at least it's functional ;-) :
local condition = "whatever"
w = _while (function()return  condition == true  end) .. function()
	local continue
	
	if I = "want to continue" then
		return continue        -- must be nil or false
	
	elseif I = "want to break" then
		return "break"         -- or anything bearing some truth.
		
	end
end
r = _repeat( function()
	-- Same principle as above regarding break and continue.
end ) : _until (function()return  condition == true  end)
of course, condition must be an upvalue to both functions.
The implementation is simple:
do
	local mt ={
		__concat=function( c, f )
			local cond = c[1]
			while  cond() and not f()  do end
		end
	}
	_while = function(c) return setmetatable( {c}, mt ) end
end
_repeat = function(f)
	return {
		f=f;
		_until = function(self,c)
			local func=self.f
			while not (func() or c()) do end
		end
	}
end
There's a 7.8 speed penalty in Lua 5.1, but almost none in LuaJIT (see
the other thread for the details)
The _for loops are left as an exercise for the reader :-)