Key differences between a variadic function, and a table of data

Lets say I’m making a class. I have the option of giving the constructor a table of constructor arguements, or a variadic function, such as:

function Class.new(...)
	local Args = ... 
end

function Class.new(Data)
	local Args = unpack(Data)
end

Both ways are variadic in a way. If “Data” is an array of comma separated strings for example (like seen in the print global), we don’t have to update our constructor code in anyway to accomodate anything else in the Data table which is passed, which is the same for the variadic syntax.

So, while I find variadics more aesthetic, I’m curious to the solid things that make them different.

1 Like

Move this to #help-and-feedback:scripting-support . No one’s gonna help you here.

1 Like

I would always prefer a table argument as it allows to fully utilize Luau typecasting, and make the values passed to the constructor more obvious.

export type PetData = {
  Name: string,
  Power: number,
  Color: Color3
}

local PetClass = {}

PetClass.new = function(data: PetData)
  -- ...
end
PetClass.new({
  Name = 'Dog',
  Power = 20,
  Color = Color3.new(1, 1, 1)
})

-- vs

PetClass.new('Dog', 20, Color3.new(1, 1, 1))

Additionally, when working with huge amount of parameters, you might find the builder design pattern useful.

Keep in mind that Lua is not fully suitable for object-oriented programming so it’s not necessarily the best approach.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.