Skip to content

String helpers

rootbeer.str is a small set of string utilities for module authors. They exist to keep generator code (Lua tables → tool config files) concise and consistent across modules.

If you're writing your own integration that takes multi-line user input, prefer these over hand-rolled gmatch loops — the built-in patterns have a habit of silently dropping blank lines.

lua
local str = require("rootbeer.str")

-- Preserves the blank line between blocks.
for _, line in ipairs(str.split_lines("step 1\n\nstep 2")) do
    print(line)
end

-- Indents every non-empty line, leaves blanks bare.
print(str.indent("a\n\nb", "\t"))

See the authoring principles for guidance on when to use these versus inlining.

API Reference

rootbeer.str.indent(s, prefix)

Indents every non-empty line of s with prefix. Blank lines are left bare, which keeps generated output diff-friendly and avoids trailing whitespace warnings from linters.

lua
local str = require("rootbeer.str")
print(str.indent("a\n\nb", "\t"))
-- "\ta\n\n\tb"

Parameters

sstring
The string to indent.
prefixstring
The prefix to prepend to each non-empty line.

Returns

stringindented — The indented string.

rootbeer.str.split_lines(s)

Splits a string on newlines, preserving empty lines.

Unlike s:gmatch("[^\n]+"), this keeps blank lines intact so multi-line user input (function bodies, shell snippets, templates) round-trips without losing readability. A single trailing newline is normalized away to avoid introducing a phantom blank line at the end.

lua
local str = require("rootbeer.str")
for _, line in ipairs(str.split_lines("a\n\nb\n")) do
  print(line) -- "a", "", "b"
end

Parameters

sstring
The string to split.

Returns

string[]lines — One entry per line; empty lines become "".