How to detect if a specific value is in a table

Hello! I’m making a chess engine and I’m storing piece location data in a table so that an algorithm can find valid spaces for each piece. Here’s a visualisation of what I mean.

--Table of all opponent piece's locations (in chess coordinates)
local opponentPiecesLocation = {a3, c4, g7, f2}
local allyPiecesLocation = {g8, f7, a6, c8}

local function validSpaces()
    --Code that will compare the selected piece to other piece's location
end

How can I make it so that the function will run through a location table looking for a specific location? I already have a somewhat working version that seems to be inefficient. Here’s my version:

local function validSpaces() -- Example of white pawn at a2
    local canMove1Space = true
    for _, pieceLocation in pairs(opponentPiecesLocation) do
         if pieceLocation == "a3" then --a3 is an example of a valid space the pawn could normaly move to
              canMove1Space = false
         end
    end
    if canMove1Space == true then
         --Code that would apply everything needed to a valid square
    end
end

How can I more effectively check to see if a specific string or value is part of a table?

Use table.find(t, searchFor)
The parameters are the table and the value you are looking for.
It will return the index or nil.

1 Like