How to call a function from moonscript in lua?

547 views Asked by At

I've got a moon script code like this:

hello = (name) ->
  print "Hello #{name}!"

And i want to use it in my lua code using moonscript.loadfile

how should i do something like that?

1

There are 1 answers

0
leafo On BEST ANSWER

MoonScript code compiles to Lua, so the function you've written is actually a Lua function when it's being executed.

There are a few ways to get access to it in Lua:

  • Compile the file ahead of time using the moonc command line tool. This will give you a a .lua file that you can load as you would any other Lua file.
  • Load the file using one of the MoonScript loader function. moonscript.loadfile is a lower level function, and I don't recommend using it unless that's what you specifically need. The easiest way is to call require "moonscript" in your program, then Lua's require function is augmented to be able to load MoonScript files directly. There's more information on the Compiler API reference page.

Keep in mind that if you have function in another file, you need to export them as part of the module. You do this by having a return value for the module. The typically pattern is to return a table that contains all the function you would want to use. In MoonScript, the last line in a file is automatically converted into a return statement. Assignment is no coerced into a return though, so I recommend structuring your module like this:

hello = (name) ->
  print "Hello #{name}!"

{:hello}