在許多數據結構中,返回值是一個常見的需求。本文將涵蓋使用 pairs() 或 ipairs() 搜尋表格的一半元素,例如鍵或值,以找出並返回另一半。
這個例子使用了一個列出等待修理的船隻的數組。使用 ipairs() 來返回船隻的排隊位置。
local shipToFind = "Void Racer"
-- 等待修理的船隻
local waitingShips = {"Battle Sun", "Void Racer", "The Big Slow"}
-- 獲取排隊位置
local function getPlaceInLine(shipName)
for placeInLine, ship in ipairs(waitingShips) do
if ship == shipName then
return placeInLine
end
end
end
--打印排隊位置
local placeInLine = getPlaceInLine(shipToFind)
print("你的排隊位置是 " .. placeInLine)
字典搜尋範例
你是否曾經在家中逐個房間尋找失蹤的寵物?自己編寫一個函數,搜尋名為 house 的字典,以查看哪個房間藏著失蹤的小狗。
複製下面的字典作為房子。
local house = {kitchen = "一堆雜物",livingRoom = "小貓",bedroom1 = "沒有人在那裡",bedroom2 = "小狗",}創建一個名為 findPet() 的新函數來搜尋字典。包含要搜尋的字典和要搜尋的值的參數。
使用 pairs() 遍歷字典。在檢查下面的解決方案之前,嘗試自己編寫代碼。
local function findPet(whereToSearch, searchFor)for place, value in pairs(whereToSearch) doendend當 for 循環遍歷字典時,使用 return 返回找到寵物的房間。
local function findPet(whereToSearch, searchFor)for place, value in pairs(whereToSearch) doif value == searchFor thenreturn placeendendend