'How do I build a variable from a character repeated N number of times, in Lua?

I have an input value of N.

I want to turn that into a variable consisting of N characters.

for example, if N = 12, and I'm repeating the character "H", the value of the created variable should look like this: "HHHHHHHHHHHH"

I need it to be a variable, because I intend to use it in a few other places.

I am completely new to Lua, by the way. I just started a few days ago.



Solution 1:[1]

You are looking for string.rep.

For example:

local result = string.rep("H", 12)
print(result) -- prints "HHHHHHHHHHHH"

Solution 2:[2]

The datatype string has a metatable with all string functions attached as methods in __index.

Therefore you also can do...

local str, N = "H", 12
str = str:rep(N)

Solution 3:[3]

You can use the load() function to do it.

load(string.format("%s=4711", string.rep("H", 12)))()

print(HHHHHHHHHHHH)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 koyaanisqatsi
Solution 3 Peter Csala