• 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
(library of common functions)
 
m (string.explode + dropping "frame" param from exists)
Line 1: Line 1:
--[[
--[[
Library for shared functions and/or constants.
Library for all the functions that are going to be shared by other scripts.
To use all the functions NOT defined as local, add the following:
To use all the functions NOT defined as local, add at the beginning of script the following:
require("Module:Common")
require("Module:Common")
]]
]]
-- create global object common (for non-global, exported functions)
common = {}


-- checks if string is set and if it's non-empty
-- checks if string is set and if it's non-empty
Line 13: Line 16:
function trim(s)
function trim(s)
   return s:gsub("^%s*(.-)%s*$", "%1")
   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] = trim(string.sub(str, pos, s-1))
    pos = e+1
  end
  t[#t+1] = trim(string.sub(str, pos))
  return t
end
end


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

Revision as of 23:15, 27 September 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 non-global, 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 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] = trim(string.sub(str, pos, s-1))
    pos = e+1
  end
  t[#t+1] = trim(string.sub(str, pos))
  return t
end

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