function Function(functionArg)
local funcStr = tostring(functionArg)
if string.match(funcStr, "^function: "..string.rep("%w", 18).."$") then
print("Is a function.")
else
print("Is not a function.")
end
end
Function(function() end)
Yes, and it looks just like that. But this is just a static analysis; it doesn’t actually enforce code to adhere to it. If you add --!strict on the first line of your script, it will underline code in red that violates the types.
If you want to enforce during runtime, you’ll have to use assertions.
type Function = (any) -> nil
function Function(Function: Function)
end
so this seems to work fine
my only concern is if it will work every time
the Function type checks all types and if the value isn’t any of those types it works
I doubt functions are the only thing excluded from the type list, so I am not sure if this only works on functions or not
You can write what type the function will return and the type of parameters that will be returned too.
local function addNumbers(a: number, b: number): number
return a + b
end
addNumbers(1, 2)
In the example I’ve displayed above, the a and b parameters return a number and : number written right next to the function parenthesis is the type of value the function will return.
function Function(fn:(any)) : any
--:(any) can be replaced, for an instance - :(string)
--It reflects the args that need to be passed by into a given function "fn"
return fn :: any
end
Function(function()
end)
Function("")
--Error, type "string" can't be converted to type "([typecheck])"
P.S. Indeed I didn’t mean to revive old topics but came upon searching for the function type-check and immediately got an answer so I decided to note it here.