user6283344
user6283344

Reputation:

How to increment the `k` here?

I was trying to increment the k in a for loop like this:

t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

for k = 1, #t do
    if k == 1 then 
        print(t[1])
    else
        print(t[k], t[k + 1], t[k + 2])
        k = k + 2
    end 
end

But it's not working! How to increment this k in else block?

Upvotes: 4

Views: 127

Answers (1)

TrebledJ
TrebledJ

Reputation: 9007

The counter variable used in a for-loop won't propagate between iterations. Consider

for i=1, 3 do
    print(i)
end
-- 1
-- 2
-- 3

Now consider

for i=1, 3 do 
    print(i)
    i = i+1 
    print(i, '\n')
end
-- 1
-- 2
--
-- 2
-- 3
--
-- 3
-- 4

Note that there is no change in the leading values (1, 2, 3).

The solution is to convert the for-loop into a while-loop, giving more freedom and control over the variable.

k = 1
while k < #t do
    if k == 1 then
        print(t[1])
    else
        print(t[k], t[k+1], t[k+2])
        k = k + 2
    end
    k = k + 1
end
-- 1
-- 2    3   4
-- 5    6   7
-- 8    9   10

Upvotes: 4

Related Questions