I have an optional callback function, is the following format correct?
callback: (() -> ())?
It appears slightly differently compared to when it is callback: () -> ()
which is why I want to make sure.
I have an optional callback function, is the following format correct?
callback: (() -> ())?
It appears slightly differently compared to when it is callback: () -> ()
which is why I want to make sure.
This means that the function can be nil
(that is not exist), () -> ()
indicates that the function always exists.
It is useful if sometimes the function is not established or when the property of the table begins as nil
.
What changes are there with this? This warning will appear
How is it solved? Adding an if
.
type F = () -> ()?
local myFunction: F = nil :: any
if myFunction then
myFunction()
end
If there is no If
and the function is still nil
, there will be an error.
attempt to call a nil value
Thanks for the reply, but I am already aware that you need to check if the function exists before calling it. My question is whether the syntax func: (() -> ())?
is correct to make func
optional (could be nil).
You wrote this here, is this the correct syntax? This does not seem to be right because I get an error.
Honestly makes sense to give that type to a function that is already defined in the variable.
But well, the correct way is so:
local Something = function()
end :: () -> ()?
or
local Something: () -> ()? = function()
end