Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

[UNANSWERED] How do I make a function have optional parameters?

I'm trying to make a function to be used with a brick, and if the brick is a MeshPart then the function should accept a MeshId as a parameter. Unfortunately, I couldn't figure out how to add optional parameters. Would anyone be able to help out? Here's a simplified version of the code I'm using:

local Brick={}
function Brick.new(brickType,optionalMeshIdParameter)
	--do stuff
end
return Brick

Thanks for helping!

1 comment

0

Do you mean parameters that can have default values if no arguments are passed to them?

2 answers

✓ Accepted answer

All parameters are optional in Lua. Arguments that aren't given resolve to nil.

But I suppose what you really want to do is this:


local Brick = {}


local function Brick.new(brickType, meshId)
	if brickType == "MeshPart" then
		print(meshId)
	else
		-- Otherwise ignore second parameter.
		
		print("ignored second parameter")
	end
end


return Brick

Brick.new("MeshPart", 06748472344)  -- Prints the mesh ID.
Brick.new("Part", 06748472344) -- Prints "ignored second parameter"

1 comment

0

Awesome, thanks!

So like:

if optionalMeshIdparameter ~= nil then
 	--do more stuff?????
end

This discussion is preserved as it was. New answers, comments, and votes are closed.