Skip to content

Instantly share code, notes, and snippets.

@NullEntity
Forked from anonymous/voicechat.lua
Last active October 14, 2015 03:34
Show Gist options
  • Save NullEntity/06f011024de4f2e47e6d to your computer and use it in GitHub Desktop.
Save NullEntity/06f011024de4f2e47e6d to your computer and use it in GitHub Desktop.
-- 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()) or (not talker:Alive() and not listener: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