lua-users home
lua-l archive

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


Hi Walter,

> I have a little doubt. I have a lua table with some values and I neet the
> sum of them.

This probably ain't really the "lua way", 'tis definitely the
functional one tho' (deftly ignoring the loop in the code):

function foldl(f, z, t)
	local fun = function (tt)
		local r = z
		for _, v in ipairs(tt) do r = f(r, v) end
		return r
	end
	if t then
		return fun(t)
	else
		return fun
	end
end

sum_it = foldl(function (a, b) return a+b end, 0)

print(sum_it({1,2,3,4,5}))

function sum (a, b) return a+b end
print(foldl(sum, 0, {1,2,3,4,5}))


So, foldl() kinda behaves a little teensy bit curried.  You can create
a function that traverses a table by providing the "folding function"
and its neutral value, or you can get the result of the application by
providing the optional third parameter.

Robby