2013-06-03 77 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字符串會導致錯誤