# Return table value based on a primitive “priority queue”

I have 2 function in Lua, one to look if a key is present inside a provided table and if true then return the value, else return false. This lookup function is called by another function with a "priority queue". It is not a queue per definition but I don't have a better name for it.

function inTable(tbl, item)
for key, value in pairs(tbl) do
if key == item then
return value
end
end
return false
end

function ReturnString()
local valid = {}

valid[22] = "string1"
valid[13] = "string2"
valid[25] = "string3"
...

if inTable(valid, "22") then
return inTable(valid, "22")
elseif inTable(valid, "13") then
return inTable(valid, "13")
elseif inTable(valid, "25") then
return inTable(valid, "25")
else
end
end


Usage:

print(ReturnString())


valid is filled with a lot of different key-value pairs, unordered. My goal is to return the value based on a priority I determine using my nested if-elseif-else construct. If there is a key 22 then return string1, else check if there is a key 13 and so on. I know that there are more real implementation of a priority queue like this but I prefer something simple. What improvement can I do without implementing a complex priority queue?

• There is a missing " in your code. – Marc-Andre May 8 '15 at 14:40

welcome to Code Review.

I don't understand the purpose of your inTable() function. Lua tables already support immediate lookup of entries in them, just by using square brackets. See the Lua documentation for tables.

  if inTable(valid, "22") then
return inTable(valid, "22")
elseif inTable(valid, "13") then
return inTable(valid, "13")
elseif inTable(valid, "25") then
return inTable(valid, "25)


is really equivalent to:

if valid[22] then
return valid[22]
elseif valid[13] then
return valid[13]
elseif valid[25] then
return valid[25]


Can we do better than this? Sure! Lua has the or operator which returns the first true value. (See documentation)

return valid[22] or valid[13] or valid[25]


Can we do even better? Definitely. Make up another table with the indexes in order, then iterate over it, returning the first true value.

local priority = {22, 13, 25}
local i
for i in priority do
if valid[i] return valid[i]
end

• I got a attempt to call table value error. when using your for loop. local priority = {22, 13, 25} and for i in priority do if valid[priority] then return valid[priority] end end – sceiler May 8 '15 at 15:12
• nevermind I could fix it. thanks a lot for i = 1, #priority, 1 do if valid[tostring(priority[i])] then return valid[tostring(priority[i])] end end – sceiler May 8 '15 at 15:32
• or just put the strings in the priority table anyway; local priority={"22","13","25"} – Snowbody May 8 '15 at 15:49
• also see my fix; i put the wrong thing inside the square brackets – Snowbody May 8 '15 at 15:50