Esta es una función suizo-armyknife puede utilizar:
function table.find(t, val, recursive, metatables, keys, returnBool)
if (type(t) ~= "table") then
return nil
end
local checked = {}
local _findInTable
local _checkValue
_checkValue = function(v)
if (not checked[v]) then
if (v == val) then
return v
end
if (recursive and type(v) == "table") then
local r = _findInTable(v)
if (r ~= nil) then
return r
end
end
if (metatables) then
local r = _checkValue(getmetatable(v))
if (r ~= nil) then
return r
end
end
checked[v] = true
end
return nil
end
_findInTable = function(t)
for k,v in pairs(t) do
local r = _checkValue(t, v)
if (r ~= nil) then
return r
end
if (keys) then
r = _checkValue(t, k)
if (r ~= nil) then
return r
end
end
end
return nil
end
local r = _findInTable(t)
if (returnBool) then
return r ~= nil
end
return r
end
Usted puede utilizarlo para comprobar si un valor existe:
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
Se puede utilizar para encontrar la clave:
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
Espero que el parámetro recursive
hable por sí mismo.
El parámetro metatables
también le permite buscar metatablas.
El parámetro keys
hace que la función busque las teclas en la lista. Por supuesto, eso sería inútil en Lua (puede simplemente hacer fruits[key]
), pero junto con recursive
y metatables
, resulta útil.
El parámetro returnBool
es una salvaguardia para cuando se tiene tablas que tienen false
como una clave en una tabla (Sí es posible: fruits = {false="apple"}
)
Esta es la mejor manera de hacer un conjunto (en la matemática pura sentido) de las cosas en Lua. ¡Bravo! Sin embargo, dado que no tiene un concepto de orden, no responde necesariamente a la pregunta general de "¿Buscar un elemento en una lista de Lua?" si el orden de la lista importa – Mark
Esto se siente mucho más elegante. Solo lo usé para crear una tabla que parecía '{thingIAmLookingFor: true, secondThingIAmLookingFor: true}' –
Parece que no funciona con números. – CalculatorFeline