syntax - 逗号分隔打印()

标签 syntax lua null

希望这不是一个愚蠢的问题,但我在偶然发现这个问题后一直在四处寻找,但我找不到任何地方对此进行记录。 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 guideprint() 的文档。 ,但我找不到任何解释这一点的内容。

最佳答案

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/

相关文章:

c++ - 如何在不使用单词 'operator' 的情况下调用模板化运算符重载?

c++ - 如何在 C++ 中获取预加载的模块名称

lua - 将数据位置信息添加到 latex 输出

c# - C# 中 override 和 virtual 的使用 vs. Java 方法覆盖

perl - Perl源代码中的 "1;"是什么?

lua - 在名为 foo.lua 的 Lua 文件中,名为 self.bar、foo.bar 和 bar 的变量之间有什么区别?

ms-access - Ms Access 中的 DoEvents 语句出现 "Invalid use of Null"错误

javascript - IE 中奇怪的 "Null or not an object"错误

组件中的 hibernate 空集合

C 程序语法(未编译)