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:
1 | local my_string = "This is a string" |
2 | print (my_string [ : 1 ] ) |
Though I just get an error "unexpected symbol near ':'"
Any guidance on this would be appreciated =)
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.
01 | local str = "abcdef" |
02 |
03 | -- everything from 3rd character on |
04 | print (str:sub( 3 ) ) -- cdef |
05 |
06 | -- last three characters: |
07 | print (str:sub(- 3 ) ) -- def |
08 |
09 | -- third to fifth characters: |
10 | print (str:sub( 3 , 5 )) -- cde |
Note that string.sub(str, ...)
and str:sub(...)
are the same thing. You can use either.