[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: getting keywords in lua5.2
- From: "Victor Bombi" <sonoro@...>
- Date: Mon, 8 Apr 2013 13:08:54 +0200
Hello,
On lua51 I managed to get all the keywords (global definitions of functions
and tables and the functions in this tables) from some lua files which also
used require on other lua files.
All this keywords were put in a env table which was afterwards scaned for
getting the keywords
-- the helper functions were
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 loadinEnv(file,env)
if not env then
env = setmetatable({}, {__index = _G})
env.require = newrequire
env.package = setmetatable({}, {__index = _G.package})
env.package.loaded = {}
end
local f = loadfilefrompath(file)
setfenv(f, env)
f()
return env
--------- I use it to get keywords like this
local env = loadinEnv"sc.synthdefsc"
loadinEnv("sc.playerssc",env)
loadinEnv("sc.stream",env)
local keyword_table = {}
for index, value in pairs(env) do
if type(value)=="function" then
table.insert(keyword_table, index.." ")
elseif type(value)=="table" then
table.insert(keyword_table, index.." ")
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)
--In lua 52 I defined setfenv
setfenv = setfenv or function(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return t end, 1) -- use unique
upvalue, set it to f
end
end
--and used
env = _ENV
instead of env = getfenv(2)
It does not work, environment is missing the definitions in the required
files.
I think that it was too complicated in lua51 version. I wonder if there is a
better way in lua 52
Thank you for reading if you arrived here.
Best
victor