Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LUA String manipulation: get all words starting with a specific character as "$"?

I’m writing a script in LUA.
I would need to get a string and get all the words are beginning with $ (they are wildcards), sending them to a function that will decode them, end rebuild the string with the values of each wildcard do not knowing upfront which wildcard the string has in it.

Example: please suppose the following wildcards having their values:

$title = Test Song
$author = Tormy
$date = 2022-10-15
$project = Test Project

and a string so built but, as I sadi, I cannot know upfront the kind of contained wildcards. i only now, they are starting with "$":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"The title of this song is $title. $title was composed by $author in $date, when he have created the $project"

I know how to make a string substitution (and I know how to do it).
What I’m not able to do is to get all the words starting with "$"

I was able to get the just the "$" out of the sentence (so I could count it and know how many wildcards the string has)

I could get all what there is before the character "$" and/or after it.

But not just the wildcard itself.

>Solution :

The good old string interpolation in Lua. You can do this pretty conveniently using string.gsub:

local vars = {
    title = "Test Song",
    author = "Tormy",
    date = "2022-10-15",
    project = "Test Project",
}
local template = "The title of this song is $title. $title was composed by $author in $date, when he have created the $project"
local interpolated = template:gsub("%$(%w+)", vars)
print(interpolated) -- The title of this song is Test Song. Test Song was composed by Tormy in 2022-10-15, when he have created the Test Project

Note:

  • The pattern is %$(%w+): A dollar sign (escaped because it is a magic character), followed by a captured word (one or more alphanumeric characters).
  • gsub allows passing a table as second argument; it will look up the capture in that table, and replace the entire matched substring with the value if it is non-nil.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading