greatodensraven
greatodensraven

Reputation: 311

lua variable in pattern match

Im just wondering if it is possible to put a variable in a pattern match in Lua. Like something similar to the following:

var = "hello"
pattern = string.match(datasource, "(var)%s(a%+)")

The reason I need to do this is because the variable "var" will change periodically. (it will be in a loop)

Cheers in advance

Upvotes: 7

Views: 3153

Answers (3)

Krackout
Krackout

Reputation: 282

I needed the same thing I think, a variable in a pattern match, but the above solution didn't work for me. I'm posting my solution in case it helps someone, didn't find anything else on the net like it.

I read a ': ' delimited file (name: tel) and want to search by name in the file and have the name and telephone number as answer.

local FileToSearch = h:read'*a' -- Read all the file
var = io.read() -- ask the name
string.gmatch(FileToSearch, ''..var..': '..'%d+') -- search for name, concatenate with number 

Upvotes: 2

Tom
Tom

Reputation: 314

Lua doesn't handle string interpolation inside of the quotes. Instead, you'll need to concatenate the parts with the var as a var reference and the rest as quote strings.

"("..var..")%s(a%+)" starts with a "(" as a string literal, concatenates the variable, then finishes off the rest of the string with a string literal.

Upvotes: 11

lhf
lhf

Reputation: 72412

Use "("..var..")%s(a%+)" instead.

Upvotes: 6

Related Questions