luau
luau copied to clipboard
Default parameter values
In many other scripting languages, you can specify the default value of a function's parameter. As far as I know, luau lacks that ability. Let's take this code for example:
function RobloxAPI.new(ApiDumpUrl: string, UseCache: boolean?)
local self = setmetatable({
ApiDumpUrl = ApiDumpUrl,
UseCache = UseCache,
Data = {},
Classes = {},
Enums = {},
Version = 1
}, RobloxAPI)
local Success, Error = pcall(function()
self.Data = HttpService:JSONDecode(HttpService:GetAsync(ApiDumpUrl))
end)
assert(Success, "Could not get API data! Please double-check if the URL is valid or returns JSON.")
self:GenerateDictionaries()
self.Version = self.Data.Version
return self
end
There's no way to tell if UseCache
is nil
or false
without making it mandatory to pass as a parameter to make it true
! In PHP, however...
function sendMessage(string $apiKey, int $universeId, string $topic, $message = "Hello!") {
$curl = curl_init("https://apis.roblox.com/messaging-service/v1/universes/{$universeId}/topics/{$topic}");
$data = json_encode([
"message" => $message
]);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"x-api-key: {$apiKey}",
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => $data
]);
return curl_exec($curl);
}
You can just set the default value of a parameter and not worry about it being null. This would be a great addition to luau in the long run, and I really hope this is considered.
function add(a: number, b = 1)
LGTM!
function add(a: number, b: number = 1)
should work too.
function add(a: number, b: number = "sdfsdf"
Should this work with an analysis warning, or should it error? I'd assume the former, since that is how it would work if it was passed in anyway.
function add(a: number, b: number = "sdfsdf"
Should this work with an analysis warning, or should it error? I'd assume the former, since that is how it would work if it was passed in anyway.
I'd say it should warn unless under strict mode, seeing that type mismatching isn't bad enough for an error in any other case.
Closing this because we do not have plans to support optional parameters at this time (and the issue is 21 months old at this point).
Suggestion like this will need an RFC for it created first, with a good motivation and a potential design for the implementation. But not that proposing an RFC is not a guarantee that it will be accepted.
edit: fixed "do have" -> "do not have" as originally intended. Sorry to those who thought the feature had a chance by looking at that!