Created
October 14, 2015 03:27
-
-
Save anonymous/db9b30b8a66c8421cccb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
returns `fn` which memoizes its arguments | |
local function memoize( fn ) | |
local cache = {} | |
local function memoize(...) | |
-- convert args into a string if they're a table | |
local args = {...} | |
local sArg = table.ToString(args) | |
-- get the item with the given arguments from the cache | |
local cached = cache[sArg] | |
if cached == nil then | |
-- if it doesn't exist, store it then return it | |
local res = fn(...) | |
cache[sArg] = res | |
return res | |
else | |
-- otherwise return the value from the cache | |
return cached | |
end | |
end | |
return memoize | |
end | |
-- can listener hear talker? | |
local function playerCanHearPlayersVoice( listener, talker ) | |
return talker:Team() ~= TEAM_HIDDEN and talker:Alive() | |
end | |
-- memoize the can hear function and rememoize it each second | |
-- to essentially rebuild the can hear cache | |
local cached = memoize(playerCanHearPlayersVoice) | |
timer.Create("ClearVoiceCache", 1, 0, function() | |
cached = memoize(playerCanHearPlayersVoice) | |
end ) | |
-- hook the cached function. This hook is called hundreds times | |
-- a second so the results need to be cached | |
hook.Add( "PlayerCanHearPlayersVoice", "VoiceCache", function(...) | |
return cached(...) | |
end ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment