I want to add … to a TextLabel in my game if the Text in it exceeds 7 characters.
I have tried using string.len, but knowing my knowledge, didn’t succeed. What I want to do is:
get the Player’s name, such as “OldBo5CoolGuy528”, and just change that to “OldBo5C…”, with succession. I have been thinking about this for around 15/30 minutes, still haven’t though of anything beneficial to use, only string.len, which I have no experience in. Here is what I got so far:
local reducingValue = string.len(Name) -- the thing im reducing
if Name >= 7 then
NewObj.Player.Text = Name -- this is where I want to change the player's name from OldBo5CoolGuy528 to OldBo5C...
else
NewObj.Player.Text = Name -- keep this as is i guess
end
string.sub stringstring.sub ( string s, int i = 1, int j = -1 )
Returns the substring of s that starts at i and continues until 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).
Please post more detailed answers - as it is, that’s a copy paste of the function definition for string.sub from the devhub.
A more complete answer:
You can easily achieve this using string.sub, like so:
local myName = "Catherine"
if myName:len() > 7 then
myName = myName:sub(1, 7) .. "..."
end
print(myName) --> Catheri...
By doing myName:sub(1, 7), you take the section of the name from the 1st character to the 7th character - that is, from C to i. So if we check if the name is longer than 7 characters, we can just take the part of the name from the 1st to 7th character, then add a ... onto the end!
Alright, now I need to do this with a number, fun!
I really hope I didn’t corrupt player’s data by doing this, at least I didn’t publish the update, though.
NewObj.Cash.Text = "$"..Cash
if NewObj.Cash.Text:len() > 7 then
Cash = Cash:sub(1, 7) .. "..."
NewObj.Cash.Text = "$"..Cash
else
NewObj.Cash.Text = "$"..Cash
end
That means the value of your Cash variable is nil rather than a number or string - if you’re using a different variable or other way of storing the cash, you can change the Cash at the end of the first line to whichever variable you’re storing the cash value in.
Otherwise, make sure your Cash value is a number and not nil
There is a TextTruncate property on TextLabel you could consider using instead. If you set it to AtEnd, it will automatically insert a ... when the text becomes too long to fit.
You should be careful using string.sub for this purpose, because it will easily break Unicode you pass into it. In addition, truncating based on the number of characters will have different results for different languages. For example:
lllllll
aaaaaaa
mmmmmmm
啊啊啊啊啊啊啊
are all 7 characters long but are visibly different lengths.