2013-06-03 73 views
3

但愿这不是一个愚蠢的问题,而是跨越这个绊脚石后,我一直在寻找周围,我找不到任何地方,这是记录在案。 print()陈述中逗号(,)的用法是什么?它似乎与输入之间的选项卡连接。逗号分隔的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) 

我试图寻找逗号的字符串连接使用,并还审议了print()文件从Lua guide,但我找不到任何解释这一点的东西。

回答

4

print可以采取可变数量的参数,并插入打印的项目之间\t。可以认为,仿佛print被这样定义:(虽然它实际上是没有,这个例子中的代码是从编程在Luahttp://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不能与字符串连接。

+0

完美!非常明确,乐于助人!非常感谢你! – MrHappyAsthma

+0

实际上,即使是PiL 1也有这样的示例代码,这是误导性的:print不会在每行的末尾添加制表符。用这个替换循环,它工作(在Lua 5.1中):'printResult = table.concat(arg,“\ t”)' – catwell

+0

@catwell可以肯定,我检查了Lua源代码,'print' did add' t'。参见函数'luaB_print'。 Pil1代码仅供参考。 –

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

在第一次打印中,只有一个参数。它是一个字符串,“thisisstringconcatenation”。因为它首先进行连接,然后传递给打印功能。

在第二打印,有5个参数传递给打印。

local nilValues = nil; 

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

在第二个例子,你Concat的一个零values.Then字符串会导致错误