-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Let's take this file structure as example
Root
├── main.lua
├── stuff.lua
└── libs
├── lua_import.lua
└── other.lua
Let's say I want to require stuff.lua from main.lua. I could just do
local lua_import = require("libs.lua_import")
local stuff = lua_import.import("./stuff")That works, but... Let's say now that stuff.lua needs other.lua. What I thought to be logical was to do
local lua_import = require("libs.lua_import")
local stuff =lua_import.useImport(function ()
return import("./libs.other")
end)But that doesn't work. Inside import, callerPath gets resolved to "libs.lua_import" and that makes sense since the function is being called from useImport function inside the lib, not from our file.
I open this as an issue becasue I'm not sure if this is intended behaviour or not, for my personal taste this is not what I expected from the function and made the following changes:
local import_inner = function(path, callerPath)
--- Previous code
end
local import = function (path)
return import_inner(path, debug.getinfo(2, "S").source:sub(2))
end
local useImport = function(fn)
local callerPath = debug.getinfo(2, "S").source:sub(2)
_G["import"] = function(path)
return import_inner(path, callerPath)
end
local results = { fn() }
_G["import"] = nil
return unpack(results)
endI renamed the import functio to import_inner, now that receives the callerPath, the import function just calls that. I made it that way to not expose the import function with that additional parameter that users must not touch. Then, I take advantage of this in useImport to define "import" as a function that captures the callerPath I cache at the beggining of the function.
Again, I'm not sure if this makes sense, but well, leaving this here just in case it's useful to other people using the lib.
Nonetheless to say that this is a pretty simplified example, in my real use case, I import a file that import other files that also need to import other files from parent folders and I wanted to give all of them the "import" function in global scope for ease of use