From 8d0074634f970668732c492bd586e2a5f4b52684 Mon Sep 17 00:00:00 2001 From: ruby0x1 Date: Thu, 3 Dec 2020 09:22:06 -0800 Subject: [PATCH] update documentation for WrenLoadModuleResult --- .../embedding/configuring-the-vm.markdown | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/doc/site/embedding/configuring-the-vm.markdown b/doc/site/embedding/configuring-the-vm.markdown index 2c293557..39b6f425 100644 --- a/doc/site/embedding/configuring-the-vm.markdown +++ b/doc/site/embedding/configuring-the-vm.markdown @@ -47,22 +47,53 @@ for a module. The signature of this function is:
-char* loadModule(WrenVM* vm, const char* name)
+WrenLoadModuleResult loadModule(WrenVM* vm, const char* name)
 
When a module is imported, Wren calls this and passes in the module's name. The -host should return the source code for that module. Memory for the source should -be allocated using the same allocator that the VM uses for other allocation (see -below). Wren will take ownership of the returned string and free it later. +host should return the source code for that module in a `WrenLoadModuleResult` struct. + +
+WrenLoadModuleResult myLoadModule(WrenVM* vm, const char* name) {
+  WrenLoadModuleResult result = {0};
+    result.source = getSourceForModule(name);
+  return result;
+}
+
The module loader is only be called once for any given module name. Wren caches the result internally so subsequent imports of the same module use the previously loaded code. If your host application isn't able to load a module with some name, it should -return `NULL` and Wren will report that as a runtime error. +make sure the `source` value is `NULL` when returned. Wren will then report that as a runtime error. -If you don't use any `import` statements, you can leave this `NULL`. +If you don't use any `import` statements, you can leave the `loadModuleFn` field in +the configuration set to `NULL` (the default). + +Additionally, the `WrenLoadModuleResult` allows us to add a callback for when Wren is +done with the `source`, so we can free the memory if needed. + +
+
+static void loadModuleComplete(WrenVM* vm, 
+                               const char* module,
+                               WrenLoadModuleResult result) 
+{
+  if(result.source) {
+    //for example, if we used malloc to allocate
+    our source string, we use free to release it.
+    free((void*)result.source);
+  }
+}
+
+WrenLoadModuleResult myLoadModule(WrenVM* vm, const char* name) {
+  WrenLoadModuleResult result = {0};
+    result.onComplete = loadModuleComplete;
+    result.source = getSourceForModule(name);
+  return result;
+}
+
### **`bindForeignMethodFn`**