# lua的多种实现方式(1-100的和)

function add( a, b )
return a + b
end

-- print( add( 10, 20 ) )

function loopT( T )
for i, v in ipairs( T ) do
print( i, v )
end
end

-- loopT{ 10, 20, 30, 40, 50, 100 }

function show( str )
print( str )
end

--show "hello baby"

-- get sum of 1.....100

function calc( start_num, end_num  )
local sum = 0
for i = start_num, end_num do
sum = sum + i
end
return sum
end

--print( calc( 1, 100 ) )

function calc2( start_num, end_num )
local sum = 0
local i = start_num
while i <= end_num do
sum = sum + i
i = i + 1
end
return sum
end

-- print( calc2( 1, 100 ) )

function calc3( start_num, end_num )
local sum = 0
local i = start_num
while true do
sum = sum + i
i = i + 1
if i > end_num then break end
end
return sum
end

-- print( calc3( 1, 100 ) )

function calc4( start_num, end_num )
local sum = 0
local i = start_num
repeat
sum  = sum + i
i = i + 1
until i > end_num
return sum
end

-- print( calc4( 1, 100 ) )

function calc5( start_num, end_num )
local T = {}
for i = start_num, end_num do
T[i] = i
end

local sum = 0
for i, v in ipairs( T ) do
sum = sum + v
end

return sum
end

-- print( calc5( 1, 100 ) )

posted @ 2018-06-28 09:12  ghostwu  阅读(509)  评论(0编辑  收藏  举报