How can I irritate through a table for a specific value?

Viewed 49

For example I have the following table:

Vehiclecache[1]='00000028376'
Vehiclecache[2]='00000036357'
Vehiclecache[3]='00000067453'

Each table has values of a vehicle Model Plate Color Etc..

I have a vehicle with plate '573D86' How can I grab the key for this value to use it like this Vehiclecache[Key]

1 Answers

is this what you're looking for?

-- vehicle table
vehicle_cache = {}
vehicle_cache[1] = {
    name = "car_1",
    plate = "BD51 HYU",
    color = { 1, 1, 1 }
}

vehicle_cache[2] = {
    name = "car_2",
    plate = "NU71 DHA",
    color = { 1, 1, 1 }
}

-- function to find the vehicle via plate
local function find_from_plate(plate)
    local vehicle = nil
    
    for _, veh in ipairs(vehicle_cache) do
        if veh.plate == plate then
            vehicle = veh
            break
        end
    end
    
    return vehicle
end

-- find a vehicle and print the name
local vehicle = find_from_plate("NU71 DHA")
if vehicle then
    print("vehicle: " .. vehicle.name) 
end
Related