leafo / moonscript

:crescent_moon: A language that compiles to Lua
https://moonscript.org
3.19k stars 190 forks source link

Range comparison #356

Open aleclarson opened 6 years ago

aleclarson commented 6 years ago
if 1 < x < 2
  print '`x` is between 1 and 2 (non-inclusive)'

..would compile to:

if x > 1 and x < 2 then
  print('`x` is between 1 and 2 (non-inclusive)')
end
RyanSquared commented 6 years ago

This is definitely something I miss from Python; however, I do think it should compile to if 1 < x and x < 2 - definitely a nitpick, but I think it'd help with debugging/looking at compiled code.

vendethiel commented 6 years ago

Definitely what @RyanSquared said, it also prevents surprised with overloaded operators. Should cache the middle one as well, in case it has side-effects.

RyanSquared commented 6 years ago

Right so it'd compile to local _comparison_0 = x ; if 1 < _comparison_0 and _comparison_0 < 2.

aleclarson commented 6 years ago

The local declaration is only necessary if doing x.y or x!, or could x really have a side effect?

RyanSquared commented 6 years ago

It actually is necessary. Example:

setmetatable(_ENV, {__index = coroutine.wrap(function()
  local n = 1
  while true do
    coroutine.yield(n)
    n = n + 1
  end
end)})
print(a, a, a)

Now, if you do this yourself, why. However, it still is a side effect.

aleclarson commented 6 years ago

Touché.
This is a nitpick, but maybe _cmp_0 would be a more concise (yet just as clear?) name for the compiled result. ¯\(ツ)

RyanSquared commented 6 years ago

(side note: I've never seen such a snarky looking shrug)

And yeah, that was just a quick example; I'd be fine with _cmp_0 given how popular "cmp" is as a shortening of the word, not that it should matter much outside of debugging anyways.