1

I have some strings representing table "paths" that can be used to iterate to a value within a table, such as:

"table.subTable[2].anotherTable"

"table.subTable.otherTable.anotherTable"

"table.subTable.otherTable[3]"

[2] and [3] are indexes which might point to another table. I need to write a function that cuts off the last key/index so that the "string path" points to the previous (or "parent") table.

For example, the above strings should turn into:

"table.subTable[2]"

"table.subTable.otherTable"

"table.subTable.otherTable"

I thought this could be done by finding the last [ or . characters in the string and splitting it by using string.sub.

There might be many other ways to achieve this, such as gmatch, but I'm not sure how. Thank you in advance!

1 Answer 1

1

If . and [ only occur in indexing syntax in the strings you are working with, you can do path:match('(.+)[.[]'). [.[] is visually confusing, but it is a set containing . and [. You can escape [ with a percent ([.%[]), but it isn't necessary.

If one of the table indices is a string that contains . or [, like table['sub.table'][3], this solution will fail. In that case, the solution would be more complicated. You could use LPeg, or replace . or [ within strings with some other sequence of characters before doing the string matching and then restore the . or [ after the string matching.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! The table indices will not contain . or [ so that will work. Not exactly sure why [[.] is fine but switching the characters around requires a % like [.^[].
Oh, right, the [ doesn't have to be escaped (though the pattern is visually confusing). I've edited my post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.