Module:Args: Difference between revisions
Jump to navigation
Jump to search
Want an adless experience? Log in or Create an account.
(this handles parsing flattened arg trees into lua tables. I don't like that you have to call :val() on everything though...) |
(add values() function to unwrap a particular node) |
||
Line 8: | Line 8: | ||
end | end | ||
-- get the Arg node's value, if it has one | |||
function Arg:val() | function Arg:val() | ||
return self.__value | return self.__value | ||
end | |||
-- get the values of the Arg node's direct children | |||
-- this is used to re-flatten/unwrap a particular piece of an Arg tree | |||
function Arg:values() | |||
local vals = {} | |||
for k, v in pairs( self ) do | |||
if type( v ) == 'table' and v.val then | |||
vals[k] = v:val() | |||
end | |||
end | |||
return vals | |||
end | end | ||
Line 30: | Line 44: | ||
function p.parse( args ) | function p.parse( args ) | ||
local parsedArgs = | local parsedArgs = Arg.new() | ||
for k, v in pairs( args ) do | for k, v in pairs( args ) do | ||
insertInto( parsedArgs, k, v ) | insertInto( parsedArgs, k, v ) |
Revision as of 22:44, June 23, 2020
Documentation for this module may be created at Module:Args/doc
local Arg = {} Arg.__index = Arg function Arg.new( value ) return setmetatable( { __value = value }, Arg ) end -- get the Arg node's value, if it has one function Arg:val() return self.__value end -- get the values of the Arg node's direct children -- this is used to re-flatten/unwrap a particular piece of an Arg tree function Arg:values() local vals = {} for k, v in pairs( self ) do if type( v ) == 'table' and v.val then vals[k] = v:val() end end return vals end local p = {} function insertInto( tbl, key, value ) local first, rest = string.match( key, '^(.-)_(.*)$' ) local myKey = first or key myKey = tonumber( myKey ) or myKey -- make sure the node exists if not tbl[myKey] then tbl[myKey] = Arg.new() end if first then -- this is an internal node so insert children insertInto( tbl[myKey], rest, value ) else -- this is a leaf so set value tbl[myKey].__value = tonumber( value ) or value end end function p.parse( args ) local parsedArgs = Arg.new() for k, v in pairs( args ) do insertInto( parsedArgs, k, v ) end return parsedArgs end return p