User:Ash/Lua Imports

From SRB2 Wiki
Jump to navigation Jump to search

How to implement Lua "imports"

This page is a personal reference of how to organize Lua modules like JS modules, with explicit imports and exports that can be used per-file. One of the major advantages of this is "lazy loading" of any potential rawset items, leaving the global table free of unused or under-utilized items.

JS Equivalent

   // Assuming we have this object:
   let myLibrary = {}
   myLibrary.myFunc = () => {}
   
   // export syntax
   export default myLibrary;

   // import syntax
   import { myFunc } from "myLibrary.js";

Lua "Import/Export"

   -- Assuming we have this object:
   local myLibrary = {}
   myLibrary.myFunc = do nothing end

   -- export syntax
   rawset(_G, "myLibrary", myLibrary)

   -- import syntax
   local myFunc = myLibrary.myFunc

Explicit Syntax Proposal Library

   -- Assuming we have this object:
   local myLibrary = {}
   myLibrary.myFunc = do nothing end

   -- export syntax (accepts a table or function)
   export(myLibrary)

   -- import syntax for one item
   local myFunc = import({ "myFunc" }, "myLibrary.lua")
   -- OR
   local myFunc = import("myLibrary.lua").myFunc -- i like this one more

   -- import for multiple (prolly a bad idea)
   local myFuncA, myFuncB, myFuncC = import({ 
      "myFuncA", 
      "myFuncB", 
      "myFuncC"
   }, "myLibrary.lua")

Global Imports

   -- equivalent of rawsetting multiple modules
   globalImport(
     "myLibrary1.lua",
     "myLibrary2.lua",
     -- etc
   );

   myLibrary.myFunc()