teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.1k stars 108 forks source link

Generate cleaner codes for nil check #556

Closed pigpigyyy closed 2 years ago

pigpigyyy commented 2 years ago

Have been using an idiom to notice user to do a nil check before using some API results.

local record R
   f: function()
end
local function get(): R | nil
end
local r = get()
if not r is nil then
   r.f()
end

And currently r is nil is being generated to (type(r) == "nil"), could make it to be just (r == nil).

github-actions[bot] commented 2 years ago

Teal Playground URL: https://556--teal-playground-preview.netlify.app

lenscas commented 2 years ago

wouldn't this potentially break for tables/userdata that implement their own comparison? As there a == nil can mean something else than type(a) == "nil"

pigpigyyy commented 2 years ago

The __eq metamethod will only be invoked when Lua find both side items from "==" expression to be tables or userdata.

lenscas commented 2 years ago

Ok. Sounds weird but then I guess this indeed doesn't break anything/change behaviour.

hishamhm commented 2 years ago

@pigpigyyy Nice, thank you!