Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by
BenSBk 781 Moderation Voter
6 years ago

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.

1
? User#5423 17 — 6y
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. SteamG00B 1633 — 6y
0
Also, anyone able to moderate, please vote to lock this so there won't be anymore spamming of question marks SteamG00B 1633 — 6y
0
Questions like these should be moved to Forums. Not here Zafirua 1348 — 6y

Closed as off-topic by Zafirua and yHasteeD

This question has been closed by our community as being off-topic from ROBLOX Lua Scripting.

Why was this question closed?

2 answers

Log in to vote
1
Answered by
BenSBk 781 Moderation Voter
6 years ago

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.

1
? User#5423 17 — 6y
1
? GoldAngelInDisguise 297 — 6y
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 ¯\_(?)_/¯ BenSBk 781 — 6y
Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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.

0
He was making a self answer... SteamG00B 1633 — 6y
0
He isn't supposed to be and he was not addressing the real issue. So I decided to answer it. AbstractionsReality 98 — 6y