dibyendumajumdar / ravi

Ravi is a dialect of Lua, featuring limited optional static typing, JIT and AOT compilers
http://ravilang.github.io/
Other
1.16k stars 60 forks source link

Optional function arguments #229

Open snoopcatt opened 3 years ago

snoopcatt commented 3 years ago

Hello. Let's summarize our discussion on that.

Nowadays Ravi lacks of support optional annotated function arguments. For example, you can't do thing like that:

function sum(a: integer, b: integer, c: integer?)
  return a + b + (c or 0)
end

Of course, you can use any type, but then you have to add additional type check inside function to ensure that third argument is a integer.

Alternatively (or simultaneously☺), it can be implemented with Union types:

function sum(a: integer, b: integer, c: integer|nil)
  return a + b + (c or 0)
end
dibyendumajumdar commented 3 years ago

I prefer the former syntax - mainly because it is simpler to use, and also union types unless fully supported do not make sense.

dibyendumajumdar commented 3 years ago

There are some issues to consider. What would it mean for this:

local x: string

The reason this type is NIL or string today is that above is valid, and creates a local with NIL value to start with. If we change this then every such local variable will need to be initialized to type specific default value. Okay for strings maybe but what is the default value for userdata? Or function?

dibyendumajumdar commented 3 years ago

Perhaps we should leave existing declaration semantics as union of NIL + type, but add new syntax for function arguments where stronger assertion is needed. Also @type operator could be strong assertion.

One possible solution is:

function x(s: string nonil) 
end

Or if @type assertion is made a strong one, then

function x(s @string) 
end