Help with checking if a string is only spaces

Hello, I am currently trying too figure out how to prevent fully empty names for my save slot system.
Now I am stuck with how to detect if a message is only spaces.

Here is the code for the check so far. (I have removed most of the code since I would have too provide an entire place file of my full game)

local SlotName = “Slot Name Here”
if SlotName ~= “” then
print(SlotName)
end

1 Like

You will want

if not SlotName:match("^%s*$") then
    print(SlotName)
end

Since the ^ anchor matches at the beginning and the $ anchor at the end, and the * quantifier to match 0 or more occurrences of %s, which is a whitespace. This accounts for empty string too.

10 Likes

This information maybe helpful for tweaking performance based on the situation your using this for.

http://lua-users.org/wiki/StringTrim

Couldn’t you just check if SlotName:match("%S")? Parsing the entire string when you’re just checking if there’s one non-space character seems like overkill.

4 Likes

Unless the person wants to check for only one spaces, doing [^%s+$] would kind of be what I would do

%S with a capital s looks for a non-space character, not a space.

2 Likes