“模块:GetParentSec”的版本间的差异
跳到导航
跳到搜索
(建立内容为“local p = {} function p.getParentSection(frame) local title = frame:getTitle() local content = frame:callParserFunction{ name = '#tag', a…”的新页面) |
|||
| (未显示同一用户的5个中间版本) | |||
| 第2行: | 第2行: | ||
function p.getParentSection(frame) | function p.getParentSection(frame) | ||
| − | + | -- 获取调用位置的行号 | |
| − | local | + | local callLine = frame:getParent():getTitle() |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| + | -- 获取当前页面内容 | ||
local currentTitle = mw.title.getCurrentTitle() | local currentTitle = mw.title.getCurrentTitle() | ||
| − | local | + | local content = currentTitle:getContent() or "" |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | -- 解析 章节 结构 | |
| − | + | local parentStack = {} | |
| − | + | local lineNumber = 0 | |
| − | + | for line in content:gmatch("[^\r\n]+") do | |
| − | + | lineNumber = lineNumber + 1 | |
| − | + | ||
| − | + | -- 匹配 章节 标题 | |
| − | + | local level, title = line:match("^(=+)([^=]+)=+$") | |
| + | if level then | ||
| + | level = #level | ||
| + | title = mw.text.trim(title) | ||
| + | |||
| + | -- 维护父章节栈 | ||
| + | while #parentStack > 0 and parentStack[#parentStack].level >= level do | ||
| + | table.remove(parentStack) | ||
| + | end | ||
| + | table.insert(parentStack, {level = level, title = title, line = lineNumber}) | ||
| + | |||
| + | -- 检查是否是当前调用行 | ||
| + | if tostring(lineNumber) == callLine then | ||
| + | if #parentStack > 1 then -- 有父章节 | ||
| + | return parentStack[#parentStack-1].title | ||
| + | else | ||
| + | return "" -- 没有父章节 | ||
| + | end | ||
| + | end | ||
end | end | ||
end | end | ||
| − | return | + | return "" |
end | end | ||
return p | return p | ||
2025年4月30日 (三) 21:46的最新版本
此模块的文档可以在模块:GetParentSec/doc创建
local p = {}
function p.getParentSection(frame)
-- 获取调用位置的行号
local callLine = frame:getParent():getTitle()
-- 获取当前页面内容
local currentTitle = mw.title.getCurrentTitle()
local content = currentTitle:getContent() or ""
-- 解析章节结构
local parentStack = {}
local lineNumber = 0
for line in content:gmatch("[^\r\n]+") do
lineNumber = lineNumber + 1
-- 匹配章节标题
local level, title = line:match("^(=+)([^=]+)=+$")
if level then
level = #level
title = mw.text.trim(title)
-- 维护父章节栈
while #parentStack > 0 and parentStack[#parentStack].level >= level do
table.remove(parentStack)
end
table.insert(parentStack, {level = level, title = title, line = lineNumber})
-- 检查是否是当前调用行
if tostring(lineNumber) == callLine then
if #parentStack > 1 then -- 有父章节
return parentStack[#parentStack-1].title
else
return "" -- 没有父章节
end
end
end
end
return ""
end
return p