Assuming I have a string in lua:
> s = "abc123"
I want to get s1
which is only the first character of s, or empty if s
is empty.
I've tried using
> s1 = s[1]
and
> s1 = s[0]
How can I get the first character without using external Lua libraries
but both only return nil
.
To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str. length - 1] returns the last character of the string.
Note that there is no individual character indexing on strings, just like in Lua, so you can't use the indexing operator [] to read a single character. Instead, you need to get a substring to get a string of length 1 if you want individual characters (using sub in pico8, string.
Overview. In Lua, the built-in string. gsub string manipulation method is used to substitute a substring with another substring value. The string.
You can use string.sub()
to get a substring of length 1:
> s = "abc123"
> string.sub(s, 1, 1)
a
This also works for empty strings:
> string.sub("", 1, 1) -- => ""
You can also use this shorter variant:
s:sub(1, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With