lualua-tablegarrys-mod

Why do I get this "attempt to call a table value" when iterating through a table?


I'm trying to find the key associated with the value of a table in Garry's mod Lua, but I'm getting an error as though it's not a table.

This is part of a larger solution to a game crashing bug on someone else's code that I'm maintaining/fixing.

long story short, I need to get the number of a key based on what value it is. a simple, short code that has this issue:


function starttest()
     local tbl = {"a", "b", "c"}

     local printme = FindValueInTable(tbl, "c")

print(printme)

end

function FindValueInTable(table, value)
     for k, v in table do --errors on this line saying "attempt to call a table value"
          if v == value then
               return k
          end
     end
     return nil
end

I'm stumped on what to do here because table is literally a table, How can the for k,v in table really be failing?

The result I'm expecting is for it to return the numerical key that has the value in value. so if value == "c" and table[3] happens to have the value "c" then it should return 3 as a result.


Solution

  • You need to use for k, v in ipairs(table) do instead of for k, v in table do, as this form of the for loop expects an iterator after in, so tries to "call" your table variable, which leads to the error.

    As discussed in the comments, you may need to use pairs instead of ipairs if you have have non-numerical or non-sequential indices in the table.