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

Find all letters in a word?

Started by ChiknNuggets, 21 September 2012 - 12:46 PM
ChiknNuggets #1
Posted 21 September 2012 - 02:46 PM
so what im trying to do is find the position of each of a certain letter in a word and then return it in a number, ive tryed so many different methods but it always seems to throw me an error or go into a infinite loop which is obviously not wanted, if anyone could help would be much appreciated
MysticT #2
Posted 21 September 2012 - 03:02 PM
I'm not sure of what you're trying to do, but I'm sure that you'll need the string library (take a look at the find and match methods).
ChiknNuggets #3
Posted 21 September 2012 - 03:11 PM
Ive allready looked through all that before i posted, for example ive got the word elephant and i want to find all of the letter 'e' through out the word so in this case its letter 1 and 3, so i want a function that returns the number of each of the 'e' in the word. i tryed string.find but it seems to only give me one of them so…
MysticT #4
Posted 21 September 2012 - 03:24 PM
Well, there might be some easier/better way, but this is what I came out with:

local function findAll(s, pattern, plain)
  local i = 1
  local result = {}
  while i < #s do
    local pos = string.find(s, pattern, i, plain)
    if not pos then
	  break
    end
    table.insert(result, pos)
    i = pos + 1
  end
  return result
end
It works like string.find but it returns a table with the starting positions of every match of the pattern.

So, you can use it like:

for _,i in ipairs(findAll("elephant", "e")) do
  print(i)
end
It will print 1 and 3.
ChiknNuggets #5
Posted 21 September 2012 - 03:39 PM
Ahh thank you, worked amazingly!