How to get first character of string in Lua

luastring

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.

Best 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 strings:

> string.sub("", 1, 1) -- => ""