[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: require in another enviroment
- From: "Victor Bombi" <sonoro@...>
- Date: Thu, 27 Dec 2012 09:47:07 +0100
Yes, require() is not going to work as you want it to. But it would be
possible to rewrite it so that it sets the environment of the blabla
module to be the environment of the caller.  It would (1) use
getfenv(2) to find out caller env (2) find the module using
package.path & load the file (3) set the module chunk env and execute
it and (4) keep track of its loaded status.
This is working for me. 
I am not sure if keeping track of loaded modules is important as env
will be useless outside of findKeywords
------------------------------------------------
function stsplit(s,c)
local t = {}
local pat = ""..c.."?([^"..c.."]+)"..c.."?"
for w in string.gmatch(s, pat) do  -- ";?[^;]+;?"
 t[#t + 1] = w
end
return t
end
function newrequire(cad)
local env = getfenv(2)
if package.loaded[cad] then return package.loaded[cad] end
local chunk = loadfilefrompath(cad)
setfenv(chunk, env)
package.loaded[cad] = chunk()
return package.loaded[cad]
end
function loadfilefrompath(cad)
-- win32,linux,mac?
cad = string.gsub(cad, "%.","/")
------------------------------------
local paths = stsplit(package.path,";")
for i, path in ipairs(paths) do
 local file=string.gsub(path,"?",cad)
 local chunk,errorst = loadfile(file)
 if chunk then
  return chunk
 end
end
error("could not loadfilefrompath "..cad) 
end
function findKeywords(file)
local keyword_table = {}
local env = setmetatable({}, {__index = _G}) 
env.require = newrequire
env.package = setmetatable({}, {__index = _G.package})
env.package.loaded = {}
local f = loadfilefrompath(file)
setfenv(f, env)
f()
for index, value in pairs(env) do
 if type(value)=="function" then
  table.insert(keyword_table, index.." ")
 elseif type(value)=="table" then
  for i2,v2 in pairs(value) do
   if type(v2)=="function" then
    table.insert(keyword_table, index.."."..i2.." ")
   end
  end
 end
end
table.sort(keyword_table)
sckeywords = table.concat(keyword_table)
print(sckeywords)
end
findKeywords"sc.synthdefsc"