harpy eagle wrote:I have a question about how the memoization functions work in the game. So suppose I wanted to cache the number of inhabited planets the current empire has this turn, to avoid iterating through empire.planets to count them every time. Would the following work?
Yes, that should work.
harpy eagle wrote:How does the memoizer know when the cache has become stale and the function needs to be called again?
SiS runs Lua with the automatic garbage collector turned off -- however, we do a manual garbage collection pass any time either 1) the player completes a strategic action or 2) the game window is resized.
Thus, when you're writing logic for the UI, most of the time you're interacting with variables that can be easily and safely cached inside a function memoization that persists until the next GC pass. That's exactly what all the 'weak_memoize' helper functions do*.
However; context really matters for memorization tricks. If you're planning to use it inside, say, a callback that's processed as part of the 'year end' strategic updates, weak memoization hacks aren't particularly safe**; most important values are likely to change a few times before the 'year end updates' function completes (and thus, the cache may not flush soon enough to ensure that your data is correct).
* editors note: This is technically a lie -- only the weak_memoize_1_to_n and weak_memoizeNN functions are guaranteed to be flushed with a GC pass. The single return value memoizers may not flush if they return tables or functions. Just to avoid confusing myself, I'll often default to using weak_memoizeNN -- even though it's technically very slightly slower than the other options, it saves the headache of worrying about return types.
** editors note(2): I recently got myself into trouble by calling the planet pop_and_habs property inside a year-end mechanic. It's an easy mistake to make.