“模块:GetParentSec”的版本间的差异
跳到导航
跳到搜索
(与大鲸鱼斗智斗勇) |
|||
| (未显示同一用户的3个中间版本) | |||
| 第2行: | 第2行: | ||
function p.getParentSection(frame) | function p.getParentSection(frame) | ||
| − | -- 获取当前页面 | + | -- 获取调用位置的行号 |
| + | local callLine = frame:getParent():getTitle() | ||
| + | |||
| + | -- 获取当前页面内容 | ||
local currentTitle = mw.title.getCurrentTitle() | local currentTitle = mw.title.getCurrentTitle() | ||
local content = currentTitle:getContent() or "" | local content = currentTitle:getContent() or "" | ||
-- 解析章节结构 | -- 解析章节结构 | ||
| − | local | + | local parentStack = {} |
| − | local | + | local lineNumber = 0 |
for line in content:gmatch("[^\r\n]+") do | for line in content:gmatch("[^\r\n]+") do | ||
| − | local level, | + | lineNumber = lineNumber + 1 |
| + | |||
| + | -- 匹配章节标题 | ||
| + | local level, title = line:match("^(=+)([^=]+)=+$") | ||
if level then | if level then | ||
level = #level | level = #level | ||
| − | + | title = mw.text.trim(title) | |
| − | -- | + | -- 维护 父章节 栈 |
| − | + | while #parentStack > 0 and parentStack[#parentStack].level >= level do | |
| − | + | table.remove(parentStack) | |
| − | |||
| − | |||
end | 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 | end | ||
| − | + | 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