17,230
edits
(add values() function to unwrap a particular node) |
(remove the Arg class) |
||
(6 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
local | local p = {} | ||
function | -- place the value in the right spot in the arg tree, determined by underscores in the key | ||
function p.expandInto( args, key, value ) | |||
local first, rest = string.match( key, '^(.-)_(.*)$' ) | |||
local myKey = first or key | |||
myKey = tonumber( myKey ) or myKey | |||
-- | if first then -- this is an internal node so insert children | ||
args[myKey] = type( args[myKey] ) == 'table' and args[myKey] -- already a table | |||
or args[myKey] and { __value = args[myKey] } -- move existing value into a new table | |||
or {} -- create new table | |||
p.expandInto( args[myKey], rest, value ) | |||
else -- this is a leaf so set value | |||
if type( args[myKey] ) == 'table' then args[myKey].__value = value | |||
else args[myKey] = value | |||
end | |||
end | |||
end | end | ||
-- | -- expand the arg tree for the given flattened args | ||
function p.expand( args ) | |||
function | local expandedArgs = {} | ||
local | for k, v in pairs( args ) do | ||
for k, v in pairs( | p.expandInto( expandedArgs, k, v ) | ||
end | end | ||
return | return expandedArgs | ||
end | end | ||
-- coerce the given node into a table, in case it is a standalone value | |||
function p.getTable( val ) | |||
return type( val ) == 'table' and val or { __value = val } | |||
end | |||
-- get the value at the given node, in case the node contains a table | |||
function p.getValue( val ) | |||
return type( val ) == 'table' and val.__value or val | |||
end | |||
function | -- expand the arg tree from the given frame and its parent | ||
function p.fromFrame( frame ) | |||
local | local parsedArgs = {} | ||
for k, v in pairs( frame.args ) do | |||
p.expandInto( parsedArgs, k, v ) | |||
end | |||
if | local parentFrame = frame:getParent() | ||
if parentFrame and parentFrame.args then | |||
for k, v in pairs (parentFrame.args ) do | |||
p.expandInto( parsedArgs, k, v ) | |||
end | |||
end | end | ||
return parsedArgs | |||
end | end | ||
function p. | -- parse and expand the arg tree for the given template on the given page | ||
local parsedArgs = | function p.fromPageContent( content, templateName ) | ||
for k, v | templateName = templateName or 'Properties' | ||
local parsedArgs = {} | |||
local templateContents = string.match( content, '{{%s*' .. templateName .. '%s*|%s*(.-)%s*}}' ) | |||
if templateContents then | |||
for prop in mw.text.gsplit( templateContents, '%s*|%s*' ) do | |||
local k, v = unpack( mw.text.split( prop, '%s*=%s*' ) ) | |||
p.expandInto( parsedArgs, k, v ) | |||
end | |||
end | end | ||