Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: Finding a token in a delimited string

Tags:

string

lua

I have a string with a set of delimited tokens that looks something like this:

local str = "foo;bar;baz"

I'd like to be able to accurately tell if a given token is in this string or not:

in_str("foo", str) -- true
in_str("bar", str) -- true
in_str("baz", str) -- true
in_str("ba", str) -- false
in_str("foo;", str) -- false

Using PHP and regular expressions, I would accomplish the desired effect with something like this:

function in_str($needle, $haystack) {
    return (bool)preg_match('/(^|;)' . preg_quote($needle, '/') . '(;|$)/', $haystack);
}

I'm unsure how to translate this logic into Lua, though. I'd also rather be able to do it in vanilla Lua, without any plugins/extensions/etc. I'd also like it to be reasonably efficient. The only way I've managed to implement this correctly thus far involves splitting the string into a table, and then iterating it, which is obviously very inefficient.

like image 484
FtDRbwLXw6 Avatar asked May 11 '26 23:05

FtDRbwLXw6


1 Answers

Here's a sample of the code at work: LINK

local str = "foo;bar;baz;and;some;more;random;data;in;here"
function check(sString, sData)
  print( string.find(";"..sString..";", ";"..sData..";") )
end
check( str, "foo" )
check( str, "bar" )
check( str, "ba" )
check( str, "baz" )
check( str, "random" )
check( str, "stuff" )
like image 184
hjpotter92 Avatar answered May 13 '26 23:05

hjpotter92