### Wasmoon CLI Example Source: https://github.com/ceifa/wasmoon/blob/main/README.md A practical example of using the Wasmoon CLI with options to run a Lua script and pass arguments. ```sh wasmoon -i sum.lua 10 30 ``` -------------------------------- ### Download Lua Submodule and Install Dependencies Source: https://github.com/ceifa/wasmoon/blob/main/README.md Provides the necessary shell commands to initialize the Lua submodule and install Node.js dependencies for building Wasmoon. ```sh git submodule update --init npm i ``` -------------------------------- ### Async/Await limitation example Source: https://github.com/ceifa/wasmoon/blob/main/README.md Example of code that triggers a coroutine error when attempting to await inside a callback. ```js local res = sleep(1):next(function () sleep(10):await() return 15 end) print("res", res:await()) ``` -------------------------------- ### LuaGlobal.get - Get Global Variables Source: https://context7.com/ceifa/wasmoon/llms.txt The `get` method retrieves values from Lua global variables, automatically converting Lua types to their JavaScript equivalents including functions. ```APIDOC ## LuaGlobal.get - Get Global Variables ### Description Retrieves values from Lua global variables, converting Lua types to JavaScript equivalents. ### Method `lua.global.get(name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the global variable to retrieve. ### Request Example ```javascript const counter = lua.global.get('counter') const config = lua.global.get('config') ``` ### Response #### Success Response (200) - **value** (any) - The retrieved value from the Lua global variable, converted to its JavaScript equivalent. #### Response Example ```json { "value": 42 } ``` ``` -------------------------------- ### Get Lua Global Variables into JavaScript Source: https://context7.com/ceifa/wasmoon/llms.txt Use `lua.global.get` to retrieve values from Lua global variables into JavaScript. It handles automatic type conversion for primitives, tables, and functions. Ensure to close the engine when done. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Define Lua globals await lua.doString(` counter = 0 greeting = "Hello" config = { debug = true, level = 5 } function multiply(x, y) return x * y end function increment() counter = counter + 1 return counter end `) // Retrieve primitive values const counter = lua.global.get('counter') const greeting = lua.global.get('greeting') console.log(counter, greeting) // Output: 0 Hello // Retrieve table as JavaScript object const config = lua.global.get('config') console.log(config) // Output: { debug: true, level: 5 } // Retrieve Lua function and call it from JavaScript const multiply = lua.global.get('multiply') console.log(multiply(6, 7)) // Output: 42 const increment = lua.global.get('increment') console.log(increment()) // Output: 1 console.log(increment()) // Output: 2 console.log(lua.global.get('counter')) // Output: 2 } finally { lua.global.close() } ``` -------------------------------- ### Initialize Lua State and Execute Code Source: https://github.com/ceifa/wasmoon/blob/main/README.md Demonstrates initializing a Lua environment, setting global JS functions, executing Lua code, and retrieving Lua functions as JS functions. Ensure the Lua environment is closed after use. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { lua.global.set('sum', (x, y) => x + y) await lua.doString( ` print(sum(10, 10)) function multiply(x, y) return x * y end ` ) const multiply = lua.global.get('multiply') console.log(multiply(10, 10)) } finally { lua.global.close() } ``` -------------------------------- ### Build Wasmoon natively Source: https://github.com/ceifa/wasmoon/blob/main/README.md Commands to build the project natively on Ubuntu, Debian, or MacOS using Emscripten. ```sh npm run build:wasm:dev # build lua npm run build # build the js code/bridge npm test # ensure everything it's working fine ``` -------------------------------- ### Load Individual Lua Libraries Source: https://context7.com/ceifa/wasmoon/llms.txt Initialize the engine without standard libraries and selectively load only required modules to reduce footprint. ```javascript const { LuaFactory, LuaLibraries } = require('wasmoon') const factory = new LuaFactory() // Create engine without standard libraries const lua = await factory.createEngine({ openStandardLibs: false }) try { // Selectively load libraries lua.global.loadLibrary(LuaLibraries.Base) // _G, print, pairs, etc. lua.global.loadLibrary(LuaLibraries.String) // string manipulation lua.global.loadLibrary(LuaLibraries.Math) // math functions lua.global.loadLibrary(LuaLibraries.Table) // table manipulation // Available libraries: // LuaLibraries.Base, LuaLibraries.Coroutine, LuaLibraries.Table, // LuaLibraries.IO, LuaLibraries.OS, LuaLibraries.String, // LuaLibraries.UTF8, LuaLibraries.Math, LuaLibraries.Debug, // LuaLibraries.Package const result = await lua.doString(` return { upper = string.upper("hello"), sqrt = math.sqrt(16), concat = table.concat({"a", "b", "c"}, "-") } `) console.log(result) // Output: { upper: 'HELLO', sqrt: 4, concat: 'a-b-c' } } finally { lua.global.close() } ``` -------------------------------- ### Build Wasmoon with Docker Source: https://github.com/ceifa/wasmoon/blob/main/README.md Commands to build the project using Docker on Windows, Linux, or MacOS. ```sh npm run build:wasm:docker:dev # build lua npm run build # build the js code/bridge npm test # ensure everything it's working fine ``` -------------------------------- ### Await Promises in Lua Source: https://github.com/ceifa/wasmoon/blob/main/README.md Demonstrates using the :await() method on a Promise within a Lua engine instance. ```js const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { lua.global.set('sleep', (length) => new Promise((resolve) => setTimeout(resolve, length))) await lua.doString(` sleep(1000):await() `) } finally { lua.global.close() } ``` -------------------------------- ### Wasmoon CLI Usage Source: https://github.com/ceifa/wasmoon/blob/main/README.md Illustrates how to use the Wasmoon CLI to execute Lua files and enter interactive mode. Options include including files/directories and enabling interactive mode. ```sh wasmoon [options] [file] [args] ``` -------------------------------- ### Wasmoon as a Script Interpreter (Unix Shebang) Source: https://github.com/ceifa/wasmoon/blob/main/README.md Shows how to use Wasmoon as a script interpreter on Unix-like systems by adding a shebang line to a Lua script. ```lua #!/usr/bin/env wasmoon return arg[1] + arg[2] ``` -------------------------------- ### Mount Virtual Files in Lua Filesystem Source: https://context7.com/ceifa/wasmoon/llms.txt Use `factory.mountFile()` to create virtual Lua modules. These can be loaded using `require()` or executed directly with `doFile()`, enabling modular code organization. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() // Mount files before or after creating engine await factory.mountFile('utils.lua', ` local M = {} function M.add(a, b) return a + b end function M.multiply(a, b) return a * b end return M `) await factory.mountFile('config.lua', ` return { version = "1.0.0", debug = true } `) // Mount in nested directories await factory.mountFile('lib/math/advanced.lua', ` local M = {} function M.factorial(n) if n <= 1 then return 1 end return n * M.factorial(n - 1) end return M `) const lua = await factory.createEngine() try { const result = await lua.doString(` local utils = require("utils") local config = require("config") local advanced = require("lib/math/advanced") return { sum = utils.add(10, 20), product = utils.multiply(5, 6), version = config.version, factorial = advanced.factorial(5) } `) console.log(result) // Output: { sum: 30, product: 30, version: '1.0.0', factorial: 120 } // Execute mounted file directly await factory.mountFile('init.lua', 'return 42') const value = await lua.doFile('init.lua') console.log(value) // Output: 42 } finally { lua.global.close() } ``` -------------------------------- ### LuaEngine.doStringSync Source: https://context7.com/ceifa/wasmoon/llms.txt Executes Lua code synchronously. Note that Promise awaiting is not supported in this mode. ```APIDOC ## LuaEngine.doStringSync ### Description Executes Lua code synchronously. Blocks the main thread until execution completes. ### Method Sync ### Parameters #### Request Body - **code** (string) - Required - The Lua source code to execute. ### Request Example { "code": "return math.sqrt(16)" } ### Response #### Success Response (200) - **result** (any) - The result of the Lua execution. ``` -------------------------------- ### Execute Lua Script with Shebang Source: https://github.com/ceifa/wasmoon/blob/main/README.md Demonstrates executing a Lua script that uses the shebang line to be interpreted by Wasmoon. ```sh ./sum.lua 10 30 ``` -------------------------------- ### LuaFactory.createEngine Source: https://context7.com/ceifa/wasmoon/llms.txt Creates a new isolated Lua engine instance with configurable options for standard libraries, object injection, and timeouts. ```APIDOC ## LuaFactory.createEngine ### Description Creates an isolated Lua environment. The factory handles WASM module loading and environment configuration. ### Method Async ### Parameters #### Request Body - **openStandardLibs** (boolean) - Optional - Whether to include standard Lua libraries. - **injectObjects** (boolean) - Optional - Whether to inject JS objects like Error, Promise, and null. - **enableProxy** (boolean) - Optional - Enables proxy for JS objects and classes. - **traceAllocations** (boolean) - Optional - Tracks memory usage. - **functionTimeout** (number) - Optional - Maximum execution time in milliseconds. ### Request Example { "openStandardLibs": true, "injectObjects": true, "functionTimeout": 5000 } ### Response #### Success Response (200) - **LuaEngine** (object) - An instance of the Lua engine. ``` -------------------------------- ### Rollup Configuration for Wasmoon Source: https://github.com/ceifa/wasmoon/blob/main/README.md Shows how to configure Rollup with the 'rollup-plugin-ignore' to exclude specific Node.js modules when bundling applications using Wasmoon. ```javascript export default { input: 'src/index.js', plugins: [ignore(['path', 'fs', 'child_process', 'crypto', 'url', 'module'])] } ``` -------------------------------- ### LuaEngine.doString Source: https://context7.com/ceifa/wasmoon/llms.txt Executes Lua code from a string asynchronously, supporting Promise awaiting and complex data return types. ```APIDOC ## LuaEngine.doString ### Description Executes Lua code asynchronously. Returns the result of the last statement or expression. ### Method Async ### Parameters #### Request Body - **code** (string) - Required - The Lua source code to execute. ### Request Example { "code": "return 10 + 20" } ### Response #### Success Response (200) - **result** (any) - The result of the Lua execution, mapped to corresponding JavaScript types. ``` -------------------------------- ### Angular package.json Configuration for Wasmoon Source: https://github.com/ceifa/wasmoon/blob/main/README.md Demonstrates how to configure the 'browser' field in package.json for Angular projects to ignore specific Node.js modules when using Wasmoon in a browser environment. ```json { "main": "src/index.js", "browser": { "child_process": false, "fs": false, "path": false, "crypto": false, "url": false, "module": false } } ``` -------------------------------- ### Monitor and Limit Memory Usage Source: https://context7.com/ceifa/wasmoon/llms.txt Enable traceAllocations to track memory consumption and set hard limits to prevent script-induced memory exhaustion. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine({ traceAllocations: true }) try { // Get current memory usage console.log('Initial memory:', lua.global.getMemoryUsed(), 'bytes') // Run some Lua code await lua.doString(` local data = {} for i = 1, 1000 do data[i] = string.rep("x", 100) end `) console.log('After allocation:', lua.global.getMemoryUsed(), 'bytes') // Set memory limit (causes allocation failures when exceeded) lua.global.setMemoryMax(lua.global.getMemoryUsed() + 1000) try { await lua.doString(` local huge = {} for i = 1, 10000 do huge[i] = string.rep("x", 1000) end `) } catch (err) { console.log('Memory limit exceeded:', err.message) } // Remove memory limit lua.global.setMemoryMax(undefined) } finally { lua.global.close() } ``` -------------------------------- ### Create Lua Engines with LuaFactory Source: https://context7.com/ceifa/wasmoon/llms.txt Use LuaFactory to create isolated Lua environments. Configure options like standard library inclusion, object injection, proxy enablement, allocation tracking, and function timeouts. Environment variables can be passed during factory instantiation. ```javascript const { LuaFactory } = require('wasmoon') // Create a factory (automatically loads WASM module) const factory = new LuaFactory() // Create an engine with default options (opens all standard libs) const lua = await factory.createEngine() // Create an engine with custom options const customLua = await factory.createEngine({ openStandardLibs: true, // Include math, coroutine, debug, etc. injectObjects: true, // Inject JS objects: Error, Promise, null enableProxy: true, // Enable proxy for JS objects/classes traceAllocations: false, // Track memory usage functionTimeout: 5000 // Max execution time in ms }) // Use environment variables in Lua const factoryWithEnv = new LuaFactory(undefined, { MY_VAR: 'hello', DEBUG: 'true' }) const envLua = await factoryWithEnv.createEngine() const envValue = await envLua.doString(`return os.getenv('MY_VAR')`) console.log(envValue) // Output: hello // Always close the engine when done lua.global.close() ``` -------------------------------- ### Configure Execution Timeouts Source: https://context7.com/ceifa/wasmoon/llms.txt Use functionTimeout during engine creation or per-execution timeouts with threads to prevent infinite loops. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() // Set default function timeout at engine creation const lua = await factory.createEngine({ functionTimeout: 1000 }) try { // Per-execution timeout using threads const thread = lua.global.newThread() thread.loadString(` local sum = 0 while true do sum = sum + 1 end `) try { await thread.run(0, { timeout: 50 }) } catch (err) { console.log('Timeout caught:', err.message) // Output: Timeout caught: thread timeout exceeded } // Engine still usable after timeout const result = await lua.doString('return 42') console.log('After timeout:', result) // Output: After timeout: 42 } finally { lua.global.close() } ``` -------------------------------- ### Execute Lua Code Synchronously with doStringSync Source: https://context7.com/ceifa/wasmoon/llms.txt The doStringSync method executes Lua code synchronously. Note that Promise awaiting is not available in synchronous mode. This is suitable for simple, non-blocking operations. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Synchronous execution const a = lua.doStringSync('return 1 + 1') const b = lua.doStringSync('return "hello" .. " world"') const c = lua.doStringSync('return math.sqrt(16)') console.log(a) // Output: 2 console.log(b) // Output: hello world console.log(c) // Output: 4 } finally { lua.global.close() } ``` -------------------------------- ### Webpack Configuration for Wasmoon Source: https://github.com/ceifa/wasmoon/blob/main/README.md Provides a Webpack configuration snippet to resolve and ignore specific Node.js modules that might cause issues in a browser environment when using Wasmoon. ```javascript module.exports = { entry: './src/index.js', resolve: { fallback: { path: false, fs: false, child_process: false, crypto: false, url: false, module: false, }, }, } ``` -------------------------------- ### Implement Custom Metatables with decorate Source: https://context7.com/ceifa/wasmoon/llms.txt Use decorate and decorateUserdata to bind JavaScript objects to Lua metatables for operator overloading and custom indexing. ```javascript const { LuaFactory, decorate, decorateUserdata } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Create a Vector class with custom metamethods lua.global.set('Vector', { new: (x, y) => decorate({ x, y }, { metatable: { __name: 'Vector', __tostring: (self) => `Vector(${self.x}, ${self.y})`, __add: (a, b) => decorate( { x: a.x + b.x, y: a.y + b.y }, { metatable: lua.global.get('Vector').new(0, 0).metatable } ), __index: (self, key) => { if (key === 'length') { return Math.sqrt(self.x * self.x + self.y * self.y) } return self[key] } } }) }) const result = await lua.doString(` local v1 = Vector.new(3, 4) return { str = tostring(v1), length = v1.length, x = v1.x } `) console.log(result) // Output: { str: 'Vector(3, 4)', length: 5, x: 3 } // Wrap class instances with decorateUserdata class GameEntity { constructor(name) { this.name = name } greet() { return `Hello from ${this.name}` } } lua.global.set('Entity', { create: (name) => decorateUserdata(new GameEntity(name)) }) const entity = await lua.doString(` local e = Entity.create("Player1") return e:greet() `) console.log(entity) // Output: Hello from Player1 } finally { lua.global.close() } ``` -------------------------------- ### Manage Lua Coroutines and Threads Source: https://context7.com/ceifa/wasmoon/llms.txt Create and control Lua threads using manual resume cycles or asynchronous execution patterns. ```javascript const { LuaFactory, LuaReturn } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Create a new thread const thread = lua.global.newThread() // Load code into thread thread.loadString(` local input = coroutine.yield(10) local doubled = input * 2 return doubled `) // First resume - runs until yield const result1 = thread.resume(0) console.log('Yielded:', result1.result === LuaReturn.Yield) // Output: true console.log('Yield value:', thread.getValue(-1)) // Output: 10 // Pop yield result and push new value thread.pop(result1.resultCount) thread.pushValue(25) // Resume with new value const result2 = thread.resume(1) console.log('Completed:', result2.result === LuaReturn.Ok) // Output: true console.log('Final value:', thread.getValue(-1)) // Output: 50 // Async thread execution lua.global.set('asyncOp', () => new Promise(r => setTimeout(() => r(100), 10))) const asyncThread = lua.global.newThread() asyncThread.loadString(` local value = asyncOp():await() return value * 2 `) const asyncResult = await asyncThread.run() console.log('Async result:', asyncResult[0]) // Output: 200 } finally { lua.global.close() } ``` -------------------------------- ### Async coroutine workaround Source: https://github.com/ceifa/wasmoon/blob/main/README.md A Lua helper function to manage coroutine resumption and Promise integration. ```lua function async(callback) return function(...) local co = coroutine.create(callback) local safe, result = coroutine.resume(co, ...) return Promise.create(function(resolve, reject) local function step() if coroutine.status(co) == "dead" then local send = safe and resolve or reject return send(result) end safe, result = coroutine.resume(co) if safe and result == Promise.resolve(result) then result:finally(step) else step() end end result:finally(step) end) end end ``` -------------------------------- ### Async/Await error output Source: https://github.com/ceifa/wasmoon/blob/main/README.md The error message returned when attempting to yield across a C-call boundary. ```text Error: Lua Error(ErrorRun/2): cannot resume dead coroutine at Thread.assertOk (/home/tstableford/projects/wasmoon/dist/index.js:409:23) at Thread. (/home/tstableford/projects/wasmoon/dist/index.js:142:22) at Generator.throw () at rejected (/home/tstableford/projects/wasmoon/dist/index.js:26:69) ``` ```text attempt to yield across a C-call boundary ``` -------------------------------- ### Handle Lua and JavaScript Errors Source: https://context7.com/ceifa/wasmoon/llms.txt Manage exceptions using JavaScript try/catch blocks or Lua's pcall function for cross-boundary error handling. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // JavaScript try/catch for Lua errors try { await lua.doString('error("Something went wrong!")') } catch (err) { console.log('Caught Lua error:', err.message) // Output includes stack trace: [string "..."]:1: Something went wrong! } // Syntax errors try { await lua.doString('invalid lua syntax here +-/*') } catch (err) { console.log('Syntax error:', err.message) } // JS errors caught in Lua with pcall lua.global.set('riskyOperation', () => { throw new Error('JS operation failed') }) const result = await lua.doString(` local success, err = pcall(riskyOperation) if not success then return "Handled: " .. tostring(err) end return "Success" `) console.log(result) // Output: Handled: Error: JS operation failed // Nested function error with stack trace try { await lua.doString(` local function a() error("deep error") end local function b() a() end local function c() b() end c() `) } catch (err) { console.log('Stack trace included:', err.message.includes('stack traceback')) // Output: true } } finally { lua.global.close() } ``` -------------------------------- ### Execute Lua Code Asynchronously with doString Source: https://context7.com/ceifa/wasmoon/llms.txt The doString method executes Lua code from a string asynchronously, returning the result. It supports async operations within Lua, such as Promise awaiting. Complex data structures like tables can be returned. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Simple expression const sum = await lua.doString('return 10 + 20') console.log(sum) // Output: 30 // Execute multiple statements and return value const result = await lua.doString(` local function factorial(n) if n <= 1 then return 1 end return n * factorial(n - 1) end return factorial(5) `) console.log(result) // Output: 120 // Return complex data structures const table = await lua.doString(` return { name = "John", age = 30, scores = {85, 92, 78} } `) console.log(table) // Output: { name: 'John', age: 30, scores: [85, 92, 78] } } finally { lua.global.close() } ``` -------------------------------- ### Create and Chain Promises in Lua Source: https://context7.com/ceifa/wasmoon/llms.txt When `injectObjects` is enabled, Lua code can create JavaScript Promises using `Promise.create()` and chain them with `:next()`. Supports `Promise.all()` for concurrent operations. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine({ injectObjects: true }) try { // Create promises in Lua const result = await lua.doString(` local promise = Promise.create(function(resolve, reject) resolve(42) end) return promise:await() `) console.log(result) // Output: 42 // Chain promises created in Lua const chained = await lua.doString(` local p1 = Promise.create(function(resolve) resolve(10) end) local p2 = p1:next(function(value) return Promise.create(function(resolve) resolve(value * 2) end) end) return p2:await() `) console.log(chained) // Output: 20 // Promise.all for concurrent operations lua.global.set('delay', (ms, val) => new Promise(r => setTimeout(() => r(val), ms))) const allResults = await lua.doString(` local promises = {} for i = 1, 5 do table.insert(promises, delay(10, i * 10)) end return Promise.all(promises):await() `) console.log(allResults) // Output: [10, 20, 30, 40, 50] } finally { lua.global.close() } ``` -------------------------------- ### Await JavaScript Promises in Lua Source: https://context7.com/ceifa/wasmoon/llms.txt Expose async JavaScript functions to Lua and await their results using the :await() method. Supports chaining with :next(), :catch(), and :finally(). ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Expose async function to Lua lua.global.set('sleep', (ms) => new Promise(resolve => setTimeout(resolve, ms))) lua.global.set('fetchData', async (id) => { await new Promise(r => setTimeout(r, 10)) return { id, name: `Item ${id}`, timestamp: Date.now() } }) // Await promises in Lua const result = await lua.doString( ` -- Wait for delay sleep(100):await() -- Fetch and process data local data = fetchData(42):await() return data.name `) console.log(result) // Output: Item 42 // Promise chaining with :next() const chained = await lua.doString( ` return fetchData(1):next(function(data) return data.id * 2 end):await() `) console.log(chained) // Output: 2 // Error handling with :catch() lua.global.set('failingFetch', () => Promise.reject(new Error('Network error'))) const errorResult = await lua.doString( ` return failingFetch():catch(function(err) return "Caught: " .. tostring(err) end):await() `) console.log(errorResult) // Output: Caught: Error: Network error } finally { lua.global.close() } ``` -------------------------------- ### Call Lua Global Functions from JavaScript Source: https://context7.com/ceifa/wasmoon/llms.txt Use `lua.global.call` to invoke Lua global functions directly from JavaScript. It accepts arguments and returns a `MultiReturn` array for all return values. Ensure to close the engine when done. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { await lua.doString(` function multiReturn(x, y) return x + y, x - y, x * y, x / y end function processData(data) local sum = 0 for _, v in ipairs(data) do sum = sum + v end return sum, #data, sum / #data end `) // Call function with multiple return values const [sum, diff, product, quotient] = lua.global.call('multiReturn', 10, 5) console.log(sum, diff, product, quotient) // Output: 15 5 50 2 // Call function with array argument const [total, count, average] = lua.global.call('processData', [10, 20, 30, 40]) console.log(total, count, average) // Output: 100 4 25 } finally { lua.global.close() } ``` -------------------------------- ### LuaGlobal.call - Call Global Functions Source: https://context7.com/ceifa/wasmoon/llms.txt The `call` method directly invokes a Lua global function with arguments and returns a `MultiReturn` array containing all return values. ```APIDOC ## LuaGlobal.call - Call Global Functions ### Description Directly invokes a Lua global function with provided arguments and returns all values returned by the Lua function. ### Method `lua.global.call(name, ...args)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the Lua global function to call. - **...args** (any) - Optional - Arguments to pass to the Lua function. ### Request Example ```javascript const [sum, diff] = lua.global.call('myMathFunction', 10, 5) const result = lua.global.call('processData', [1, 2, 3]) ``` ### Response #### Success Response (200) - **MultiReturn** (array) - An array containing all values returned by the Lua function. #### Response Example ```json { "MultiReturn": [ 15, 5, 50, 2 ] } ``` ``` -------------------------------- ### LuaGlobal.set - Set Global Variables Source: https://context7.com/ceifa/wasmoon/llms.txt The `set` method assigns JavaScript values to Lua global variables. It handles automatic type conversion including functions, objects, arrays, and complex nested structures. ```APIDOC ## LuaGlobal.set - Set Global Variables ### Description Assigns JavaScript values to Lua global variables with automatic type conversion. ### Method `lua.global.set(name, value)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the global variable to set. - **value** (any) - Required - The JavaScript value to assign. Supports primitives, arrays, objects, and functions. ### Request Example ```javascript lua.global.set('myNumber', 42) lua.global.set('myArray', [1, 2, 3]) lua.global.set('myFunction', (a, b) => a + b) ``` ### Response #### Success Response (200) This method does not return a value upon success. #### Response Example None ``` -------------------------------- ### Set Lua Global Variables with JavaScript Source: https://context7.com/ceifa/wasmoon/llms.txt Use `lua.global.set` to assign JavaScript values to Lua global variables. It supports automatic type conversion for primitives, arrays, objects, and functions. Ensure to close the engine when done. ```javascript const { LuaFactory } = require('wasmoon') const factory = new LuaFactory() const lua = await factory.createEngine() try { // Set primitive values lua.global.set('myNumber', 42) lua.global.set('myString', 'Hello from JS') lua.global.set('myBoolean', true) // Set arrays (become Lua tables with numeric indices) lua.global.set('myArray', [1, 2, 3, 4, 5]) // Set objects (become Lua tables with string keys) lua.global.set('config', { host: 'localhost', port: 8080, debug: true }) // Set JavaScript functions callable from Lua lua.global.set('sum', (x, y) => x + y) lua.global.set('greet', (name) => `Hello, ${name}!`) lua.global.set('stringify', (table) => JSON.stringify(table)) // Use the variables in Lua const result = await lua.doString(` local total = sum(10, 20) local message = greet("World") local json = stringify({ test = 1, items = myArray }) return { total = total, message = message, json = json, configPort = config.port } `) console.log(result) // Output: { total: 30, message: 'Hello, World!', json: '{"test":1,"items":[1,2,3,4,5]}', configPort: 8080 } } finally { lua.global.close() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.