2015-09-29 105 views
1

有没有这样的函数在Lua(Python中)x范围的功能,这样我就可以做这样的事情:Lua中是否有像xrange这样的函数?

for i in xrange(10) do 
    print(i) 
end 

这是与其他问题不同,因为他正在寻找一个条件测试,但我我不是在寻找一个状态测试器。

+1

[Lua For Variable In Range]可能重复(http://stackoverflow.com/questions/12020574/lua-for-variable-in-range) – scrappedcola

+0

@scrappedcola不,与其他问题不同,因为他正在寻找对于一个条件测试器,但我不是在寻找一个条件测试器。 – wb9688

+1

答案提供了一种获取一系列数字的方法。除非你真的在lua里有一个动态存储列表的函数,而不是创建一个静态列表,那么'var = 2,20 do'就是你的问题的答案。你需要指定你正在寻找的xrange的功能 – scrappedcola

回答

2

如果你想遍历号码:

for i = 0,9 do 
    print(i) 
end 

在其他的方式可以使你自己的迭代:

function range(from, to, step) 
    step = step or 1 
    return function(_, last) 
    local next = last + step 
    if step > 0 and next < to or step < 0 and next > to or step == 0 then 
     return next 
    end 
    end, nil, from - step 
end 

,并使用它:for i in range(0, 10) do print(i) end

还可以看到http://lua-users.org/wiki/RangeIterator

0
function xrange(a,b,step) 
    step = step or 1 
    if b == nil then a, b = 1, a end 
    if step == 0 then error('ValueError: xrange() arg 3 must not be zero') end 
    if a + step < a then return function() end end 
    a = a - step 
    return function() 
      a = a + step 
      if a <= b then return a end 
     end 
end 
相关问题