Search code examples
stringlua

How to get the first character of a string in Lua?


Given a string s in Lua:

s = "abc123"

If the string is non-empty, I want to store the first character of this string in a variable s1, else store nothing.

I've tried the following, but both return nil:

s1 = s[1]
s1 = s[0]

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


Solution

  • 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) -- => ""