希望这不是一个愚蠢的问题,但我在偶然发现这个问题后一直在四处寻找,但找不到任何有记录的地方。语句,
中逗号()有什么用?print()
它似乎与输入之间的选项卡连接起来。
例子:
print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");
Run Code Online (Sandbox Code Playgroud)
输出:
thisisstringconcatenation
how is this also working?
Run Code Online (Sandbox Code Playgroud)
我之所以费心去研究这个,是因为它似乎允许nil
值的串联。
示例2:
local nilValues = nil;
print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues); -- ERROR -> attempt to concatenate local 'nilValues' (a nil value)
Run Code Online (Sandbox Code Playgroud)
输出2:
This somehow seems to concatenate nil
Error: lua: test.lua:7: attempt to concatenate local 'nilValues' (a nil
value)
Run Code Online (Sandbox Code Playgroud)
我尝试搜索字符串连接中逗号的用法,并检查了Lua 指南print()
中的文档,但我找不到任何解释这一点的内容。
print
可以采用可变数量的参数,并\t
在打印的项目之间插入。你可以认为 ifprint
是这样定义的:(虽然实际上不是,这个示例代码取自Programming in Lua http://www.lua.org/pil/5.2.html)
printResult = ""
function print (...)
for i,v in ipairs(arg) do
printResult = printResult .. tostring(v) .. "\t"
end
printResult = printResult .. "\n"
end
Run Code Online (Sandbox Code Playgroud)
在实施例2中
local nilValues = nil;
print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues);
Run Code Online (Sandbox Code Playgroud)
第一个print
接受多个参数,并在中间逐个打印它们\t
。请注意,这print(nil)
是有效的,并将打印nil
。
第二个print
采用单个参数,即字符串。但字符串参数"This" .. "will" .. "crash" .. "on" .. nilValues
无效,因为nil
无法与字符串连接。