List-Styled Tables

From Garry's Mod
Jump to: navigation, search

What is a List?

Value-indexed tables are a commonly-neglected technique in Lua:

local tbl = {[1] = "a",[2] = "b",[3] = "c"} --this is a normal sequential table.
--Checking if a value is in a normal table:
function table.HasValue(tbl,value) --O(n) worst-case complexity
   for k,v in pairs(tbl)do
      if v == value then return true end
   end
   return false
end

local list = {["a"]=true, ["b"]=true, ["c"]=true} --this is a value-indexed version of that table.
--Checking if a value is in a value-indexed table:
function ListHasValue(tbl,value) --O(1) worst-case complexity
   return tbl[value]
end

We'll call them Lists, for short. They're incredibly useful! The idea is that by using the actual value we intend to store in the table as the key itself, we can retrieve and remove it from the table much easier and faster. This has many uses:

  • Good for when the order of data saved is unimportant and each value is unique within the table.
  • Creating a table in which the same value can't exist more than once.
  • Rapidly checking whether a value is stored in a table without the use of iteration (seen above).


Two-Dimensional Lists

We can take it one step further with 2D Lists:

--A 2D sequential table holding players' friends as {guy=player, friends={their friends}}
local friendTbl = { {guy=Entity(1), friends={Entity(2), Entity(3)}}, {guy=Entity(2), friends={Entity(1)}}, {guy=Entity(3),friends={Entity(1)}} } 
function TwoPlayersAreFriends(ply,ply2)
   for k,v in pairs(friendTbl)do
      if v.guy == ply then
         for k2,v2 in pairs(v.friends)do
            if v2 == ply2 then
               return true
            end
         end
         return false
      end
   end
   return false
end

--And this is a 2D list which holds the same data as above.
local friendList = { [Entity(1)] = {Entity(2)=true, Entity(3)=true}, [Entity(2)] = {Entity(1)=true}, [Entity(3)] = {Entity(1)=true} }
--Checking if a value is in a value-indexed table:
function TwoPlayersAreFriends(ply,ply2)
   return friendList[ply][ply2]
end

Look at how much faster and simpler that is! If you wanted to, you could even replace `true` in the list with some kind of data. This makes the list into a dictionary.

So remember: Any time you need to save distinct data in an unordered table, opt to use a List instead!

Personal tools
Navigation