moonscript icon indicating copy to clipboard operation
moonscript copied to clipboard

Document that @name is a method call if self.name is a function

Open bpj opened this issue 4 years ago • 4 comments

Please consider these three expressions:

  1. @\foo bar, @baz
  2. @foo bar, @baz
  3. @.foo bar, @baz

Currently 1 and 2 both compile into

self:foo(bar, self.baz)

while 3 compiles into

self.foo(bar, self.baz)

with 2 interpreted as a method call, which I find rather confusing. I did rather expect 2 to be interpreted like 3, especially since non-calling context @baz compiles to self.baz in all cases!

I'm not sure that this is a bug (I have not found it in the documentation) but it seems inconsistent.

bpj avatar Mar 16 '21 10:03 bpj

There is a small snippet in the documentation that kind of alludes to this, but is definitely not clear enough:

The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua’s colon syntax.

I would definitely welcome (as a user) a clarification on the docs. Perhaps it could be PR'd.

Regardless, I'm pretty sure that it is expected behavior that @foo is self.foo unless @foo is a function call. @foo is generally preferred over @\foo, at least in all instances of MoonScript code I've seen. The MoonScript compiler source itself uses this syntax with the current compiled behavior. As such, I doubt this is a bug or that it will change at all.

daelvn avatar Mar 16 '21 12:03 daelvn

Thanks for your input

Apart from having to decide whether to eyeball through ~600 lines of code to insert dots in sundry places or to wrap some non-method functions adopted from other libraries in methods I can live with it even though IMO it is an inconsistency (and I'll probably keep writing self-method calls as @\foo since it makes them easy to spot!) It definitely should be clearly documented though. I'll probably do a PR if I find an obvious place to put it.

bpj avatar Mar 16 '21 15:03 bpj

How it works is intentional.

  • @hello "world" is shorthand for self\hello "world"
  • @hello is shorthand for self.hello

Since both of these operations are the most common uses of self, they are made easily accessible with the @ operator directly

leafo avatar Mar 18 '21 23:03 leafo

I realize that it is intentional, but I still think the docs should explain it explicitly. I have taken to always using the explicit @\method @.other syntax since I think it leads to fewer bugs. I may be showing my age in more than one way, but I'm more comfortable this way.

bpj avatar Mar 09 '23 10:03 bpj