How to check which file is importing this file in Lua?

Viewed 80

I've been constructing a packet analising system for wireshark with Lua script. Now I'm managing three following lua files where VPS.lua and DSS.lua are importing some functions from DSS_function.lua by require module.

VPS.lua     DSS.lua     DSS_function.lua

Question is how to know which file, VPS.lua or DSS.lua, DSS_function.lua are imported from. DSS_function.lua has to know this information, because each time it declares the protocol depending on the file which is importing itself.

Thank you.

2 Answers

If you use require("name_of_the_Lua_file") then the return of the required Lua file goes to...

package.loaded.name_of_the_Lua_file

The next require("name_of_the_Lua_file") looks for this name in package.loaded.name_of_the_Lua_file and if there it loads it from there.
Only if the Lua file dont return anything then package.loaded.name_of_the_Lua_file returns a: true
...and not what you expected.
Example what i mean...

package.loaded.example={test = function() print "Hi - I am a test" end}
require('example').test()
-- Output: Hi - I am a test

So, check what is allready required with a look in package.loaded.
It could look like...

if package.loaded.example ~= nil then
 print("Already loaded")
 return true
else
 print("Not exists - Load it first")
 return false
end
-- Output: Already loaded
--         true

You can use something along these lines to figure out where a library is required from:

local name = debug.getinfo(3).short_src

if name:find "foo.lua" then
  print("Required from Foo")
elseif name:find "bar.lua" then
  print("Required from Bar")
end

But the problem is that it will only work the first time because Lua caches modules after the first time they are required.

Setting that aside, what you are trying to build is an abomination and whatever reason you think you have for wanting this is just a sign of a deeper problem with your code structure.

Related