How to use ...?

Hello!

I am trying to create a function in a module which can take a variable number of arguments, like so:

local function test(...)
	--Stuff here
end

I was reading about how to use the ellipses, it said that when it is used in place of arguments, you can use a “hidden variable” called arg, which is a table containing the passed arguments. When I attempt to use arg I get an error:

Players.Pr0pelled.PlayerGui.Build.Populate:11: invalid argument #1 to 'pairs' (table expected, got nil)

Does LuaU handle this differently? Is there something I’m missing? I’d love to be able to use the ellipses as it will make the function much more efficient/readable.

Thanks in advance!

Ellipses are used to reference whenever a function (or method) takes several arguments which are not specified. (On another words, We can call them “Custom” Arguments)

Most of the time, You would use them in functions such as adding Values into a table, Check whenever a certain parameter is equals to something, etc.

This is what it would look like in some cases:

local function PrintArguments(...)
	-- Pack our Arguments:
	local Arguments = {...}

	-- Loop through our Arguments and Print them:
	for Index, Argument in pairs(Arguments) do
		-- Will print something like this: 1 | Hello!
		print(Index, "|", Argument)
	end
end

PrintArguments("Hello!", true, 123, {Value = 1})

local function IsThereBoolean(...)
	-- Pack our Arguments:
	local Arguments = {...}

	-- Loop through the Arguments:
	for Index, Argument in pairs(Arguments) do
		if typeof(Argument) == "boolean" then
			print("There is a boolean inside the Arguments!")
		end
	end
end

IsThereBoolean(1, 2, 3, "Test", true) -- Will print.

Thankyou, I searched deeper and found the solution just before you posted this. Thanks for the help anyways!

1 Like

https://www.lua.org/pil/5.2.html

Unlike Lua, in LuaU a function’s arguments aren’t collected in a table value which can then be accessed by a hidden parameter named “arg”.

To circumvent this missing behavior you assign the variable argument expression to some variable within the function’s body.

local function variadicFunc(...)
	local args = {...}
	for _, arg in ipairs(args) do
		print(arg)
	end
end

variadicFunc(1, 2, 3, "a", "b", "c")

Another thing worth noting, a variadic function is one which receives a variable number of arguments (one of its arguments is a variable argument expression, denoted by an ellipses ...).

1 Like