Advertisement
Snusmumriken

moonscript require on the fly loader

Jul 23rd, 2023 (edited)
1,066
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.23 KB | None | 1 0
  1. local moonc = "D:\\drive\\bin\\moon\\moonc.exe"
  2. local function loader(modulename)
  3.     local errmsg = ""
  4.     local config = package.config
  5.     local separator   = config:sub(3, 3)
  6.     local placeholder = config:sub(5, 5)
  7.    
  8.     for path in (package.path .. separator):gmatch("(.-)" .. separator) do
  9.         local path, gsubs = path, 0
  10.         path, gsubs = path:gsub("%" .. placeholder, modulename)
  11.         path, gsubs = path:gsub("%.lua$", ".moon")
  12.         if gsubs > 0 then
  13.             local touchfile, err = io.open(path, "rb")
  14.             if touchfile then
  15.                 touchfile:close()
  16.                 local compfile, err = io.popen(moonc .. " -p " .. path .. " 2>&1", "rb")
  17.                 if not compfile then
  18.                     error("Error compiling code from " .. path .. ": " .. tostring(err), 2)
  19.                 end
  20.                 local code = compfile:read("*all"); compfile:close()
  21.                 local finderr = code:find(path .. "\tFailed to parse:", 0, true)
  22.                 if finderr == 1 then
  23.                     error(tostring(code), 2)
  24.                 end
  25.                 local func, err = loadstring(code, modulename)
  26.                 if not func then
  27.                     error("Error loading module from " .. path .. ": " .. tostring(err), 2)
  28.                 end
  29.                 return func
  30.             else
  31.                 errmsg = errmsg .. "\n\tno file '" .. path .. "' (moonloader)"
  32.             end
  33.         end
  34.     end
  35.     return errmsg
  36. end
  37.  
  38. table.insert(package.loaders, 2, loader)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement