One thing I'd like to do is possibly replace some of the table-based caches I'm using in the combat AI mod with memoization. Especially since if I can use N-to-N memoization to memorize priority values not just for ships, but for ship-weapon combinations, I might have a shot at getting the AI to take into account Armor Piercing and Shield Piercing weapon mods.
To do that I need to be able to flush the entire cache at the start of each turn, and flush the cache just for certain ships when needed.
The first one should be easy I think? I have an ai_turn table that stores information needed only for that turn, if I define the memoized function as an entry in that table the cache should be discarded when the table is, right?
The second one I'm not so sure about. I skimmed Orders\farming.lua, but I didn't see anything that could flush a memorized value just for a particular key. The main place where I saw cache flushing was in reset_food_caches(), and that seems to work by replacing entire function values.
I guess if I really need to though I can continue using tables.
Memoization
- sven
- Site Admin
- Posts: 1621
- Joined: Sat Jan 31, 2015 10:24 pm
- Location: British Columbia, Canada
- Contact:
Re: Memoization
Yes. (Or could could even just write your function straight to _ENV, as new variables created in _ENV get thrown away when the ai_context call completes. )harpy eagle wrote:The first one should be easy I think? I have an ai_turn table that stores information needed only for that turn, if I define the memoized function as an entry in that table the cache should be discarded when the table is, right?
Yes, all my standard memoization functions use underlying tables that are variously hidden; there's no way to clear a particular cache value, other than just throwing out the whole function and starting with a completely clean cache.harpy eagle wrote:The second one I'm not so sure about. I skimmed Orders\farming.lua, but I didn't see anything that could flush a memorized value just for a particular key. The main place where I saw cache flushing was in reset_food_caches(), and that seems to work by replacing entire function values.
Well, there are a variety of tricks you can use to basically turn a table into an N to M memoizer with an exposed cache; basically by abusing the existing N-to-M memoization functions and 'catch'. For example, if you write a hack like:harpy eagle wrote:I guess if I really need to though I can continue using tables.
Code: Select all
get_weapon_ship_id = strong_memoizeNN | function(ship,weapon)
return catch(ship,weapon)
end
-- then you can do nonsense like
weapon_evals = {}
local id = get_weapon_ship_id (ship,weapon)
-- update the rating for this ship/weapon pair, but only if it isn't cached.
weapon_evals [id] = weapon_evals [id] or catch(my_rating_function(id()))