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

How do I "collect" certain characters in a string? [closed]

Asked by 9 years ago

What I meant by how do I collect certain characters, what I meant was in a string variable, how do I collect the characters of a specified region in a string as a variable? For example, how do I collect the first two letters of a string, such as the "Ro" of "Roblox is the best online website ever!".

Locked by User#24403

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
19
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

A portion of a string is called a substring. You can get substrings using the string.sub function:

local text = "abcdefg"

local firstTwo = text:sub(1, 2)
-- ab

local nextTwo = string.sub(text, 3, 5)
-- cde

-- `text:sub(` and `string.sub(text,` act the same

string.sub has a few different ways to be used:

  • text:sub(start, stop)
    • start and stop are both inclusive
    • 1 is the first letter, 2 the second, etc
    • -1 is the last letter, -2 the second to last, etc
  • text:sub(start)
    • the same thing as text:sub(start, -1)
    • gets all of the string starting at start *If the range is empty (entirely before or entirely after the string, or with a stop before a start) you get an empty string
    • string.sub never returns nil and never errors if the parameters are of the right types

Examples:

print( string.sub( "abcdef", 2, 3) )
-- bc

print( string.sub("blah", 4) )
-- h

print( string.sub("waffle", 2, -2) )
-- affl

print( string.sub("cat", 2) )
-- at

print( string.sub("cat", 10) )
--

print( string.sub("cat", 3, 2) )
--

1 will include the first letter, 2 will include the second letter, etc.

If you give negative numbers to :sub, they count backwards -- -1 is the last letter, -2 is the second to last letter, etc. Thus ("waffle"):sub(2, -2) is "affl".

If you only give one number to :sub(x), then it acts like :sub(x, -1) -- from the xth character on. For example, ("cat"):sub(2) is "at".

1
local nextTwo = string.sub(text, 3, 5) -->cde, not def. Line 10 on the second script should have "print" instead of string.sub Validark 1580 — 9y
0
Corrected BlueTaslem 18071 — 9y
Ad