Function arguments don’t have to be limited to singular values.
Because arrays are often used to store large amounts of data, it’s imperative that we can pass tables as function arguments.
Here we define a function that accepts an array argument and prints out the sum of all the numbers.
local function printArraySum(valuesList)
local sum = 0
for _, value in ipairs(valuesList) do
sum = sum + value
end
print(sum)
end
local valueList = {1, 2, 4, 8, 16}
printArraySum(valueList) --Output: 31
Parameter Structure
While there is not a limit to how many parameters a function can accept, it becomes a bit of a mess to maintain after the first several. Another guideline is to create a function that requires a few arguments as you can get away with.
Once you go beyond about three, its worth considering if you’re asking the function to do too much and if you can abstract another function from it.
Sometimes however, it might not be possible to pass just a few arguments.
Or attempting to limit the number of arguments only leads to a convoluted mess of fragmented, trivial, single use functions that differ little.
local function createPart_at_position(positionV3) end
local function createPart_at_cframe(cframe) end
local function createPart_with_brickColor(brickColor) end
--- etc...
So instead, one strategy is to create a table will contain all of the the settings and pass that table as the argument instead.
local function createPart(partSettings)
local part = Instance.new("Part")
part.BrickColor = partSettings["brickColor"] or part.BrickColor
part.Position = partSettings["position"] or part.Position
part.CFrame = partSettings["cframe"] or part.CFrame
part.Size = partSettings["size"] or part.Size
part.Anchored = partSettings["anchored"] or part.Anchored
part.Material = partSettings["material"] or part.Material
part.Parent = game.Workspace
end
local newPartSettings = {
["position"] = Vector3.new(2, 4, 6),
--["brickColor"] = BrickColor.new("Magenta"),
["material"] = Enum.Material.DiamondPlate,
["anchored"] = true
}
createPart(newPartSettings)
By creating a parameter structure and implementing default arguments in the function, this allows us to selectively define some settings while leaving the others to the default settings.
And by organizing the code strategically, we can quickly toggle settings.