Table.filter function

The “Problem”

I can’t say that it is too hard to filter tables but it can be streamlined considering if you do it enough times, it gets very annoying.

If a developer wanted to get a table of players that are “ready” in their game, they would do something similar to this:

local Players = game:GetService("Players");

local readyPlayers = {};
for _, player in pairs (Players:GetPlayers()) do
    if player.PlayerData.Ready.Value then
        table.insert(readyPlayers, player);
    end;
end;

table.foreach(readyPlayers, function(_, player);
    -- do stuff
end);

With table.filter() that could be shortened down to:

local Players = game:GetService("Players");

local readyPlayers = table.filter(Players:GetPlayers(), function(player)
    return player.PlayerData.Ready.Value
end);

table.foreach(targetPlayers, function(_, player);
    -- do stuff
end);

The Solution

Create a table.filter() function that allows developers to filter tables without having to create a separate loop to get the data they want into an array. Other languages, like JavaScript (ES5+), have the filter function for their tables and it makes the job of filtering data easier.

The prototype code to filter would look similar to this:

function filter( t, func, withKeys )
  	local result = { };

  	for key, value in pairs (t) do
    	if func(value, key, t) then 
			if withKeys then
				result[key] = value;
			else
				table.insert(result, value);		
			end;
    	end;
  	end;

  	return result;
end;

Sample usage code:

table.filter({ 1, 6, 7, 2, 3 }, function(n) return n > 5 end); -- { 6, 7 }

local players = { 
  a = { 
    name = 'Jane', 
    damageDealt = 1214 
  }, 
  b = { 
    name = 'John', 
    damageDealt = 23
  }, 
  c = {
    name = 'Jonathon', 
    damageDealt = 200
  }
};

table.filter(players, function(p) return p.damageDealt > 120 end, true); -- { a = { name = 'Jane', damageDealt = 1214 }, c = { name = 'Jonathon', damageDealt = 200 }
13 Likes

This topic was automatically closed after 1 minute. New replies are no longer allowed.