Guest User

Untitled

a guest
Oct 21st, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. local imported = {}
  2. local path = nil
  3.  
  4. local function package_stub(name)
  5. local stub = {}
  6. local stub_meta = {
  7. __index = function(_, index)
  8. error(string.format("member `%s' is accessed before package `%s' is fully imported", index, name))
  9. end,
  10. __newindex = function(_, index, _)
  11. error(string.format("member `%s' is assigned a value before package `%s' is fully imported", index, name))
  12. end,
  13. }
  14. setmetatable(stub, stub_meta)
  15. return stub
  16. end
  17.  
  18. local function locate(name)
  19. local path = path
  20. if type(path) ~= "string" then
  21. path = os.getenv "LUA_PATH" or "./?.lua"
  22. end
  23. for path in string.gfind(path, "[^;]+") do
  24. path = string.gsub(path, "?", name)
  25. print(path)
  26. local chunk = loadfile(path)
  27. if chunk then return chunk, path end
  28. end
  29. return nil, path
  30. end
  31.  
  32. function setpath()
  33. path = string.sub(debug.getinfo(2).source, 2, lastindexof(debug.getinfo(2).source, "/"))
  34. end
  35.  
  36. function require(name)
  37. local package = imported[name]
  38. if package then return package end
  39. local chunk, path = locate(name)
  40. if not chunk then
  41. print(name .. path)
  42. error(string.format("could not locate package `%s' in `%s'", name, path))
  43. end
  44. package = package_stub(name)
  45. imported[name] = package
  46. chunk = chunk()
  47. setmetatable(package, nil)
  48. if type(chunk) == "function" then
  49. chunk(package, name, path)
  50. end
  51. return package
  52. end
Add Comment
Please, Sign In to add comment