逗号分隔的打印()

希望这不是一个愚蠢的问题,但是当我偶然发现这个问题后我搜索了一下,但是我找不到任何文档来解释这个问题。在print()语句中,逗号(,)的用途是什么?它似乎会在输入之间连接一个制表符。

例如:

print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");

输出:

this is string concatenation

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指南上的print()文档,但我找不到任何解释这个问题的东西。

点赞
用户1009479
用户1009479

print 可以接受变量数量的参数,并在打印的项之间插入 \t。您可以把它看作是像这样定义的:(虽然实际上并不是这样,但是这个示例代码来源于 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 不能与字符串连接。

2013-06-03 14:06:44
用户1290114
用户1290114
print("this" .. "is" .. "string" .. "concatenation");
print("how", "is", "this", "also", "working?");

在第一个 print 语句中,只有一个参数。它是一个字符串 "thisisstringconcatenation"。因为它先进行字符串拼接,然后再传递给 print 函数。

在第二个 print 语句中,有 5 个参数传递给 print。

local nilValues = nil;

print("This", "somehow", "seems", "to", "concatenate", nilValues);
print("This" .. "will" .. "crash" .. "on" .. nilValues);

在第二个例子中,您将一个字符串与一个 nil 值拼接起来,从而导致错误。

2013-06-04 11:20:24