Jest to funkcja swiss-armyknife można użyć:
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
Można go używać do sprawdzenia, czy istnieje wartość:
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
Można używać go znaleźć klucz:
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
Mam nadzieję, że parametr recursive
mówi sam za siebie.
Parametr metatables
umożliwia także wyszukiwanie metatabeli.
Parametr keys
powoduje, że funkcja szuka kluczy na liście. Oczywiście byłoby to bezużyteczne w Lua (można po prostu zrobić fruits[key]
), ale wraz z recursive
i metatables
, staje się przydatny.
Parametr returnBool
jest bezpieczne-guard, gdy masz tabele, które mają false
jako klucz w tabeli (Tak, to możliwe: fruits = {false="apple"}
)
Jest to najlepszy sposób, aby zestaw (w czystej matematycznej sens) rzeczy w Lua. Brawo! Jednak ponieważ nie ma koncepcji zamówienia, nie musi odpowiadać na ogólne pytanie "Wyszukaj przedmiot na liście Lua?" jeśli kolejność list ma znaczenie. – Mark
To jest o wiele bardziej eleganckie. Po prostu użył go do stworzenia tabeli, która wyglądała jak '{thingIAmLookingFor: true, secondThingIAmLookingFor: true}' –
Nie wydaje się działać z liczbami. – CalculatorFeline