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.
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.
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.
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?