A host controls how scripts pull in other scripts by implementing
ModuleProvider. Without one, require is unavailable — a script cannot load
code the host has not sanctioned. This is the JavaScript analogue of golua's
code provider.
go run ./examples/modulesExpected output:
start distance: 5
after move: 6 4 -> 7.211102550927978
cached module identity: true
Key points:
WithModuleProvider(p)enables CommonJS-stylerequire(specifier). Each module runs in its own scope withmodule,exports,require,__filename, and__dirname.- A module's
requireresolves relative specifiers (./lib/vec.js) against that module — the provider'sResolve(specifier, referrer)does the mapping. - Modules are cached by canonical id: a module's body runs once and the same
exportsis returned on subsequentrequires (circular deps see a partialexportsrather than looping). NewMapModuleProviderserves from an in-memory map — ideal when the host already holds scripts in memory (game data files, bundled assets). Implement the two-methodModuleProviderinterface yourself to serve from a pak archive, database, or network.NewDirModuleProvider(dir)serves from a directory, confined to that root.