Combining tables

Post Reply
ali0sha
Posts: 4
Joined: Tue Jun 30, 2009 7:25 am

Combining tables

Post by ali0sha »

I wrote a small function that takes two tables, list1 and list2 and combines them. I use it for concatenating lists of enemies. Is there an easier way to do this?

Code: Select all

function combinelists(list1 , list2)
   index = {}
   for i = 1, #list2 do
      for v = 1, #list1 do
         if list2[i] == list1[v] then
            table.insert(index,i)
         end
      end
   end
   for i = 0, #index-1 do
      table.remove(list2,index[#index-i])
   end
   for i = 1,#list2 do
      table.insert(list1,list2[i])
   end 
   return(list1)
end

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: Combining tables

Post by Vadi »

Code: Select all

function combinelists(l1, l2)
   if typeof l1 ~= "table" or typeof l2 ~= "table" then return end
   
   local list1 = l1
   local list2 = l1
   local index = {}
   for i = 1, #list2 do
      for v = 1, #list1 do
         if list2[i] == list1[v] then
            table.insert(index,i)
         end
      end
   end
   for i = 0, #index-1 do
      table.remove(list2,index[#index-i])
   end
   for i = 1,#list2 do
      table.insert(list1,list2[i])
   end
   return(list1)
end
Added a check to make sure that you're given tables, and localized the tables (see the tips section - localizing makes accessing them much faster)

derekperrault
Posts: 14
Joined: Sun May 31, 2009 7:40 am

Re: Combining tables

Post by derekperrault »

You can implement a "poor man's Set" and make use of speedy O(1) key look-ups.

enemies = {}
enemies['bob'] = 'bob'
enemies['charles'] = 'charles'

If you attempt to access an enemy that doesn't exist, "nil" is returned, which is a nice handy false value for your if-statement.

In this way, you'll only have to loop over one of the tables, doing key look-ups on all the values contained within.

Post Reply