Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

String Manipulation: Why Isn't string.sub Working Correctly? [RE-POST, THREAD DELETED]

A thread was recently made about string.sub working incorrectly, but the question was deleted before I could answer. The problem was an easy one to make; the code looked similar to:

local s = "Hello world!"
print(s:sub(1, 5) == "ell") --> false -- why?

I'll post my answer to this question below for those who may come across a similar issue.

4 comments

1

?

0

There's nothing wrong with self answering a question because in the case that someone asked a question, received or didn't receive an answer, and deleted the question, doing this will help people in the future.

0

Also, anyone able to moderate, please vote to lock this so there won't be anymore spamming of question marks

0

Questions like these should be moved to Forums. Not here

2 answers

✓ Accepted answer

Your issue is in inclusiveness. The full syntax of string.sub is:

s:sub(int i, int j)/string.sub(string s, int i, [int] j) Return the substring of s that starts at i and ends at j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length).

i and j are inclusive; they are included in the substring:

local s = "Hello world!"
print(s:sub(2, 4)) --> ell -- e is the 2nd character, l is the 4th character.

In your script, you do not account for this inclusion, which is why you are receiving unexpected results.

3 comments

1

?

1

?

1

someone asked a question like this which i answered to see that the post was deleted. i didn't want to waste my answer ¯_(?)_/¯

You are assuming that the index of the substring begins at 0, which in fact in Lua, begins at 1!

local s = "Hello world!"

print(s:sub(1, 5)); 

would print Hello. Not ello which is what you are assuming right now. Many other languages's index begins at 0 which is why you are confusing yourself right now.

To fix your problem, simply start from 2.

local s = "Hello world!"

print(s:sub(2, 5) == "ello"); 

which would evaluate to true.

That is the real issue here. There really is nothing wrong with the syntax itself. It is simply a Logical Error.

2 comments

0

He was making a self answer...

0

He isn't supposed to be and he was not addressing the real issue. So I decided to answer it.

This discussion is preserved as it was. New answers, comments, and votes are closed.