Farzher
Farzher

Reputation: 14583

Moonscript, add a function/method to an object?

How do I do this in Moonscript?

function a:do_something(b)
    print(b)
end

Nothing I tried would compile and I didn't see anything in their documentation.

Upvotes: 1

Views: 209

Answers (3)

nonchip
nonchip

Reputation: 1142

what you're looking for is class.__base:

class C
  a: (x)=> print x

C.__base.b = (y)=> @a y*2

i=C!

i\b 5
--prints 10

Upvotes: 0

leafo
leafo

Reputation: 1852

In Lua what you wrote is syntactic sugar for the following:

a.do_something = function(self, b)
  print(b)
end

So you would do just that in MoonScript. (note the => as a shorthand for adding self to the front of the function's argument list)

a.do_something = (b) =>
  print b

Upvotes: 2

huli
huli

Reputation: 101

In MoonScript you'd do:

a.dosomething = (self, b) ->
  print b

The -> and => symbols are aliases of the function keyword.

a.dosomething = (b) =>
  print b

Using the => (Fat arrow) style as above, adds the scope, ie. self, to the arguments list automatically.

Upvotes: 1

Related Questions