Module:Util

From Path of Exile Wiki
Revision as of 14:44, 9 July 2015 by >OmegaK2 (renamed the functions and made them take abitary values)
Jump to navigation Jump to search
Module documentation[view] [edit] [history] [purge]


This is a meta module.

This module is meant to be used only by other modules. It should not be invoked in wikitext.

Lua logo

This module depends on the following other modules:

Overview

Provides utility functions for programming modules.

Structure

Group Description
util.cast utilities for casting values (i.e. from arguments)
util.html shorthand functions for creating some html tags
util.misc miscellaneous functions

Usage

This module should be loaded with require().

ru:Модуль:Util

-- Utility stuff

local util = {}
util.cast = {}
util.cast.bool_false = {'false', '0', 'disabled', 'off', 'no', ''}

function util.cast.boolean(value)
    -- Takes an abitary value and casts it to a bool value
    -- 
    -- for strings false will be according to util.cast.bool_false
    local t = type(value)
    if t == 'nil' then
        return false
    elseif t == 'boolean' then
        return value
    elseif t == 'number' then
        if t == 0 then return false end
        return true
    elseif t == 'string' then
        local tmp = string.lower(value)
        for _, v in ipairs(util.cast.bool_false) do
            if v == tmp then
                return false
            end
        end
        return true
    else
        error('"' .. value .. ' is of uncaptured type "' .. t .. '"')
    end
    
end

function util.cast.number(value, default)
    -- Takes an abitary value and attempts to cast it to int
    --
    -- For strings: if default is nil and the conversion fails, an error will be returned
    local t = type(value)
    
    if t == 'nil' then
        return 0
    elseif t == 'boolean' then
        if value then
            return 1
        else
            return 0
        end
    elseif t == 'number' then
        return value
    elseif t == 'string' then
        val = tonumber(value)
        if val == nil then
            if default ~= nil then
                return default
            else
                error('"' .. value .. '" is not an integer')
            end
        else
            return val
        end
    else
        error('"' .. value .. ' is of uncaptured type "' .. t .. '"')
    end
end

return util