string.rep()
The string.rep()
function in Lua is used to generate a new string by repeating an existing string a specified number of times. This is useful for creating strings with repeated patterns or for formatting output.
Syntax
string.rep(string, times)
Parameters
- Name
string
- Type
- string
- Description
The string that will be repeated.
- Name
times
- Type
- number
- Description
The number of times to repeat the string. It must be a positive integer.
Return Value
Returns a new string that is the result of repeating the input string the specified number of times. If times
is less than or equal to zero, an empty string is returned.
Examples
Example 1: Basic String Repetition
Repeat a simple string multiple times.
Example 1
local repeated = string.rep("Lua ", 3)
print(repeated) -- Output: Lua Lua Lua
Example 2: Repeating with Different Values
Repeat a string with different numbers.
Example 2
local repeated = string.rep("A", 5)
print(repeated) -- Output: AAAAA
Example 3: Handling Zero and Negative Values
Demonstrate behavior when times
is zero or negative.
Example 3
local empty = string.rep("Hello", 0)
print(empty) -- Output: (empty string)
local negative = string.rep("Hello", -1)
print(negative) -- Output: (empty string)
Example 4: Creating Patterns
Use string.rep()
to create a string pattern.
Example 4
local pattern = string.rep("-", 10)
print(pattern) -- Output: ----------
Use Cases
- Output Formatting: Creating formatted output for console display or logs.
- String Manipulation: Building strings with repeated elements for various applications.
See also
string.len()
: Returns the length of a string, useful in conjunction withstring.rep()
for formatting.