Get the first character of a string in lua

Assuming I have a line in lua:

> s = "abc123"

I want to get s1which is only the first character s or empty if sempty.

I tried using

> s1 = s[1]

and

> s1 = s[0]

How can I get the first character without using external Lua libraries

but both return only nil.

+4
source share
1 answer

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 lines:

> string.sub("", 1, 1) -- => ""
+5
source

Source: https://habr.com/ru/post/1671711/


All Articles