Creating a TON618 module — full guide
#1. Where modules live
IMPORT://name looks for name.ton in two places, in order:
- The same directory as the script that imports it.
- A
modules/subdirectory next to that script.
So a project can keep one-off helpers next to the script, and shared code under modules/.
#2. What a module can declare
A module file is just a normal .ton file: it can declare variables and functions (ton.function), and everything it declares becomes available in the importing script's global scope once imported. A module isn't a separate namespace — there's no mathutils.add(...) syntax; you call add(...) directly (see the naming convention below).
#3. A worked example
modules/greetings.ton:
ton.function greetings_hello(name) {
return "Hello, " + name + "!"
}
ton.function greetings_bye(name) {
return "Goodbye, " + name + "."
}
Using it:
IMPORT://greetings
print(greetings_hello("kuro"))
print(greetings_bye("kuro"))
#4. Best practices for writing a module
- Prefix every function with the module's own name (
greetings_hello, nothello) — since importing flattens everything into one global scope, this is the only thing preventing two modules (or a module and the main script) from silently overwriting each other's functions. - Keep a module focused on one concern; compose several small modules rather than one large one.
- A module is only executed the first time it's imported — importing the same name twice (from anywhere) is a no-op the second time, so it's safe for two different modules to both import a third one they both depend on.