lua-users home
lua-l archive

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

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.

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:

	local mt ={
		__concat=function( c, f )
			local cond = c[1]
			while  cond() and not f()  do end

	_while = function(c) return setmetatable( {c}, mt ) end

_repeat = function(f)
	return {
		_until = function(self,c)
			local func=self.f
			while not (func() or c()) do 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 :-)