Michael Plotke
Michael Plotke

Reputation: 1001

Replace String Characters by Index in Lua

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?

Upvotes: 4

Views: 1961

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23737

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

Upvotes: 3

Related Questions