• Welcome to Touhou Wiki!
  • Registering is temporarily disabled. Check in our Discord server to request an account and for assistance of any kind.

Module:Common: Difference between revisions

From Touhou Wiki
Jump to navigation Jump to search
(restoring the mw.exists function...)
m (Undo revision 275604 by DennouNeko (talk))
Line 29: Line 29:
   t[#t+1] = string.trim(string.sub(str, pos))
   t[#t+1] = string.trim(string.sub(str, pos))
   return t
   return t
end
-- checks if a given page exists
function mw.exists(page)
  if not isset(page) then return false end
  return mw.getCurrentFrame():preprocess('{{#ifexist:' .. page .. '|1|0}}') == '1'
end
end



Revision as of 23:37, 1 October 2012

--[[
Library for all the functions that are going to be shared by other scripts.
To use all the functions NOT defined as local, add at the beginning of script the following:
require("Module:Common")
--]]

-- create global object "common" for most of exported functions
common = {}

-- checks if string is set and if it's non-empty
function isset(target)
  return target ~= nil and target ~= ""
end
 
-- removes preceding and trailing whitespaces from string
function string.trim(s)
  return s:gsub("^%s*(.-)%s*$", "%1")
end

-- adds a method to string that splits it into a table, using sep as a delimiter
function string.explode(str, sep) 
  local pos = 1
  local t = {}
  if not isset(sep) or not isset(str) then return t end
  for s, e in function() return string.find(str, sep, pos) end do
    t[#t+1] = string.trim(string.sub(str, pos, s-1))
    pos = e+1
  end
  t[#t+1] = string.trim(string.sub(str, pos))
  return t
end

--slices a table to return values within a certain range
--source: http://snippets.luacode.org/snippets/Table_Slice_116
function table.slice (values,i1,i2)
    local res = {}
    local n = #values
    -- default values for range
    i1 = i1 or 1
    i2 = i2 or n
    if i2 < 0 then
        i2 = n + i2 + 1
    elseif i2 > n then
        i2 = n
    end
    if i1 < 1 or i1 > n then
        return {}
    end
    local k = 1
    for i = i1,i2 do
        res[k] = values[i]
        k = k + 1
    end
    return res
end

-- checks if a given page exists
function mw.exists(page)
  if not isset(page) then return false end
  return mw.getCurrentFrame():preprocess('{{#ifexist:' .. page .. '|1|0}}') == '1'
end

-- [[Category:Lua Libraries|{{PAGENAME}}]]