문제
다음과 같은 항목 목록이있는 경우 :
local items = { "apple", "orange", "pear", "banana" }
이 목록에 "오렌지"가 있는지 어떻게 확인합니까?
파이썬에서 나는 할 수있다 :
if "orange" in items:
# do something
LUA에 해당하는 것이 있습니까?
해결책
세트와 같은 것을 사용할 수 있습니다 LUA의 프로그래밍:
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
그런 다음 목록을 세트에 넣고 멤버십을 테스트 할 수 있습니다.
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
또는 목록을 직접 반복 할 수 있습니다.
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
다른 팁
대신 다음 표현을 사용하십시오.
local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
...
end
당신은 하나의 데이터 구조 만있는 LUA의 단점 중 하나를 직접보고 있습니다. LUA를 고수하면 일을 좋아하는 방식으로 테이블을 조작하는 기능 라이브러리가 점차 축적됩니다. 내 라이브러리에는 목록으로 설정된 변환 및 고차원 목록 검색 기능이 포함되어 있습니다.
function table.set(t) -- set of list
local u = { }
for _, v in ipairs(t) do u[v] = true end
return u
end
function table.find(f, l) -- find element v of l satisfying f(v)
for _, v in ipairs(l) do
if f(v) then
return v
end
end
return nil
end
LUA 테이블은 목록이 아닌 Python 사전의 유사체입니다. 당신이 만든 테이블은 본질적으로 1 기반 인덱스 된 문자열 배열입니다. 표준 검색 알고리즘을 사용하여 값이 배열에 있는지 확인하십시오. 또 다른 접근법은 Jon Ericson의 게시물 세트 구현에 표시된 대신 값을 테이블 키로 저장하는 것입니다.
function valid(data, array)
local valid = {}
for i = 1, #array do
valid[array[i]] = true
end
if valid[data] then
return false
else
return true
end
end
데이터가 배열에 있는지 확인하는 데 사용하는 기능은 다음과 같습니다.
중족 가능한 솔루션 ...
local function preparetable(t)
setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end
local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)
if workingtable[456] then
...
end
이것은 당신이 사용할 수있는 스위스-아미 나이프 기능입니다.
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
값이 존재하는지 확인하기 위해 사용하여 다음을 수행 할 수 있습니다.
local myFruit = "apple"
if (table.find({"apple", "pear", "berry"}, myFruit)) then
print(table.find({"apple", "pear", "berry"}, myFruit)) -- 1
키를 찾는 데 사용할 수 있습니다.
local fruits = {
apple = {color="red"},
pear = {color="green"},
}
local myFruit = fruits.apple
local fruitName = table.find(fruits, myFruit)
print(fruitName) -- "apple"
나는 recursive
매개 변수는 자체적으로 말합니다.
그만큼 metatables
매개 변수를 사용하면 메타 타블도 검색 할 수 있습니다.
그만큼 keys
매개 변수는 함수가 목록에서 키를 찾게 만듭니다. 물론 Lua에서는 쓸모가 없습니다 (당신은 그냥 할 수 있습니다. fruits[key]
) 그러나 함께 recursive
그리고 metatables
, 그것은 편리해집니다.
그만큼 returnBool
매개 변수는 테이블이있는 경우 안전한 가드입니다. false
테이블의 키로 (예, 가능합니다 : fruits = {false="apple"}
)