lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> On 05 Oct 2016, at 15:31, tyrondis <tyrondis@icloud.com> wrote:
> 
> Hi *,
> 
> I have a 3rd party module that operates and maintains its state in the global environment.
> Is there anyway I can load this module into a custom context table, so that it uses that table as its _G? I want to be able to have multiple instances of that module, which is currently not possible because of its “Singleton” nature.
> 
> I could also refactor the 3rd part module but I want to have it untouched to make it easier to apply potential patches to it.
> 
> Thanks
> Tyr

The proper way to do singletons (imo) would be to store state in module level upvalues. These are fairly easy to work around by clearing the module from the `package.loaded` table.

Something like this (untested);

local function load_singleton(mod_name)
  local old = package.loaded[mod_name]
  local mod = require(mod_name)
  package.loaded[mod_name] = old
  return mod
end

Other than that, you’d probably need to explicitly set an environment or use the global environment with a proxy table and a lot of meta table magic, which seems more complex than adapting the module.

hth
Thijs