gpt4 book ai didi

lua - 'for in '循环调用在Lua中有作用吗?

转载 作者:行者123 更新时间:2023-12-04 19:22:50 25 4
gpt4 key购买 nike

Programming in Lua中有一段代码让我很困惑

local iterator   -- to be defined later
function allwords ()
local state = {line = io.read(), pos = 1}
return iterator, state
end

function iterator (state)
while state.line do -- repeat while there are lines
-- search for next word
local s, e = string.find(state.line, "%w+", state.pos)
if s then -- found a word?
-- update next position (after this word)
state.pos = e + 1
return string.sub(state.line, s, e)
else -- word not found
state.line = io.read() -- try next line...
state.pos = 1 -- ... from first position
end
end
return nil -- no more lines: end loop
end
--here is the way I use this iterator:
for i ,s in allwords() do
print (i)
end

似乎“for in”循环使用参数状态隐式调用函数迭代器: 我(小号)

谁能告诉我,发生了什么事?

最佳答案

是的。引用 Lua Manual

The generic for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil.

通用的 for 语句只是一个语法糖:

A for statement like

for var_1, ···, var_n in explist do block end

is equivalent to the code:

do
local f, s, var = explist
while true do
local var_1, ···, var_n = f(s, var)
if var_1 == nil then break end
var = var_1
block
end
end

关于lua - 'for in '循环调用在Lua中有作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com