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