-2

even if i use gsub to change white space to _ the if statement still get error attempt to index a nil value i wonder whats the problem.i cant use pairs since that's the instruction my teacher gave.

this is the code sorry in advance im a beginner.

text = "ib c e d f"
text = string.lower(text)
b = text:gsub("%s+", "_")
for k=1, #b do

  if  not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then
      if a[i][2] == string.sub(b, k,k) then
        print(yes)
      end
  end

1 Answers1

0

There are some syntax error on your code snippet which causes the error you mentioned. The gsub function is actually working just fine.

text = "ib c e d f"
text = string.lower(text)
b = text:gsub("%s+", "_") --> this gsub is working just fine
for k=1, #b do

  if not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then
      if a[i][2] == string.sub(b, k,k) then --> you didn't assign any table called "a" before --> attempting to index a nil value
        print(yes)
      end
  --> haven't close the "if not string.sub" function with an end
end --> this is the end for the loop "for k"

I am just wildly guessing that you want to compare the result string with the original string. Since your question is so enigmatic, I could only offer you this code below for your reference:

text = "ab c  d e f  "
text = string.lower(text)

output = text:gsub("%s", "_")

for k = 1, #output do
  local char = string.sub(output, k, k)
  local originalChar = string.sub(text, k, k)
  if (originalChar ~= " ") and (char == originalChar) then
    print(char .. " --> OK")
  end
end

The gsub pattern uses %s instead of %s+ so that each space is converted to an underscore to allow simple unit test (char by char comparison). Code snippet available here.

Rheza
  • 11
  • 4