JooF
JooF

Reputation: 11

How to store part of a string in a variable on Lua

I have a phrase, where only some words will change, and I need to store those words on a variable.

Example:

phrase = "I cannot connect to server XPTO\TEST for the last five hours"

The only part that will change is XPTO\TEST and I need to store it on a variable so that I can use it later.

Any ideas, or is it possible?

Upvotes: 1

Views: 225

Answers (1)

excanoe
excanoe

Reputation: 696

Seems like you need some form of placeholders, if that is a case, then you can use string.format or string.gsub.

 local t = {name="lua", version="5.3"}
 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
 --> x="lua-5.3.tar.gz"

With PHP for example you can achieve what you want without any extra work done, because there is a feature called string interpolation (wiki).

But at the same time Lua doesn't have one, that's why you can't do that without extra string post-processing.

Upvotes: 2

Related Questions