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

find a string's position in an array

Started by KingofGamesYami, 06 April 2014 - 01:18 PM
KingofGamesYami #1
Posted 06 April 2014 - 03:18 PM
Is it possible to find the position of a string (eg. "Bob") in an array (eg. {"Tom", "Bob", "Ron"})? If so, how would I do this?
Lets say we have this:
Array1 = {"Tom", "Bob", "Ron")
for i, #Array1 do –I do realize this is doing nothing but shifting stuff into a different array.
Name = Array1
end
Edited on 06 April 2014 - 01:21 PM
CometWolf #2
Posted 06 April 2014 - 03:20 PM
Im assuming you mean key when you say "position", so a pairs loop will do just fine.

for k,v in pairs({"Tom,"Bob","Ron"}) do
  if v == "Bob" then
    print(k) --k being the key that contains "Bob"
  end
end
KingofGamesYami #3
Posted 06 April 2014 - 03:22 PM
Im assuming you mean key when you say "position", so a pairs loop will do just fine.

for k,v in pairs({"Tom,"Bob","Ron"}) do
  if v == "Bob" then
	print(k) --k being the key that contains "Bob"
  end
end
so k will be 2 in this case?
Bomb Bloke #4
Posted 06 April 2014 - 03:24 PM
The variable "k" will cycle through the values of 1, 2 and 3; assuming an extra quotation mark, yes, 2 should be printed.
Edited on 06 April 2014 - 01:26 PM
CometWolf #5
Posted 06 April 2014 - 03:33 PM

"Tom,"Bob"
hehe, my bad.

I assume you know what pairs does? When used in a for loop, we get each key and it's value, from the table specified. One pair for every loop. Now what im doing is comparing the value to the value you wish to find the key of. If they match, we've found the key the value is held in.
Edited on 06 April 2014 - 01:33 PM
KingofGamesYami #6
Posted 06 April 2014 - 03:55 PM
Yes, I figured that out now CometWolf. Thanks, but now I am having trouble with this part of my program:
for i = 1, #Args/2, 2 do
User[i] = Args[i]
local f = i+1
uPass[i] = Args[f]
end
This is giving me this error:
index expected, got nil
How do I fix it? I am trying to make a program to check usernames against passwords if that helps.
*derp* fixed this.
Edited on 06 April 2014 - 02:45 PM