Lua - 列表搜尋



當我們想要迭代一個專案以查詢特定值時,我們通常使用 for 迴圈。這始終是最直觀的方法,也是推薦的方法。

讓我們來看一個例子,其中我們在 Lua 中儲存了一個水果列表,然後我們想要檢查特定水果是否存在於其中。為此,最原生且高效的方法是迭代列表元素並將其中的每個元素與我們正在查詢的元素進行比較。這種技術或方法也稱為線性搜尋。

示例

考慮以下示例:

main.lua

local fruits = { "apple", "orange", "pear", "banana" }
for _, fruit in pairs(fruits) 
do
   if fruit == "pear" then
   do 
	  print("We Found it!")
      break
   end
      else print("Oh no, keep traversing!")
   end
end

輸出

Oh no, keep traversing!
Oh no, keep traversing!
We Found it!

雖然上述方法執行良好,但建議使用集合而不是遍歷列表。

示例

以下示例使用我們可以使用的**集合**方法,它執行良好。考慮以下示例:

main.lua

function Set (list)
   local set = {}
   for _, l in ipairs(list)
   do
      set[l] = true
   end
   return set
end

local fruits = Set { "apple", "orange", "pear", "banana" }

   if fruits["pear"] then
   do
      print("Present in the set")
   end
end

輸出

Present in the set
廣告
© . All rights reserved.