Module:Utilities

From Deadlock Wiki
Jump to navigation Jump to search

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

local p = {};

	--round_to_significant_figures(12345.6789, 3)  -- Output: 12300
	--round_to_significant_figures(0.0012345, 2)   -- Output: 0.0012
	--round_to_significant_figures(-98765, 4)      -- Output: -98760
	function p.round_to_sig_fig(num, n)
	    if num == 0 then
	        return 0
	    end
	
	    -- Calculate the order of magnitude (log10 returns the logarithm base 10)
	    local order_of_magnitude = math.floor(math.log10(math.abs(num)))
	    
	    -- Scale the number to move the significant digits into the integer part
	    local scale = math.pow(10, n - 1 - order_of_magnitude)
	    
	    -- Round the scaled number and then scale it back
	    local rounded_num = math.floor(num * scale + 0.5) / scale
	    
	    return rounded_num
	end
	
	-- If the image exists exists, return it back enclosed in brackets, else return a blank string
	function p.get_image_file(image_file_name, px)
		if (px == nil) then px = 15 end --default
		
		image_file = mw.title.new(image_file_name)
		if image_file and image_file.exists then
		    image_file_name = "[[" .. image_file_name .. "|" .. px .. "px]]"
		else
		    image_file_name = ''
		end
		
		return image_file_name
	end
	
	--Call {{Lang}} on a given unlocalized string using key (not label)
	function p.call_lang(unlocalized)
		local template_title = mw.title.new("Template:Lang")
		local template_args = {}
		local template_call
	
		template_args["key"] = unlocalized
		
		local template_call = mw.getCurrentFrame():expandTemplate{ title = template_title, args = template_args }
		return template_call
	end

return p