给定lua脚本中for循环语法的解释 [英] Explaination of for loop syntax in given lua script

查看:52
本文介绍了给定lua脚本中for循环语法的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来了解以下lua脚本中_,v的 下一行,键,没有做 .

I need help understanding this for _,v in next,keys,nil do line in the below lua script.

在这里,我们从redis数据库中获取一个我认为是列表的列表,然后对其进行迭代.但是我不明白这个for循环语法是如何工作的.

Here we are fetching i think a list from redis database and then iterating over it. But i couldn't understand how this for loop syntax is working.

local keys=redis.call('keys', 'someRegexPattern');

for _,v in next,keys,nil do
  -- doing somethings with variable v
end

return something;

我知道 _ 用作占位符来保存我们不会在循环中使用的值.但是我们如何在RHS中有3个变量,而在LHS中只有2个变量

I know that _ is used as placeholders to hold values we will not be using in the loop. But how do we have 3 variables in RHS and only 2 variables in LHS

感谢您的帮助

推荐答案

这是Lua中 for 循环的通用形式.in 右侧的三个参数是迭代器、状态和初始值:

This is the generic form of the for loop in Lua. The three arguments on the right side of the in are the iterator, the state and the initial value:

for value, other variables... in iterator, state, initialValue do ... end

在每次迭代中,将状态和当前值(在第一次迭代中,初始值)传递给迭代器,并返回下一个值(可能还包含其他迭代变量),直到返回的值为false.

On each iteration the state and the current value (on the first iteration the initial value) are passed to the iterator, and it returns the next value, possibly with additional iteration variables, until the returned value is falsey.

在您的情况下,迭代器是 next 函数.它具有一个表和一个键名,并返回该表的下一个键以及该键在表中的值.如果键为 nil ,则返回表的第一项.

In your case the iterator is the next function. It takes a table and a key name, and returns the next key of the table alongside the value of that key from the table. If the key is nil, it returns the first entry of the table.

有关其工作方式的更多技术细节,请参见 Lua参考手册

For more technical details on how it works you can see the Lua Reference Manual

这篇关于给定lua脚本中for循环语法的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆