Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a way to set default parameter values?

Asked by 8 years ago

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

Log in to vote
1
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

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
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 ScriptGuider 5640 — 8y
0
*for default values* ScriptGuider 5640 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

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

Answer this question