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 "$":
"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). gsuballows 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.