1
這是一個簡短的程序,它接收一個表並返回表中最大數值的索引。Lua Max Number Program
我的問題是 - 有人可以向我解釋第5行for循環中的「word,count」嗎?該程序的工作原理,但我不明白如何在for循環中的單詞計數做任何事情。
numbers = {10, 5, 1}
function largest(t)
local maxcount = 0
local maxindex
for word, count in pairs(t) do
if count > maxcount then
maxcount = count
maxindex = word
end
end
return maxindex, maxcount
end
print(largest(numbers))
變量名'word'和'count'的選擇在這裏很糟糕,尤其是如果這是一本書或教程的示例代碼。更好的名字應該是'index'(或者只是'i'或'idx')和'value'。如果使用任何非數字值調用「largest()」,代碼也會做「有趣」的事情。嘗試'print(最大{「a」,3,{13},function()end})'例如。 – RBerteig 2012-07-26 22:01:33