Module:Foreach

From talkhaus wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Foreach/doc

-- Modified from https://www.mediawiki.org/wiki/Module:Foreach
-- adds a third argument that toggles whether the for loop parses the table from a single argument string

local p = {}

local function parseArgFour(arg)
    local tbl = {}
    
    for match in (arg..", "):gmatch("(.-)"..", ") do
        table.insert(tbl, match);
    end

    return tbl
end

function p.w(frame)
-- called from Template:Fe

    local pframe = frame:getParent() 
    local tplname = pframe.args[1]   
    local delim = pframe.args[2]
    local listType = pframe.args[3]
 
    local list = pframe.args
    local listStartN = 3
    if  listType == "arg"  then
        list = parseArgFour(pframe.args[4])
        listStartN = 0
    end

    r = ''
    for n,v in ipairs(list) do
       if n > listStartN then
           r = r .. delim
       end
       if n > listStartN then 
           r = r .. frame:expandTemplate{title = tplname, args = {i=n-listStartN, [1]=v}}
       end
    end
    return r
end

function p.m(t,frame)
-- to be called from a module
-- at the top: p={foreach = require "Module:foreach"}
-- example: p.foreach.m({tplname,', ','',item1,item3,item3},frame)

    r = ''
    tplname=t[1]
    delim=t[2]
    listType=t[3]

    list = t
    listStartN = 3
    if  listType == "arg"  then
        list = parseArgFour(t[4])
        listStartN = 0
    end

    for n,v in ipairs(list) do
       if n > listStartN  then
           r = r .. delim
       end
       if n > listStartN then
           r = r .. frame:expandTemplate{title = tplname, args = {i=n-listStartN, [1]=v}}
       end
    end
    return r
end

 
return p