-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimport.lua
More file actions
49 lines (44 loc) · 1.45 KB
/
import.lua
File metadata and controls
49 lines (44 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-- Copied/modified from LTN 11: http://www.lua.org/notes/ltn011.html
local imported = {}
local function package_stub(name)
local stub = {}
local stub_meta = {
__index = function(_, index)
error(string.format("member `%s' is accessed before package `%s' is fully imported", index, name))
end,
__newindex = function(_, index, _)
error(string.format("member `%s' is assigned a value before package `%s' is fully imported", index, name))
end,
}
setmetatable(stub, stub_meta)
return stub
end
local function locate(name)
local path = LUA_PATH
if type(path) ~= "string" then
path = os.getenv "LUA_PATH" or "./?.lua"
end
for path in string.gfind(path, "[^;]+") do
path = string.gsub(path, "?", name)
local chunk = loadfile(path)
if chunk then return chunk, path end
end
return nil, path
end
function import(name)
local package = imported[name]
if package then return package end
local chunk, path = locate(name)
if not chunk then
error(string.format("could not locate package `%s' in `%s'", name, path))
end
package = package_stub(name)
imported[name] = package
setfenv(chunk, getfenv(2))
chunk = chunk()
setmetatable(package, nil)
if type(chunk) == "function" then
chunk(package, name, path)
end
return package
end