Search code examples
lua

How to write the for loop in LUA?


There is a demo:

days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"}

    if keyJustPressed('space') then
        for i, v in ipairs(days) do
            print(v)
            break
        end
    end

I want:
When pressing key "space" the first time, print "Sunday".
When pressing key "space" the second time, print "Monday".
When pressing key "space" the third time, print "Tuesday".
And so on...

How to write the for loop?
Don't worry about keyJustPressed('space'), it works correctly.


Solution

  • You don't want to use a for loop here. but keep a variable that points to the current day. For example

    index = 1
    

    Then increase the index everytime you press space like this

    if keyJustPressed('space') then
        print(days[index])
        index = index % #days + 1
    end
    

    % #days is done here so it goes back to 1 after getting to 7. And be sure to do the index = 1 outside of the scope where you do keyJustPressed, otherwise it keeps being reset to 1