metamethods를 사용하여 할 수있는 또 다른 방법이 있습니다. 는 [당신이 값을 제거 할 수 있도록 편집도]
t = {} -- Create your table, can be called anything
t.r_index = {} -- Holds the number value, i.e. t[1] = 'Foo'
t.r_table = {} -- Holds the string value, i.e. t['Foo'] = 1
mt = {} -- Create the metatable
mt.__newindex = function (self, key, value) -- For creating the new indexes
if value == nil then -- If you're trying to delete an entry then
if tonumber(key) then -- Check if you are giving a numerical index
local i_value = self.r_index[key] -- get the corrosponding string index
self.r_index[key] = nil -- Delete
self.r_table[i_value] = nil
else -- Otherwise do the same as above, but for a given string index
local t_value = self.r_table[key]
self.r_index[t_value] = nil
self.r_table[key] = nil
end
else
table.insert(self.r_index, tonumber(key), value) -- For t[1] = 'Foo'
self.r_table[value] = key -- For t['Foo'] = 1
end
end
mt.__index = function (self, key) -- Gives you the values back when you index them
if tonumber(key) then
return (self.r_index[key]) -- For For t[1] = 'Foo'
else
return (self.r_table[key]) -- For t['Foo'] = 1
end
end
setmetatable(t, mt) -- Creates the metatable
t[1] = "Rock1" -- Set the values
t[2] = "Rock2"
print(t[1], t[2]) -- And *should* proove that it works
print(t['Rock1'], t['Rock2'])
t[1] = nil
print(t[1], t[2]) -- And *should* proove that it works
print(t['Rock1'], t['Rock2'])
당신이 t
값을 복사하고 당신과 함께 걸릴 수있는 더 다양한입니다; 그것은 또한 대부분의 시간 변수 중 하나만 가지고 놀아야 만한다는 것을 의미합니다. 잘못된 일에 액세스하려는 가능성을 줄여야합니다.
function touchListener(event)
local rock = event.target
local rockIndex = rock.index
-- ...
end
그것을 : 당신이 터치 리스너 방법을 사용하는 경우
RockTable = {}
for i=1,20 do
local rock
-- do your thing that generates a new 'rock' object
rock.index = #RockTable + 1
RockTable[rock.index] = rock
end
, 당신은 바위 이런 식으로 검색 할 수 있습니다
여기에 쓰여진 것처럼'Rocks'와'RocksB'는 동일한 배열입니다. 'RocksB'에서 인덱스와 값을 역전 시키길 원했을 것입니다. 아마도 {{a rock = 1, ...}이라고 생각했을 것입니다. – RBerteig
@RBerteig 오, 예; 내가 그걸 믿을 수 없어. 그것을 지적 주셔서 감사합니다. –