Module:CodeToText: Difference between revisions
Appearance
Created page with "local p = {} function p.test(frame) local pageName = frame.args.page or 'Module:Sandbox' local titleObj = mw.title.new(pageName) if not titleObj then return "Failed to create mw.title object for '" .. pageName .. "'" end local content = titleObj:getContent() if not content then return "No content for '" .. pageName .. "'" end return content end return p" |
No edit summary |
||
| Line 1: | Line 1: | ||
local p = {} | local p = {} | ||
function p. | function p.showSnippet(frame) | ||
-- Get the page to load, defaulting to "Module:Sandbox" if none is specified | |||
local pageName = frame.args.page or 'Module:Sandbox' | local pageName = frame.args.page or 'Module:Sandbox' | ||
local fromLine = tonumber(frame.args.from) or 1 | |||
local toLine = tonumber(frame.args.to) or fromLine | |||
local titleObj = mw.title.new(pageName) | local titleObj = mw.title.new(pageName) | ||
if not titleObj then | if not titleObj then | ||
| Line 13: | Line 17: | ||
end | end | ||
return | -- Split by line | ||
local lines = {} | |||
for line in content:gmatch('[^\r\n]+') do | |||
table.insert(lines, line) | |||
end | |||
-- Extract only the requested line range | |||
local snippet = {} | |||
for i = fromLine, math.min(toLine, #lines) do | |||
table.insert(snippet, lines[i]) | |||
end | |||
return table.concat(snippet, '\n') | |||
end | end | ||
return p | return p | ||
Revision as of 18:00, 7 February 2025
Documentation for this module may be created at Module:CodeToText/doc
local p = {}
function p.showSnippet(frame)
-- Get the page to load, defaulting to "Module:Sandbox" if none is specified
local pageName = frame.args.page or 'Module:Sandbox'
local fromLine = tonumber(frame.args.from) or 1
local toLine = tonumber(frame.args.to) or fromLine
local titleObj = mw.title.new(pageName)
if not titleObj then
return "Failed to create mw.title object for '" .. pageName .. "'"
end
local content = titleObj:getContent()
if not content then
return "No content for '" .. pageName .. "'"
end
-- Split by line
local lines = {}
for line in content:gmatch('[^\r\n]+') do
table.insert(lines, line)
end
-- Extract only the requested line range
local snippet = {}
for i = fromLine, math.min(toLine, #lines) do
table.insert(snippet, lines[i])
end
return table.concat(snippet, '\n')
end
return p