Function Default Argument Declaration

As a Roblox developer, it is currently very space-inefficient to create default function arguments. Currently, a minimum of three lines must be added per default argument, which can equate to a large amount of space within a library or utility. This additionally is much harder to read.

If Roblox is able to address this issue, it would improve my development experience because it would allow me to quickly, and easily declare default arguments in a function without the need for many extra lines, and would improve the readability of scripts.

I believe default argument declaration should follow this syntax, as it feels most lua-like to me, and meshes with luau type declaration:

function(argument1, argument2="abc", argument3, ...)
    -- Code
end

With luau type checking it could simply follow the same syntax as variable type declarations:

local myVariable: type = "Abc"

This would be equivalent to the following:

function(argument1, argument2, argument3, ...)
    if argument2 == nil then
        argument2 = "abc"
    end
    -- Code
end

This takes up a lot of extra space, and takes longer to write. I often end up copy-pasting those three lines in a lot of my scripts, which, while it’s slightly faster, I can’t easily reserve my clipboard for other things I may need it for, and it still takes up 3 extra lines of code for this logic.

14 Likes

Workaround: If you care about lines, this takes 1 extra line:

argument2 = argument2 == nil and "abc" or argument2

or if argument2 was never meant to be false:

argument2 = argument2 or "abc"
4 Likes

Would the default be used whenever nil was passed?

local function f(arg="abc")
    print(arg)
end
f(nil) -- nil or abc?

If it only used the default with none

local function withNone(...)
    if select("#",...) == 0 then
        print"abc"
    else
        print((...))
    end
end
withNone() -- abc
withNone(nil) -- nil

Or with none and nil

local function withNoneAndNil(arg)
    print(arg == nil and "abc" or arg)
end
withNoneAndNil() -- abc
withNoneAndNil(nil) -- abc

And how would this work with variadic functions?

It should be none or nil otherwise you could not pass arguments after a default one (this is also how roblox functions work). With variadic functions a default argument would be consumed like any other argument would be, so no changes there. It’d basically just be equivalent to argument = (argument ~= nil and argument) or default being prefixed to script code, so its more syntactic sugar (same with js), however, it greatly reduces script size and improves readability imo.

1 Like

This would make false also use the default
(false ~= nil and false) or "abc"
(true and false) or "abc"
false or "abc"
"abc"

With variadic functions I mean how would ... work with a default argument?

local function f(a=1, -- obvious
                 ...=2) -- ???
end

Ah, my bad yeah my brain died lol. I meant what FieryEvent said.