Jeff Zivkovic
Jeff Zivkovic

Reputation: 587

Lua update screen during loop

I'm writing a function for an on-screen character to follow a path of markers. I'd like to iterate through all of the markers for that character, and update the display for each. What's happening now is that the display only updates once at the end of the iteration. Based on a few FAQs, it appears that lua is designed to work this way. So what's the best way to accomplish gradual movement in lua?

local function follow_movement_path (moving_char)
    these_markers = moving_char.move_markers
    for m, n in ipairs(these_markers) do
        this_marker = n
        moving_char.x = this_marker.x
        moving_char.y = this_marker.y
        print(this_marker.current_space.name)
        sleep(1)
    end
end 

Thank you in advance for any insight.

Upvotes: 2

Views: 400

Answers (1)

gotocoffee
gotocoffee

Reputation: 199

This blog gives an example how to solve this problem. An interesting one is the coroutines (or here) approch. The idea is that you can still write the code like in your example but after every iterration you break out of the loop, draw on screen and continue the function on the exact position you left.

Could look like this:

local function follow_movement_path (moving_char)
    these_markers = moving_char.move_markers
    for m, n in ipairs(these_markers) do
        this_marker = n
        moving_char.x = this_marker.x
        moving_char.y = this_marker.y
        print(this_marker.current_space.name)
        coroutine.yield()
    end
end

local c = coroutine.create(follow_movement_path)
coroutine.resume(c)
draw_on_display()
coroutine.resume(c)

Upvotes: 2

Related Questions