Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,094 questions

40,775 answers

573 users

How to use function with variadic arguments in Lua

2 Answers

0 votes
function average(...)
   result = 0
   local arg = {...}
   for i, n in ipairs(arg) do
      result = result + n
   end
   return result/#arg
end

print(average(3, 7, 8, 2, 6, 9))





--[[
run:
  
5.8333333333333
 
--]]

 





answered Sep 25, 2020 by avibootz
edited Sep 25, 2020 by avibootz
0 votes
function f(...)
   local arg = {...}
   for i, n in ipairs(arg) do
      print(i, n)
   end
end

f(43, 67, 98, 12, 46, 90)





--[[
run:
  
1	43
2	67
3	98
4	12
5	46
6	90
 
--]]

 





answered Sep 25, 2020 by avibootz
edited Sep 25, 2020 by avibootz

Related questions

1 answer 112 views
112 views asked Sep 25, 2020 by avibootz
1 answer 106 views
1 answer 108 views
108 views asked Sep 24, 2020 by avibootz
1 answer 34 views
34 views asked Dec 21, 2022 by avibootz
1 answer 106 views
...