我如何在lua中做for i in range的事情

1 lua

我想知道如何在 Lua 中做到这一点

Python:

for i in range(10)
 print("Hello World")
Run Code Online (Sandbox Code Playgroud)

LMD*_*LMD 5

Lua 有一个特殊的“numeric for”循环。存在两种形式:

for i = from, to do ... end
Run Code Online (Sandbox Code Playgroud)

相当于for i in range(from, to + 1)Python 中的范围,因为 Python 范围有一个独占的结束索引,并且

for i = from, to, increment do ... end
Run Code Online (Sandbox Code Playgroud)

相当于for i in range(from, to + increment, increment)Python中的。

Python 的范围循环允许省略from参数并仅提供(独占)to参数,如示例所示:

for i in range(10):
    print(i)
Run Code Online (Sandbox Code Playgroud)

等于

for i = 1, 10 do print(i) end
Run Code Online (Sandbox Code Playgroud)

在 Lua 中:Python 将从 0 开始一直到 9,而 Lua 循环从 1 开始一直到 10。如果你不需要索引 - 并且只需要to多次迭代 -或者索引应该是索引Lua 表、字符串等,您应该使用从 1 到 10(包括两者)的循环。

for i in range(to)Lua 中Python 的正确等效循环是

for i = 0, to - 1 do ... end
Run Code Online (Sandbox Code Playgroud)

最后,您可以实现自己的range迭代器。不过,由于函数调用开销,这会表现出更差的性能。

function range(...)
    local n_args = select("#", ...)
    local increment = 1
    if n_args == 1 then
        from, to = 0, ...
    elseif n_args == 2 then
        from, to = ...
    elseif n_args == 3 then
        from, to, increment = ...
    else error"range requires 1-3 arguments" end

    local i = from
    return function()
        if i >= to then return end -- note: to is exclusive
        local prev_i = i
        i = i + increment
        return prev_i
    end
end
Run Code Online (Sandbox Code Playgroud)

用法就像Python一样range

for i in range(stop) do ... end
for i in range(start, stop) do ... end
for i in range(start, stop, increment) do ... end
Run Code Online (Sandbox Code Playgroud)