Lua Max Number Program
问题描述:
这是一个简短的程序,它接收一个表并返回表中最大数值的索引。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))
答
运行下面的代码应该更清楚:
tbl = { a = "one", b = "two", c = "two and half" }
for key, val in pairs(tbl) do print(key, val) end
当您在for循环运行pairs
,它执行do
和end
之间的代码,一旦在每个键/值对表; for x, y in
设置循环内代码的键名和值。 pairs
是iterator最常见的示例。
+0
非常感谢你!真的帮了! – 2012-07-26 18:08:17
变量名'word'和'count'的选择在这里很糟糕,尤其是如果这是一本书或教程的示例代码。更好的名字应该是'index'(或者只是'i'或'idx')和'value'。如果使用任何非数字值调用“largest()”,代码也会做“有趣”的事情。尝试'print(最大{“a”,3,{13},function()end})'例如。 – RBerteig 2012-07-26 22:01:33