Table.remove workaround in lua (mudlet :)

by Unknown

Back to Chronicles of the Basin.

Unknown2010-09-15 00:20:45
So if you do table.remove 2, in a table with 3 indexes (1 - rat, 2 - mouse and 3 - squirrel) , you'll have 2 left. 1- rat and 3- squirrel. But table.remove will change 3- squirrel into 2- squirrel for you.

Now let's say I don't want to remove by the index number, but instead by the word "mouse", and have the table still re-order itself. How can I do this? Alger explained it to me but I closed what he pasted to me by mistake sad.gif

Edit: Sorry about wrong section.
Unknown2010-09-15 03:45:02
mytable = {"cat", "fish", "rat"}

function findmything(what)
count = 0
for i, v in ipairs(mytable) do
count = count + 1
if v == what then break end
end

return count
end

print("Rat was at: "..findmything("rat"))
print("fish was at: "..findmything("fish"))


In case anyone else was wondering!
Unknown2010-09-20 20:35:07
You don't even need the count. You can just return i, since that's the position in the table.

CODE
function findmything(what)
  for i,v in ipairs(mytable) do
    if v == what then
      return i
    end
  end
end
Vadi2010-09-20 20:53:57
You can improve that with:

CODE
function findmything(what)
  for i,v in ipairs(mytable) do
    if v == what then
      return i
    end
  end

  return 0
end


as well, so your print statements don't break.
Unknown2010-09-21 00:41:27
Ah, good point.
Unknown2010-09-22 03:18:06
Ladies, Gentlemen, the Mechanics Corner is vvv thataway.