Module:StringBuilder

Revision as of 15:35, 1 April 2024 by Ricewind (talk | contribs) (Created page with "local StringBuilder = {} StringBuilder.__index = StringBuilder -- Constructor function StringBuilder.new() local self = setmetatable({}, StringBuilder) self.buffer = {} return self end -- Append method function StringBuilder:append(value) if value then table.insert(self.buffer, tostring(value)) end return self end function StringBuilder:appendLine(value) if value then table.insert(self.buffer, tostring(value)) end table.insert(self.buffer,...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

StringBuilder Module Documentation

The `StringBuilder` module provides functionality to efficiently build and manipulate strings in Lua.

Constructor

StringBuilder.new()

Creates a new `StringBuilder` object.

  • Returns: `StringBuilder` object.

Methods

StringBuilder:append(...)

Appends strings or values to the `StringBuilder` buffer.

  • Parameters:
 * `...`: One or more values to append to the buffer.

StringBuilder:appendLine(...)

Appends strings or values followed by a newline (`\n`) to the `StringBuilder` buffer.

  • Parameters:
 * `...`: One or more values to append to the buffer.

StringBuilder:clear()

Clears the contents of the `StringBuilder` buffer.

  • Usage: Call this method to reset the `StringBuilder` buffer to an empty state.

StringBuilder:toString()

Converts the `StringBuilder` buffer into a concatenated string.

  • Returns: Concatenated string representation of the `StringBuilder` buffer.

Example Usage

To use the `StringBuilder` module in your Lua scripts, follow these examples:

local StringBuilder = require("StringBuilder")

-- Create a new StringBuilder object
local sb = StringBuilder.new()

-- Append strings and values to the StringBuilder buffer
sb:append("Hello, ")
  :append("world!")
sb:append(123)

-- Append a new line and more content
sb:appendLine("This is a new line.")

-- Convert StringBuilder buffer to a string
local result = sb:toString()

-- Output the result
print(result)  -- Output: "Hello, world!123\nThis is a new line."

local StringBuilder = {}
StringBuilder.__index = StringBuilder

-- Constructor
function StringBuilder.new()
    local self = setmetatable({}, StringBuilder)
    self.buffer = {}
    return self
end

-- Append method
function StringBuilder:append(value)
	if value then
    	table.insert(self.buffer, tostring(value))
	end
	
	return self
end

function StringBuilder:appendLine(value)
	if value then
		table.insert(self.buffer, tostring(value))
	end

	table.insert(self.buffer, "\n")
	return self
end

-- Clear method
function StringBuilder:clear()
    self.buffer = {}
end

-- ToString method
function StringBuilder:toString(separatorChar)
    return table.concat(self.buffer, separatorChar or '')
end

return StringBuilder