Ask Your Question
4

How can I use Lua to globally search for things in the format of {{{parameter}}} or {{{parameter|default}}}, and capture both "pattern" and "default" without experiencing overflow?

asked 2021-12-20 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-11-20 18:00:00 +0000

lakamha gravatar image

You can use Lua's string.gsub function to globally search for the pattern and capture both the "pattern" and "default" values. Here's an example:

local input = "some text with {{{parameter}}} and {{{parameter|default}}} placeholders"
local pattern = "{%{%{(.-)%}%}}"
local output = input:gsub(pattern, function(match)
  local parts = {}
  for part in match:gmatch("[^|]+") do
    table.insert(parts, part)
  end
  local pattern = parts[1]
  local default = parts[2] or ""
  print(pattern, default)
end)

In this example, we define the input string and the pattern we want to search for. The pattern matches three opening curly braces, followed by any characters (lazy), followed by three closing curly braces. The .- captures any text between the first and last curly braces, and the () around it make it a capture group.

We use string.gsub to replace all occurrences of the pattern with the result of a function. The function takes the matched text as an argument, and extracts the pattern and default values from it. We split the matched text on the | character to get the two parts, and then use the or operator to set the default value to an empty string if it's not present.

Finally, we print out the pattern and default values for each match. The output variable will contain the original text with the placeholders replaced with our custom values.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-20 11:00:00 +0000

Seen: 13 times

Last updated: Nov 20 '22