-1

I'm currently using equations to enter items into a table. I then want to check if the items in v are the same when string.reverse and if so, print that out.

table.insert (t,#t+1,z)
  for k,v in ipairs (t) do
    if string.reverse(v) == v then
      print (v)
    end
  end
end

Unfortunately, all I get back are errors with if string.reverse(v) == v then print (v) end. I've switched the order of my reverse statement and even changed it to:

table.insert (t,#t+1,z)
  for k,v in ipairs (t) do
      print (string.reverse(v))
  end
end

The code above will successfully print every item in my table to the screen, which is not what I want. I would like it to check each item, preferably before it places that item into my table, and if true, places it into my t{}.

What is the proper way to check whether the items in a table spell the same when reversed and print that to screen? I continually receive the following error:

bad argument #1 to 'reverse' (string expected, got nil)

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Pwrcdr87
  • 935
  • 3
  • 16
  • 36

1 Answers1

0

The error you are getting bad argument #1 to 'reverse' (string expected, got nil) does not make sense to me since it means that v is nil, but since v is an element in your table, it can't be nil, something else is going on. However, to "check each item, preferably before it places that item into my table" you co do this:

function insertIfSymmetric(word, tbl)
    if string.reverse(word) == word then
        tbl[#tbl+1] = word
    end
end

Then

> t={}
> insertIfSymmetric("hi", t)
> for k,v in ipairs(t) do print(k,v) end
> insertIfSymmetric("hih", t)
> for k,v in ipairs(t) do print(k,v) end
1       hih
Oliver
  • 27,510
  • 9
  • 72
  • 103