lua-users home
lua-l archive

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



Going for it myself:

-- Returns the sum of all given values (using tail recursion)
--
function sumofn( a,b, ... )
--return b and sumofn(a+b,...) or a or 0 -- not proper tail call (but works)
	return (not b) and (a or 0) or sumofn(a+b,...)	-- proper tail call
end

> print( sumofn( unpack{1,2,3,4,5,6,7,8} ) )
36
>


Asko Kauppi kirjoitti 14.12.2005 kello 18.56:


What really matters to me, is clearness, maintainability and generic "readability" of any code I write.

Sometimes, "making it Lua" may mean that you're actually making it harder for those PHP/C/etc. people to understand.

So, I'd be happy with:

	local result = 0

	for _,value in {1,2,3,4,5,6,7,8} do
		result = result + value
	end
	print(result)

Then again... :)

	local function sumofn( a, ... )
		if not a then
			return 0
		else
			return a + sumofn(...)
		end
	end

	print( sumofn( unpack{1,2,3,4,5,6,7,8} ) )

Note that the ... notation requires Lua 5.1, and the use of if/else to make sure the recursion happens with proper tail call (= not causing stack heating). Hmm.. the + might in fact cause stack heat, would someone do the above with proper tail call then? :)

-asko


Walter Cruz kirjoitti 14.12.2005 kello 16.28:

Hi all.

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

Here's is the code snippet:
_________
c = 0
function sum(v)
c = c+v
print(c)
end

values ={1,2,3,4,5,6,7,8}

result = 0
for _,value in values do
result = result + value
end
print(result)


table.foreach(values,sum)
_________

The code between result = 0 and print(result) works, but i don't think that this is the 'lua way' of doing the things. Except by the lua way of make the for loop, this could be C, PHP or javascript.

The function sum is my attempt to make it more 'lua'. It works, but all the values are printed and I have the c variable outside of the scope of the function (global). As far I know, I can do it with a closure no ?

I just wanna make my lua code more lua :)

Thanks on advance.

[]'s
- Walter