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

Is there a way to set default parameter values?

Instead of having to define every parameter every time, is there a way to select a default?

I know in some languages it's possible to do something like this:

function myNewFunc(defaultVar = true)
	--do code
end

So that if defaultVar doesn't get a value passed in it'll be true.

I'd like a simpler way than this:

function myNewFunc(defaultVar)
	if defaultVar == nil then 
		defaultVar = true;
	end
	--do code
end

Any insights?

2 answers

✓ Accepted answer

There is no shortcut built into Lua to do such a thing.

However, instead of using an if statement you could use a conditional expression:

####Example:

function myFunction(a, b, c, d)
	a = a or 7
	b = b or "String"
	c = c or Vector3.new()
	d = d or true
	-- code
end

2 comments

0

I wish Lua had the same syntax as Python when it comes to declaring parameters, so you can just have the statement within the parenthesis :p

0

for default values

No, there is no simpler way to do it, unless you create another function that you just run to set the value. E.G;

function setDefault(val)
	if val == nil then
		return true
	else
		return val
	end
end

function funcName(defaultParam)
	defaultParam = setDefault(defaultParam)
end

This doesn't really count as simpler, though.

Hope I helped :)

~TDP

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