This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
RunasSudo-AWOLindefinitely's profile picture

[Resolved] [LUA] string.find() being weird?

Started by RunasSudo-AWOLindefinitely, 22 December 2012 - 04:48 PM
RunasSudo-AWOLindefinitely #1
Posted 22 December 2012 - 05:48 PM
EDIT: nvm, I solved it (http://computercraft...tring_%28API%29), "calling string.find on a string returned by string.sub will return the index of the character in the original string". Please close this thread.

I'm trying to make a program with ComputerCraft 1.33 which receives data from rednet and processes it. The test packet I am using is

BALANCE,1234567890,012345

The first part of the parsing works correctly:

lua> message = "BALANCE,1234567890,012345"
lua> comma = string.find(message, ",")
lua> data = string.sub(message, comma + 1)
lua> data
1234567890,012345

However, the second part doesn't work properly:

lua> comma2 = string.find(data, ",")
lua> comma2
19

As you can see, string.find is reporting that there is a comma in "1234567890,012345" at the 19th character, which doesn't exist - the length of the string is only 17.
If I do this, however, string.find works properly:

lua> data = "1234567890,012345"
lua> comma2 = string.find(data, ",")
lua> comma2
11

What's going on?!!
ChunLing #2
Posted 22 December 2012 - 06:13 PM
Beats the hell out of me. To top it off, if you kept the data produced by message:sub(comma), you'd see that Lua finds data == "1234567890,012345" is true. Length returns right and all.

It must be that string.sub returns a reindexed string rather than a fresh string. You should get around this by using gmatch instead.