Module:Others
来自滚动的天空Wiki
local p = {}
function p.tindex(t, paras)
-- 本函数用于求取层叠表的一个域。
-- 例如index(a,'b','c','d')
-- 就相当于获得a.b.c.d,
-- 并且,如果a、a.b、a.b.c中的任何一个如果不是表,
-- 则直接返回nil,避免出错。
local result = t
for i,k in ipairs(paras) do
if type(result)=='table' then
result = result[k]
else
return nil
end
end
return result
end
function p.index(t,...) return p.tindex(t,{...}) end
function p.tnewindex(t, value, paras)
-- 类似于index。
-- 例如,newindex(t,3,'a','b','c')就相当于设置t.a.b.c=3。如果原来的t.a.b.c是表则修改无效。
-- 并且如果t.a、t.a.b中的任何一个不是表,则将其修改为表。
-- 注意:如果是其他数据类型,也会被强制改成表。
-- 如果添加的值是一个表,会返回这个表,否则返回t。
if #paras <1 then return end
local current = t
local num = #paras
for i,k in ipairs(paras) do
if i==num then
if type(current[k])~='table' then
current[k] = value
end
return type(value)=='table' and current[k] or t
else
if type(current[k])~='table' then
current[k] = {}
end
current = current[k]
end
end
end
function p.newindex(t,value,...) return p.tnewindex(t,value,{...}) end
function p.newTable(t)
-- 获取一个可面向对象操作的表,或使一个表面向对象。
t = t or {}
return setmetatable(
t,
{
__index = {
newindex = p.newindex,
tnewindex = p.tnewindex,
index = p.index,
tindex = p.tindex,
sort = table.sort,
insert = table.insert,
concat = table.concat
}
}
)
end
function p.addNewLine(str) --这里的addNewline不同于导航框的
if type(str) ~= 'string' then return str end
if not str:find('^\n') then
str = '\n' .. str
end
if not str:find('\n$') then
str = str .. '\n'
end
return str
end
p.addNewline,p.addnewline = p.addNewLine,p.addNewLine
function p.visit(t, notnum)
local keys = {}
for k, v in pairs(t) do
if type(k) == "number" then
table.insert(keys,k)
elseif type(notnum) == 'function' then
notnum(k,v)
end
end
table.sort(keys)
local i = 0
return function()
i = i + 1
return keys[i], keys[i] and t[keys[i]]
end
end
--[[-----------下面部分对标签对象类的一些方法进行改进---------------
function p.notspace(str)
--检测字符串是否只有空格或空字符串
if type(str) ~= "string" then return nil end
if str:match("^ *$") then
return nil
end
return str
end
local notspace = p.notspace
function p.style(style)
-- 对于末尾没有分号的样式增加分号
if not p.notspace(style) then
return nil
end
if not style:find(";$") then
style = style ..";"
end
return style
end
local c = getmetatable(mw.html.create('div')).__index
function p.newstyle()
c.ocssText = c.cssText
function c:cssText(...)
for i, text in pairs({...}) do
self:ocssText(p.style(text))
end
return self
end
end
function p.newclass()
c.oaddClass = c.addClass
function c:addClass(...)
for i, class in pairs {...} do
self:oaddClass(p.notspace(class))
end
return self
end
end
function p.newattr()
c.oattr = c.attr
function c:attr(attr,value)
if not p.notspace(value) or not p.notspace(attr) then
return self
end
if attr == "style" then
return self:cssText(value)
elseif attr == 'class' then
return self:addClass(value)
else
return self:oattr(attr,value)
end
end
end
function p.newtagobj()
p.newstyle()
p.newclass()
p.newattr()
end
]]
return p