Is there any way to repeat a character 'X' amount of times using the string library?

I’m pretty sure this can be done with string.format, but I don’t really understand the documentation for it.

Anyway, what I want to do is to be able to repeat a character like this:

local repeatCount = 16
local charToRep = 'H'
local reppedChar = '%s%s'
for i = 1, repeatCount do
    reppedChar = i ~= repeatCount and reppedChar:format(charToRep, '%s%s') or reppedChar:format(charToRep, '')
end

Now, obviously I could use the code above, but is there any way to do this using string.format()?

@domboss37 Yes; but in some cases, using :format("String 1 %s", "String 2") or string.format("String 1 %s", "String 2") is faster. source

You can use string.rep( 'a', 3)
The line above repeats the letter a 3 times.

local repeatCount = 16
local charToRep = 'H'

local repeated = string.rep(charToRep, 16)

Note: to add it to a new string use .. to concatenate it

4 Likes

Your choice, aslong as it works!

1 Like