Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Indexing 最大数程序_Indexing_Lua_Iteration_Lua Table - Fatal编程技术网

Indexing 最大数程序

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

下面是一个简短的程序,它接收一个表,并返回表中最大数值的索引

我的问题是-有人能给我解释一下第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 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})