ratchet600
ratchet600

Reputation: 79

lua string.find not recognising substring

I am using LUA as part of a minecraft mod - I am not sure how much that affects things - see openComputers.

The code attempts to match a given string to one obtained by iterating over a series of slots containing items which have names.

The chunks of code that are important are:

    term.write("enter name")
    name=term.read()

returns a string e.g. "Forest" without the quotation marks. I have also checked the datatype.

Then later the code parses an inventory of items looking for one with "Forest" in its name. The first line for what it's worth is somewhat specific to the game but the output should render that unimportant.

    item = storage.getStackInSlot(sides.top,i)

this returns a bunch of stuff but is then refined with:

    item_name = item.label

which returns "Bee Sample - Species: Forest" which I have also checked is definitely a string.

The code then returns nil for the line where the match/find should return something != nil. I even print the two strings before the string.find operation.

    match = string.match(item_name, name, 1, true)
    print(match)

returns nil.

I have no clue why this would return false. I have tested the match and find functionality separately in interpreter with stuff like:

    a=bic
    b=ambico
    string.find(b,a)

and it was fine.

Sorry if this is super obvious and many thanks

Upvotes: 3

Views: 1664

Answers (2)

ratchet600
ratchet600

Reputation: 79

I have found a solution, Using string.gsub with the ascii code instead of the character itself solves the problem. For those who encounter the same problem:

newstring = string.gsub(string, "[\10]", "")

This removes the line feed and allows string matching henceforth.

Upvotes: 1

Norman Ramsey
Norman Ramsey

Reputation: 202725

Try stripping all trailing whitespace off the read name, as follows:

name = term.read():gsub('%s+$', '')

Upvotes: 1

Related Questions