I am creating a optional argument function so I can easily utilize optional arguments. The problem I am having right now is that I don’t know if I do this:
function Package.optionalArgument<a>(param: a?, defaultValue: a): a
if param == nil and defaultValue ~= nil then
return defaultValue
elseif param ~= nil then
return param
end
return
end
Alright, so basically in type checking you can do this with functions: function Package.optionalArgument<a>, basically if I assign a as a type to something, the type will change to whatever it is. Also, a? is the equivalent of a | nil
The first return exists the function and returns whatever value was given. If either of the if statements are true, then it will return either defaultValue or param respectively, and this value could also be nil if the variable also happens to be nil.
Alright, I was being dumb I guess. Anyways, thanks for helping. And just to clarify once more, it should never return void right? The type checker is practically forcing me to return something when I have any sort of elseif statement above, not sure if this is a bug but I might report it.
I believe what you might be getting confused about is type declaration. When you say a variable is of type a (var: a) or that a function must return a value of type a (myFunc(): a), these declarations in lua serve essentially as a comment and do not actually force types like strictly-typed languages will. For example I can have the following code, and as far as lua is concerned, it is a completely valid function call (except that the function itself that will error)
function squareNum(num: number): string
return num^2
end
squareNum(4)
squareNum("NotANumber")
Type declarations in lua do not effect the code
Also, the idea of a template function, like what you’re doing, does not exist in lua unless that is infrastructure you have created. It appears that myFunction()<T> does not error, but as far as I know the <> syntax is just ignored.