Moonscript, add a function/method to an object?

210 views Asked by At

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.

3

There are 3 answers

0
leafo On

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
1
huli On

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.

0
nonchip On

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