Check if string contains square bracket [

I tried

  local str = "[string]"
  if str:match("[") then print("found") end
  -- also tried string.find() 

image

the only other way I can think of is to use an iterator function

  local str = "[string]"
  for char in  str:gmatch(".") do
      if char == "[" then print("found") end 
  end

is there a way this can be done with fewer lines of code?

1 Like

Perhaps try:
if string.find(myString, tostring("[")) then ... end

2 Likes

Try: not not str:find('%[') (or if str:find('%[') then)
%[ is a literal ‘[’ for lua string patterns.

Nope, it’s already a string so it’ returns the same value.

print( string.find('[', tostring("[")))

00.35.39,624 - print( string.find(‘[’, tostring(“[”))):1: malformed pattern (missing ‘]’)
00.35.39,625 - Stack Begin
00.35.39,625 - Script ‘print( string.find(’[‘, tostring(“[”)))’, Line 1
00.35.39,625 - Stack End

2 Likes

There are a couple ways to do this; Blockzez’s works pretty well, although you can also use str:find('[', 1, true).

string.find(str, pattern, start, plain) is how string.find is defined, so if you set the plain flag to true it will instead find the literal pattern you gave it instead of using it as a Lua pattern. This method also tends to be faster (although not noticeable unless you abuse find).

4 Likes

Try:
if string.find(myString, "\91") then

\91 is the bytecode for [, i think.

Edit: Nevermind, doesn’t work.

1 Like