44local GLOBAL_KEY = ' emigration' -- used for state change hooks and persistence
55
66enabled = enabled or false
7+ last_cycle_tick = last_cycle_tick or 0
78
89function isEnabled ()
910 return enabled
1011end
1112
1213local function persist_state ()
13- dfhack .persistent .saveSiteData (GLOBAL_KEY , {enabled = enabled })
14+ dfhack .persistent .saveSiteData (GLOBAL_KEY , {enabled = enabled , last_cycle_tick = last_cycle_tick })
1415end
1516
1617function desireToStay (unit ,method ,civ_id )
@@ -191,12 +192,20 @@ function checkmigrationnow()
191192 else
192193 for _ , civ_id in pairs (merchant_civ_ids ) do checkForDeserters (' merchant' , civ_id ) end
193194 end
195+
196+ last_cycle_tick = dfhack .world .ReadCurrentTick () + 403200 * dfhack .world .ReadCurrentYear ()
194197end
195198
196199local function event_loop ()
197200 if enabled then
198- checkmigrationnow ()
199- dfhack .timeout (1 , ' months' , event_loop )
201+ local current_tick = dfhack .world .ReadCurrentTick () + 403200 * dfhack .world .ReadCurrentYear ()
202+ if last_cycle_tick and (current_tick - last_cycle_tick < 33600 ) then
203+ local timeout_ticks = last_cycle_tick - current_tick + 33600
204+ dfhack .timeout (timeout_ticks , ' ticks' , event_loop )
205+ else
206+ checkmigrationnow ()
207+ dfhack .timeout (1 , ' months' , event_loop )
208+ end
200209 end
201210end
202211
@@ -210,8 +219,9 @@ dfhack.onStateChange[GLOBAL_KEY] = function(sc)
210219 return
211220 end
212221
213- local persisted_data = dfhack .persistent .getSiteData (GLOBAL_KEY , {enabled = false })
222+ local persisted_data = dfhack .persistent .getSiteData (GLOBAL_KEY , {enabled = false , last_cycle_tick = 0 })
214223 enabled = persisted_data .enabled
224+ last_cycle_tick = persisted_data .last_cycle_tick
215225 event_loop ()
216226end
217227
0 commit comments