sum - Why is this function to add the contents of a table together in Lua returning nothing -
i stuck trying make contese of table (all integers) add form 1 sum. working on project end goal percentage. putting various quantities , storing them in 1 table. want add of integers in table sum. haven't been able find in standard library, have been tyring use this:
function sum(t) local sum = 0 k,v in pairs(t) sum = sum + v end return sum
however, not giving me after return sum.... , appreciated.
a more generic solution problem of reducing contents of table (in case summing elements) outlined in answer (warning: no type checking in code sketch).
if function not returning @ all, because missing end
statement in function definition.
if function returning zero, possible there problem table passing argument. in other words, parameter t
may nil
or empty table. in case, function return zero, value local sum
initialized.
if add print (k,v)
in loop debugging, can determine whether function has add. try:
local function sum ( t ) print( "t", t ) -- debugging: should not nil local s = 0 k,v in pairs( t ) print(k,v) --for debugging s = s + v end return s end local mytestdata = { 1, 2, 4, 9 } print( sum( mytestdata) )
the expected output when running code is
t table: [some index] 1 1 2 2 3 4 4 9 16
notice i've changed variable name inside function sum
s
. it's preferable not use function name sum
variable holding sum in function definition. local sum
in function overrides global one, example, couldn't call sum()
recursively (i.e. call sum()
in definition of sum()
).
Comments
Post a Comment