如何在 Lua 中乘以一个字符串?

How do I multiply a string in Lua?

我想乘以一个字符串并将它们存储到一个变量中,这是我想做的一个例子,但是在 Python:

a = "A" * 200

pete 和 repete 在船上...请注意 repeat 的故意拼写错误,因为这是 Lua 中的关键字。您将 concatenation 与容器一起使用。

#! /usr/bin/env lua
local pete, repete, boat  = 'a',  20,  ''

for a = 1, repete do boat = boat ..pete end
print( boat )

aaaaaaaaaaaaaaaaaaaa

您可以使用标准函数:

a = string.rep("A", 200)

如果你只需要重复字符串 n 次你应该使用 string.rep

string.rep (s, n [, sep])

Returns a string that is the concatenation of n copies of the string s separated by the string sep. The default value for sep is the empty string (that is, no separator). Returns the empty string if n is not positive.

(Note that it is very easy to exhaust the memory of your machine with a single call to this function.)

如果你想使用乘法语法,你可以在字符串元表中实现 __mult 元方法

getmetatable("a").__mult = string.rep

不过这会改变 Lua 的行为。 Lua 会将 "1" * "4" 隐式转换为 1 * 4,后者解析为 4。在我们的更改之后,它将导致 "1111"

这可能会导致以后出现问题。这也会影响所有字符串,因此您可能会在您的公共代码库中更改不打算这样做的其他人的代码。

所以我个人建议在需要重复字符串时坚持使用 string.rep