“模块:GetParentSec”的版本间的差异
跳到导航
跳到搜索
(与大鲸鱼斗智斗勇) |
|||
| 第2行: | 第2行: | ||
function p.getParentSection(frame) | function p.getParentSection(frame) | ||
| − | -- 获取当前页面 | + | -- 获取当前页面 原始内容 |
local currentTitle = mw.title.getCurrentTitle() | local currentTitle = mw.title.getCurrentTitle() | ||
| + | local content = currentTitle:getContent() or "" | ||
| − | -- | + | -- 解析章节结构 |
| − | local | + | local stack = {} -- 用于跟踪章节层级 |
| − | + | local found = false | |
| − | + | for line in content:gmatch("[^\r\n]+") do | |
| − | + | local level, name = line:match("^(=+)([^=]+)=+$") | |
| − | + | if level then | |
| − | |||
| − | |||
level = #level | level = #level | ||
| − | + | name = mw.text.trim(name) | |
| − | + | ||
| − | + | -- 检查是否包含我们的模板 | |
| − | + | if name:find("{{ParentSection}}") then | |
| − | + | -- 返回栈顶的父 章节 (如果有) | |
| − | + | found = true | |
| − | + | break | |
| − | + | end | |
| − | + | ||
| − | + | -- 维护 章节 栈 | |
| − | + | while #stack > 0 and stack[#stack].level >= level do | |
| − | + | table.remove(stack) | |
| + | end | ||
| + | table.insert(stack, {level = level, name = name}) | ||
end | end | ||
end | end | ||
| − | + | if found and #stack > 0 then | |
| − | if | + | return stack[#stack].name |
| − | return " | + | else |
| + | return "" -- 返回空字符串避免破坏标题格式 | ||
end | end | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
end | end | ||
return p | return p | ||
2025年4月30日 (三) 21:34的版本
此模块的文档可以在模块:GetParentSec/doc创建
local p = {}
function p.getParentSection(frame)
-- 获取当前页面原始内容
local currentTitle = mw.title.getCurrentTitle()
local content = currentTitle:getContent() or ""
-- 解析章节结构
local stack = {} -- 用于跟踪章节层级
local found = false
for line in content:gmatch("[^\r\n]+") do
local level, name = line:match("^(=+)([^=]+)=+$")
if level then
level = #level
name = mw.text.trim(name)
-- 检查是否包含我们的模板
if name:find("{{ParentSection}}") then
-- 返回栈顶的父章节(如果有)
found = true
break
end
-- 维护章节栈
while #stack > 0 and stack[#stack].level >= level do
table.remove(stack)
end
table.insert(stack, {level = level, name = name})
end
end
if found and #stack > 0 then
return stack[#stack].name
else
return "" -- 返回空字符串避免破坏标题格式
end
end
return p