1

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 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.