Indexing 最大数程序
下面是一个简短的程序,它接收一个表,并返回表中最大数值的索引 我的问题是-有人能给我解释一下第5行for循环中的“单词,计数”吗?这个程序可以工作,但我不理解for循环中的count这个词是如何工作的Indexing 最大数程序,indexing,lua,iteration,lua-table,Indexing,Lua,Iteration,Lua Table,下面是一个简短的程序,它接收一个表,并返回表中最大数值的索引 我的问题是-有人能给我解释一下第5行for循环中的“单词,计数”吗?这个程序可以工作,但我不理解for循环中的count这个词是如何工作的 numbers = {10, 5, 1} function largest(t) local maxcount = 0 local maxindex for word, count in pairs(t) do if count > maxcount the
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
之间的代码对于x,y in
设置循环中代码的键名和值<代码>配对是最常见的一个例子。非常感谢!真的很有帮助!这里变量名word
和count
的选择非常糟糕,特别是如果这是一本书或教程中的示例代码。更好的名称应该是index
(或者只是i
或idx
)和value
。如果使用任何非数字值调用maximum()
,代码也会做一些“有趣的”事情。例如,尝试print(最大的{“a”,3,{13},函数()end})
。