Does this return void or a | any

Hello developers,

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

Will it return void?

sorry i actually have a question about this. is type checking right? what does “?” mean and how did you get “a”

i wish i could help but i dont really understand

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

Yes, having an empty return (or no return at all) will return as nil (lua’s void equivalent)

okay and bar is basically “or” right? so its just a or nil.

1 Like

Well, I want to know if it will return void, or whatever it returns in the if statement.

Yes, | is just or. ? is 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.

1 Like

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.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.