This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
nateracecar5's profile picture

Getting the value of a string in a table

Started by nateracecar5, 29 March 2014 - 08:37 PM
nateracecar5 #1
Posted 29 March 2014 - 09:39 PM
I'm kind of a noob in CC, but I know my way around most things. My question: How can I take a string, and find it in a table, then get the index of it?

For example:
I enter the text "Bob", which is in my table. It searches the table, and returns "5", which means table[5].

How would I do this? I know how to get the text of a value (name = table[5]), but not the other way around.
Edited on 29 March 2014 - 08:45 PM
Lyqyd #2
Posted 29 March 2014 - 09:47 PM
You simply iterate the table:


function find(tab, val)
  for k, v in pairs(tab) do
    if v == val then
	  return k
    end
  end
end
TheOddByte #3
Posted 29 March 2014 - 10:02 PM
You should go and check out these loops here http://www.lua.org/pil/4.3.4.html