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

How to 'slice' a string?

I know in python you can use the index of characters to 'slice' your string using square brackets, eg:

string = "This is my string" print (string[0:5])

Which would print 'This'.

I've tried doing this with Lua in the same way:

local my_string = "This is a string"
print(my_string[:1])

Though I just get an error "unexpected symbol near ':'"

Any guidance on this would be appreciated =)

1 comment

0

That would be acceptable in Python. However, as Blue has shown, getting different ranges of text is a bit different.

1 answer

✓ Accepted answer

Strings don't support [] in Lua (which is sort of a shame). Lua also doesn't support indexing by a "range" like Python.

For strings, you use string.sub to get a substring.

local str = "abcdef"

-- everything from 3rd character on
print(str:sub(3) ) -- cdef

-- last three characters:
print(str:sub(-3) ) -- def

-- third to fifth characters:
print(str:sub(3, 5)) -- cde

Note that string.sub(str, ...) and str:sub(...) are the same thing. You can use either.

1 comment

0

Thank you =-)

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