如何将大的 lua 字符串分成小字符串
我有一个大字符串(base64 编码的图像),它有 1050 个字符长。如何附加由小字符串组成的大字符串,就像在 C 中一样
function GetIcon()
return "Bigggg string 1"\
"continuation of string"\
"continuation of string"\
"End of string"
I have a big string (a base64 encoded image) and it is 1050 characters long. How can I append a big string formed of small ones, like this in C
function GetIcon()
return "Bigggg string 1"\
"continuation of string"\
"continuation of string"\
"End of string"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据 Lua 2.4 字符串编程:
这是与您所要求的最接近的事情,但是使用上述方法会将换行符嵌入到字符串中,因此这不会直接起作用。
您还可以通过字符串连接来完成此操作(使用 ..):
According to Programming in Lua 2.4 Strings:
This is the closest thing to what you are asking for, but using the above method keeps the newlines embedded in the string, so this will not work directly.
You can also do this with string concatenation (using ..):
这里的大多数答案在运行时解决这个问题,而不是在编译时解决。
Lua 5.2引入了转义序列
\z
来优雅地解决这个问题,并且不会产生任何运行时开销。\z
跳过字符串文字1 中的所有后续字符,直到第一个非空格字符。这也适用于非多行文字文本。摘自Lua 5.2参考手册
1:所有转义序列,包括
\z
,仅适用于短文字字符串("..."
、'... '
),并且可以理解的是,不在长文字字符串上([[...]]
等)Most answers here solves this issue at run-time and not at compile-time.
Lua 5.2 introduces the escape sequence
\z
to solve this problem elegantly without incurring any run-time expense.\z
skips all subsequent characters in a string literal1 until the first non-space character. This works for non-multiline literal text too.From Lua 5.2 Reference Manual
1: All escape sequences, including
\z
, work only on short literal strings ("…"
,'…'
) and, understandably, not on long literal strings ([[...]]
, etc.)我将所有块放入表中并对其使用
table.concat
。这避免了在每次连接时创建新字符串。例如(不计算 Lua 中字符串的开销):如您所见,它的爆炸速度非常快。最好:
大约需要 3*4+12=24 字节。
I'd put all chunks in a table and use
table.concat
on it. This avoids the creation of new strings at every concatenation. for example (without counting overhead for strings in Lua):As you can see, this explodes pretty rapidly. It's better to:
Which will take about 3*4+12=24 bytes.
你有没有尝试过
string.sub(s, i [, j]) 函数。
您可能想看这里:
http://lua-users.org/wiki/StringLibraryTutorial
Have you tried the
string.sub(s, i [, j]) function.
You may like to look here:
http://lua-users.org/wiki/StringLibraryTutorial
这种:
C/C++ 语法使编译器将其全部视为一个大字符串。它通常用于可读性。
Lua 等效项是:
请注意,C/C++ 语法是编译时的,而 Lua 等效项可能在运行时进行串联(尽管编译器理论上可以优化它)。不过这应该没什么大不了的。
This:
C/C++ syntax causes the compiler to see it all as one large string. It is generally used for readability.
The Lua equivalent would be:
Do note that the C/C++ syntax is compile-time, while the Lua equivalent likely does the concatenation at runtime (though the compiler could theoretically optimize it). It shouldn't be a big deal though.