Module:Cooking Random Weights

From Caves of Qud Wiki
Jump to navigation Jump to search

local p = {}
local process_args = require('Module:ProcessArgs')
local text_util = require('Module:Text Utility')

function p.splitEncounterTableArgs(row)
    local TABLE_ARGS = { 'cookeffect', 'weight' }
    return text_util.splitArgs(row, TABLE_ARGS)
end


function p.start(frame)
    args = process_args.merge(true)
    local pick = 'once'

    local result = {}
    local totalWeight = 0
    for i, row in ipairs(args) do
        local newrow = p.splitEncounterTableArgs(row)
        result[i] = newrow
        totalWeight = totalWeight + tonumber(newrow['weight'])
    end
 
--format table. 
    local finalTable = {}
    local str = ''
    for i, row in ipairs(result) do
        finalTable[i]={}
        finalTable[i]['cookeffect'] = row['cookeffect']
        finalTable[i]['weight'] = row['weight']
   -- calculate final chance
        if pick == 'once' then
            finalTable[i]['chance'] = string.format("%.2f%%",row['weight']*100/totalWeight)
        elseif pick == 'each' then
            finalTable[i]['chance'] = string.format("%.2f%%",row['weight'])
        else
            error('"roll" parameter takes only "once" or "each"!')
        end
    end
    return (p.formatTable(finalTable))
end

function p.formatTable(final)
    local tblheader = '<tr><th>Cooking Effect</th><th>Weight</th><th>Chance</th></tr>'
    local tr = ''
    for _, v in ipairs(final) do
        tr = tr ..  ' <tr><td>' ..v['cookeffect'] ..  '</td><td>' .. v['weight'] .. '</td><td>' .. v['chance'] .. '</td></tr>'
    end
    return '<table class="wikitable sortable">' .. tblheader  .. tr .. '</table>'
end

return p