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

Revive `boolean` type #227

Open snoopcatt opened 3 years ago

snoopcatt commented 3 years ago

Hello! I'm here to resurrect the boolean type. Looks like it was dead a long time ago and buried in source code.

As for current Ravi version, there is zombie boolean type. Look:

local function bool(b: boolean)
        print(b, ravitype(b))
end

bool(true)

ravi: /home/ann/bool.ravi:0: type mismatch: expected boolean

Literally, boolean type exists, but it just does not work -- nor true nor false are "not boolean".


After some necromancy, boolean shows signs of life.

local function bool(b: boolean)
    print(b, ravitype(b))
end

bool(true)
bool('world')

true boolean src/ravi: /home/ann/bool.ravi:0: boolean expected

That works too:

local b: boolean = true
b = 123

src/ravi: b.ravi:4: Invalid assignment: boolean expected near <eof>

But I could forget to add it somewhere, please, double check it.

XmiliaH commented 3 years ago

It should be discussed if

local x:boolean
x = (function() return 1 end)()
print(x)

should error, since 1 is no boolean or convert 1 to a boolean. As

local x:number
x = (function() return "1" end)()
print(x)

does for strings.

snoopcatt commented 3 years ago

I think it shouldn't. Because in Lua representation, anything that is not nil or false considered as true.

It means that both 0 (number) and "0" (string) are true (boolean) in Lua world. Besides 0 and "1" we have also "true" and "false" strings.


But we may discuss implementation of explicit cast to @boolean(var). It should return:

function toboolean(v)
  if (v == 1 or v == '1' or v == 'true' ) then return true elseif (v == 0 or v == '0' or v == 'false') then return false end
end
snoopcatt commented 3 years ago

It should be discussed if

I implemented it in second commit. Seems to be working.

function test(i: integer) -- boolean
    return @boolean(i)
end

local x:boolean
x = (function() return 1 end)()
print(x)

print(test(1))

true true

But now I don't know, good it or bad, that string/number converting to boolean sometimes lol

dibyendumajumdar commented 3 years ago

In general - boolean is a dubious type in Lua. It was added just to allow something like NIL value in a table. Roberto has said many times he regrets adding this type. I want to understand what is the benefit of adding this type? Is there a good use case?