Search code examples
lua

Compare a variable to all the variables from a Lua table?


I am a new Lua user, and I have some questions regarding comparing variables to multiple values from a table.

So, let's start.

I have a variable named 'PLATE' that is equal to "AAA 111" .

I also have a table names 'VEHICLES' that has multiple values similar to PLATE, for example: AAA 333, AAA 222, AAA 111.

I use a script to check if PLATE is equal to value from the table. Here is the script:


for i = 1, #Vehicles, 1 do

  if PLATE == Vehicles[i].plate then 
    -- do action
  elseif PLATE ~= Vehicles[i].plate then
    -- do  2 action
  end
end

Because AAA 111 has the index 3, it first checks index 1 and index 2, and runs the second action. However, I don't want this to happen. I wan't to first check all the values, from the table, and if NONE of them is AAA 111 to run the second action. Is there a way I can to that ? Thanks a lot!


Solution

  • You could do this using a Lua Table-as-Set.

    plates = {}
    
    function addToSet(set, key) --see the linked answer for more functions like this
        set[key] = true
    end
    
    function setContains(set, key)
        return set[key] ~= nil
    end
    
    function checkPlate(PLATE)
      if setContains(plates, PLATE) then
        print("One of the plates is", PLATE)
      else
        print("There is no plate", PLATE)
      end
    end
    
    addToSet(plates, "AAA 111")
    addToSet(plates, "AAA 123")
    
    local PLATE = "AAA 123"
    checkPlate(PLATE)
    
    PLATE = "AAA 456"
    checkPlate(PLATE)
    

    OUTPUT:

    One of the plates is    AAA 123
    There is no plate   AAA 456
    

    This is also much more efficient than looping, and if you wanted to change the plates table to include more information about plates, using plates as dictionary keys, i.e:

    plates = {
        ["AAA 123"] = {
              ["registered"] = {'1/2/3'}
        }
    }
    

    It would still work with minor modifications to the addToSet function.