2
votes

If you've every played hangman, you will readily understand what I'm trying to accomplish. All I want is to replace characters at certain indices with other characters. Here's what I'm currently doing:

word = getwordoflength(10)
found = string.rep("_", 10)

while found ~= word do

  char = getcharfromuser()

  temp = ""
  for i = 1, 10 do
    if word:sub(i, i) == char then
      temp = temp..char
    else
      temp = temp..found:sub(i, i)
    end
  end
  found = temp
end

Now, to me this seems inordinately stupid and inefficient, but maybe there is no better way. Bottom line, what's the 'right' way to do this?

1

1 Answers

2
votes
while found ~= word do
   local char = getcharfromuser()
   for i in word:gmatch('()'..char) do
      found = found:sub(1,i-1)..char..found:sub(i+1)
   end
end

One more way:

while found ~= word do
   local char = getcharfromuser()
   for i in word:gmatch('()'..char) do
      found = found:gsub('().', {[i]=char})
   end
end