希望这不是一个愚蠢的问题,但我在偶然发现这个问题后一直在四处寻找,但我找不到任何地方对此进行记录。 print()
语句中的逗号 (,
) 有什么用。它似乎与输入之间的制表符连接。
例子:
print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");
输出:
thisisstringconcatenation
how is this also working?
我什至费心研究这个的原因是因为它似乎允许连接 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)
输出 2:
This somehow seems to concatenate nil
Error: lua: test.lua:7: attempt to concatenate local 'nilValues' (a nil
value)
我尝试搜索逗号在字符串连接中的用法,还检查了来自 Lua guide 的 print()
的文档。 ,但我找不到任何解释这一点的内容。
最佳答案
print
可以接受可变数量的参数,并在打印的项目之间插入 \t
。你可以认为好像 print
是这样定义的:(尽管实际上不是,这个示例代码来自 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
例2
local nilValues = nil;
print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues);
第一个 print
接受多个参数,并用 \t
将它们一个接一个地打印出来。请注意 print(nil)
是有效的,并将打印 nil
。
第二个print
接受一个参数,即一个字符串。但是字符串参数 "This".. "will".. "crash".. "on".. nilValues
是无效的,因为 nil
不能与字符串连接.
关于syntax - 逗号分隔打印(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16898228/