... in a function, whats that all about?

I am learning lua and I recently came across this code, while I can understand a bit of it can someone explain all of the steps here? Any answer is greatly appreciated.


function average(...)    
 result = 0    
 local arg = {...}    
 for i,v in ipairs(arg) do       
  result = result + v    
 return result/#arg 
print("The average is",average(10,5,3,4,5,6))

What is arg and what is the three ... dots, how does this work?

1 Like

When you call a function, it sometimes returns a variable. In this case, it is returning the average of the numbers fed in. The 3 dots just represents all of the arguments. Arguments are data fed into the function.

function addnums(...)
    sum = 0
    --create a table listing the numbers
    local numbers = {...}
    -- loop through the numbers and add the numbers
    for i, v in ipairs(numbers) do
        result += v
    return result
-- in this case, the arguments are 3, 4 and 6
addnums(3, 4 ,6)

So by doing this I can pass unlimited args into the function?
the … in the parentheses are the same as the … in the numbers?

Agro is basically the distance of something

You can pass as many arguments into the function as you want, but keep it as low as possible to not harm readability. The … represents the arguments passed into the function, so {…} would just be those arguments in an array.

1 Like

The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg . Besides those arguments, the arg table has an extra field, n , with the actual number of arguments collected.

Basically ... means that the function is accepting any number of arguments. But when using this in the script it’s referenced as arg, which is a table. The offical lua website goes into depth listed so I would recommend reading it, Programming in Lua : 5.2

1 Like

So what does distance mean, the args?

1 Like
local args = {...} -- instead of 1, 2, 3, 4, 5; it becomes {1, 2, 3, 4, 5}
1 Like

Oh thanks, where is this source from?

Just added it to my post, whoops.

Here is the wiki page: Functions | Roblox Creator Documentation

1 Like

yes for an example if I did a gun and I only wanted it to shoot 50 studs straight and it detects a player if the player is more then 50 studs away the gun wont shoot.

1 Like

EDIT: I changed the title so people will find this topic if they have a similar question