Module:Module introspection: Difference between revisions
mNo edit summary |
detect whether a module returns a single function |
||
| Line 153: | Line 153: | ||
module_name = module_name or "p" | module_name = module_name or "p" | ||
-- Find all functions defined in the module | |||
for line in code:gmatch("([^\n]*)\n?") do | for line in code:gmatch("([^\n]*)\n?") do | ||
line_num = line_num + 1 | line_num = line_num + 1 | ||
-- Match functions defined as: function p.name(param1, param2) | -- CASE 1: Match functions defined as: | ||
-- function p.name(param1, param2) | |||
local name, params_str = line:match("function%s+" .. module_name .. "%.([%w_]+)%s*%(([^)]*)%)") | local name, params_str = line:match("function%s+" .. module_name .. "%.([%w_]+)%s*%(([^)]*)%)") | ||
if name then | if name then | ||
| Line 166: | Line 168: | ||
end | end | ||
-- Match functions defined as: p.name = function(param1, param2) | -- CASE 2: Match functions defined as: | ||
-- p.name = function(param1, param2) | |||
name, params_str = line:match(module_name .. "%.([%w_]+)%s*=%s*function%s*%(([^)]*)%)") | name, params_str = line:match(module_name .. "%.([%w_]+)%s*=%s*function%s*%(([^)]*)%)") | ||
if name then | if name then | ||
| Line 174: | Line 177: | ||
end | end | ||
table.insert(funcs, { name = name, line = line_num, params = params }) | table.insert(funcs, { name = name, line = line_num, params = params }) | ||
end | |||
end | |||
-- CASE 3: If no functions were found, check the code again to see whether | |||
-- it returns a single function. | |||
if #funcs == 0 then | |||
local return_line_num = 0 | |||
for line in code:gmatch("([^\n]*)\n?") do | |||
return_line_num = return_line_num + 1 | |||
local params_str = line:match("return%s+function%s*%(([^)]*)%)") | |||
if params_str then | |||
local params = {} | |||
for param in params_str:gmatch("([%w_]+)") do | |||
table.insert(params, param) | |||
end | |||
table.insert(funcs, { name = "return", line = return_line_num, params = params }) | |||
break | |||
end | |||
end | end | ||
end | end | ||