Is it possible to run a script over multiple ticks?

Place to get help with not working mods / modding interface.
Post Reply
Romner_set
Inserter
Inserter
Posts: 30
Joined: Thu Mar 07, 2019 4:25 pm
Contact:

Is it possible to run a script over multiple ticks?

Post by Romner_set »

For example :

Code: Select all

script.on_event(defines.events.on_tick, function(event)
    run_every_5_seconds
    	 if something do
    	 	do stuff
     	 	wait 1 tick
    	 	do more stuff
    	 end
    	 wait 1 tick
    	 do more stuff
    	 etc.
    end
end)
This is useful because I want to run kinda heavy code every 5 (maybe more) secs, so it is better to have a drop in UPS for a few seconds than lag the whole game for a second or two.

ratchetfreak
Filter Inserter
Filter Inserter
Posts: 952
Joined: Sat May 23, 2015 12:10 pm
Contact:

Re: Is it possible to run a script over multiple ticks?

Post by ratchetfreak »

You can use a coroutine:

Code: Select all

local mycoroutine = coroutine.create (function ()
       run_every_5_seconds
            if something do
                do stuff
                coroutine.yield()
                do more stuff
            end
            coroutine.yield()
             do more stuff
    	     etc.
        end
end )

script.on_event(defines.events.on_tick, function(event)
         coroutine.resume(mycoroutine)
end)

Romner_set
Inserter
Inserter
Posts: 30
Joined: Thu Mar 07, 2019 4:25 pm
Contact:

Re: Is it possible to run a script over multiple ticks?

Post by Romner_set »

ratchetfreak wrote:
Wed Oct 23, 2019 3:05 pm
You can use a coroutine
Oh! For now I found a way to make the code much less performance heavy, so this isn't needed. But thanks anyway!

User avatar
eradicator
Smart Inserter
Smart Inserter
Posts: 5206
Joined: Tue Jul 12, 2016 9:03 am
Contact:

Re: Is it possible to run a script over multiple ticks?

Post by eradicator »

ratchetfreak wrote:
Wed Oct 23, 2019 3:05 pm
You can use a coroutine:
Factorio engine does not suppot coroutine.

If you just want to iterate a table see this thread.
Author of: Belt Planner, Hand Crank Generator, Screenshot Maker, /sudo and more.
Mod support languages: 日本語, Deutsch, English
My code in the post above is dedicated to the public domain under CC0.


Post Reply

Return to “Modding help”