Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first character of string in Lua?

Tags:

string

lua

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.

like image 981
Uli Köhler Avatar asked Mar 07 '17 14:03

Uli Köhler


People also ask

How do you get the first character of a string?

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.

Can you index strings in Lua?

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.

What is GSUB in Lua?

Overview. In Lua, the built-in string. gsub string manipulation method is used to substitute a substring with another substring value. The string.


2 Answers

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) -- => ""
like image 57
Uli Köhler Avatar answered Sep 18 '22 14:09

Uli Köhler


You can also use this shorter variant:

s:sub(1, 1)
like image 20
Termininja Avatar answered Sep 20 '22 14:09

Termininja