bra*_*tao 23 string lua multiline literals
我有一个大字符串(base64编码图像),它长1050个字符.如何在C中添加一个由小的字符串组成的大字符串
function GetIcon()
return "Bigggg string 1"\
"continuation of string"\
"continuation of string"\
"End of string"
Run Code Online (Sandbox Code Playgroud)
cra*_*str 36
我们也可以通过匹配双方括号[[...]]来分隔文字字符串.这种括号中的文字可能会运行几行,可能会嵌套,并且不会解释转义序列.此外,当此字符是换行符时,此表单忽略字符串的第一个字符.这种形式对于编写包含程序片段的字符串特别方便; 例如,
page = [[
<HTML>
<HEAD>
<TITLE>An HTML Page</TITLE>
</HEAD>
<BODY>
<A HREF="http://www.lua.org">Lua</A>
[[a text between double brackets]]
</BODY>
</HTML>
]]
Run Code Online (Sandbox Code Playgroud)
这是你要求的最接近的东西,但是使用上面的方法会将新行嵌入字符串中,因此这不会直接起作用.
您也可以使用字符串连接(使用..)来执行此操作:
value = "long text that" ..
" I want to carry over" ..
"onto multiple lines"
Run Code Online (Sandbox Code Playgroud)
leg*_*s2k 15
这里的大多数答案在运行时而不是在编译时解决了这个问题.
Lua 5.2引入了转义序列\z来优雅地解决这个问题,而不会产生任何运行时费用.
> print "This is a long \z
>> string with \z
>> breaks in between, \z
>> and is spanning multiple lines \z
>> but still is a single string only!"
This is a long string with breaks in between, and is spanning multiple lines but still is a single string only!
Run Code Online (Sandbox Code Playgroud)
\z跳过字符串中的所有后续字符,直到第一个非空格字符.这也适用于非多行文字文本.
> print "This is a simple \z string"
This is a simple string
Run Code Online (Sandbox Code Playgroud)
转义序列'\ z'跳过以下白色空格字符跨度,包括换行符; 将长文字字符串分解并缩进多行而不将新行和空格添加到字符串内容中特别有用.
我将所有块放入表中并使用table.concat它。这避免了在每次连接时创建新字符串。例如(不计算 Lua 中字符串的开销):
-- bytes used
foo="1234".. -- 4 = 4
"4567".. -- 4 + 4 + 8 = 16
"89ab" -- 16 + 4 + 12 = 32
-- | | | \_ grand total after concatenation on last line
-- | | \_ second operand of concatenation
-- | \_ first operand of concatenation
-- \_ total size used until last concatenation
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这种爆炸速度非常快。最好是:
foo=table.concat{
"1234",
"4567",
"89ab"}
Run Code Online (Sandbox Code Playgroud)
大约需要 3*4+12=24 字节。