Module:Molar mass calculator

From Wikipedia

Documentation for this module may be created at Module:Molar mass calculator/doc

local p = {};

function p.calc(frame)
	local atomicWeights = mw.loadData(  'Module:Standard atomic weight'  )
	local total = 0
	
	for element, quantity in pairs( frame:getParent().args ) do
		if quantity ~= "" then
			local atomicWeight = atomicWeights[element] or error( 'Element "' .. element .. '" is not known. Please add it to [[Module:Standard atomic weight]] if it\'s not a typo.' )
			quantity = tonumber( quantity ) or error( 'Quantity for ' .. element .. ' is not a number.' )
			total = total + atomicWeight * quantity
		end
	end
	
	function round(num, idp) --- taken from lua-users.org/wiki/SimpleRound
		local mult = 10^(idp or 0)
		return math.floor(num * mult + 0.5) / mult
	end
	
	return round(total,3)   --- 3 can be replaced by whatever number of decimal places you wish to round to. 
end
 
return p