lua-users home
lua-l archive

Re: Convenience require (resend)

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


It was thus said that the Great Soni L. once stated:
> (Hopefully it sends correctly this time)
> 
> We currently have raw requires, which means we do things like
> 
> local a = require"io.github.soniex2.a"
> local b = require"io.github.soniex2.b"
> local c = require"io.github.soniex2.b.c"
> -- use a, b and c normally
> 
> Instead of that, is there a module or something that lets me do 
> something like
> 
> local soniex2 = reqpath"io.github.soniex2"
> local a = soniex2("a") -- alternatively, `soniex2.a()`
> local b = soniex2("b") -- alternatively, `soniex2.b()`
> local c = soniex2("b.c") -- alternatively, `soniex2.b.c()`, with the 
> call at the
> -- end for disambiguating between module and 
> path, and
> -- setting an __index is not an option as the 
> module
> -- could already have its own __index (or not be a
> -- table at all; some modules return functions!).
> -- use a, b and c normally
> 
> I think it looks nicer.
 On second thought, it should be easy enough to implement (untested):
	function reqpath(path)
	 return function(module)
	 return require(path .. "." .. module)
	 end
	end
or
	local mt_reqpath = {}
	function my_reqpath:__index(key)
	 table.insert(self.path,key)
	 return self
	end
	function my_reqpath:__call(...)
	 table.insert(self.path,1,self.base)
	 local path = table.concat(self.path,".")
	 self.path = {}
	 return require(path)
	end
	function reqpath(path)
	 return setmetatable(
		{ base = path , path = {} },
		my_reqpath
	 )
	end
 -spc (Wait a second ... why am I doing your homework again? 8-P

AltStyle によって変換されたページ (->オリジナル) /