Module:OutputBuffer

From Funkinchan
Revision as of 07:52, 20 September 2023 by Jedevari (talk | contribs) (making module)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

This module provides an easy and efficient way to generate lengthy strings.

Usage

First, load the module.

<syntaxhighlight lang="lua"> local newBuffer = require('Module:OutputBuffer') </syntaxhighlight>

Then, create the buffer and the functions that act on it.

<syntaxhighlight lang="lua"> local getBuffer, print, printf = newBuffer() </syntaxhighlight>

getBuffer

<syntaxhighlight lang="lua"> local text = getBuffer(sep) </syntaxhighlight>

Returns the contents of the buffer, with an optional separator string sep.

print

<syntaxhighlight lang="lua"> print(s) </syntaxhighlight>

Adds the string s to the buffer.

printf

<syntaxhighlight lang="lua"> printf(s, ...) </syntaxhighlight>

Adds the string s to the buffer. The string is formatted with any subsequent arguments, following the rules used for string.format.

Example

<syntaxhighlight lang="lua"> local newBuffer = require('Module:OutputBuffer') local p = {}

function p.main() local getBuffer, print, printf = newBuffer() print('Welcome to the English Wikipedia.') printf('There are currently %d articles on this site.', mw.site.stats.articles) return getBuffer(' ') end

return p

-- Assuming this module's name is "TestModule", and that mw.site.stats.articles returns 4500000, -- Script error: No such module "TestModule". would output: -- "Welcome to the English Wikipedia. There are currently 4500000 articles on this site." </syntaxhighlight>


return function()
	local buffer = {}
	return function(sep)
		local b = buffer
		buffer = {}
		return table.concat(b, sep)
	end,
	function(text)
		buffer[#buffer + 1] = text
	end,
	function(...)
		buffer[#buffer + 1] = string.format(...)
	end
end