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

How to 'slice' a string?

Asked by
PredNova 130
9 years ago

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 =)

0
That would be acceptable in Python. However, as Blue has shown, getting different ranges of text is a bit different. DigitalVeer 1473 — 9y

1 answer

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

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.

0
Thank you =-) PredNova 130 — 9y
Ad

Answer this question