Is there an easier (more efficient) way to iterate through table values first, then indexes in Lua?
Question
Currently, I have the following code:
runtable={}
for _,v in pairs(akeys) do
if string.match(string.upper(v),string.upper(area)) then
table.insert(runtable,area)
break
end
end
if #runtable = 0 then
for i,_ in pairs(akeys) do
if string.match(string.upper(i),string.upper(area)) then
table.insert(runttable,area)
end
end
end
The purpose of this script is to go through all the values first and see if the area variable matches the value. If it does, it's going to be a one-time thing, so it'll stop the loop and continue on with the rest of the script (beyond the if #runtable = 0
). If it fails to find anything in the values, then it goes through the list again, but this time comparing indices to the area, and each time it finds a match (partial or full), it'll add it to the runtable.
Is there a more efficient way to do this? Or is this the best possible way to run this, regardless of how cluttered it may look?
Solution
local rt1, rt2 = {}, {}
for i,v in pairs(akeys) do
if string.match(string.upper(v),string.upper(area)) then
table.insert(rt1,area)
break
end
if string.match(string.upper(i),string.upper(area)) then
table.insert(rt2,area)
end
end
local runtable = #rt1 > 0 and rt1 or rt2
Not a huge saving in terms of ugliness, but it saves a second loop. Sadly there's no kind of magic I'm aware of that'll make this much prettier, but that's one of the tradeoffs of having a language as compact as Lua.