I need a pattern that will work with string.find (or string.match if necessary) that will return true if a "table path" string matches. This is my function:
local function FindValueFromPattern(myTable, pattern, previousPath)
for key, value in pairs(myTable) do
local path;
if (not previousPath) then
path = key;
else
path = string.format("%s.%s", previousPath, key);
end
if (path:find(pattern)) then
return value;
elseif (type(value) == "table") then
value = FindValueFromPattern(value, pattern, path);
if (value ~= nil) then
return value;
end
end
end
return nil;
end
local tbl = {}
tbl.settings = {};
tbl.settings.module = {};
tbl.settings.module.appearance = {};
tbl.settings.module.appearance.color = "blue";
print(FindValueFromPattern(tbl, "settings.module.appearance.color")); -- prints "blue";
The code above works BUT I want to now change the pattern to:
"module.<ANY>.color"
where <ANY>
is any child table of "module" and also has a child table called "color", so when traversing down the table, a value will be returned regardless of what table is used (does not have to be the appearance table):
-- should also print "blue" ("setting." should not be required);
print(FindValueFromPattern(tbl, "module.<ANY>.color"));
Rather than returning found values straight away, I may have to change the logic to insert found values in a table and then return the table after the for-loop but I wrote this quickly to illustrate the problem.
So the question is, what would that pattern look like? Thank you.
"settings.module[3].color"
be found? – Egor Skriptunoff"."
so if the pairs function returned a number then, for example, it would still look like"module.2.property"
and I can use this in the pattern I send to the function. Thanks for asking. – Mayron"module.<ANY>.color"
string you might use a"module%.[^.]+%.color"
pattern. If you need to extract the ANY part, wrap the[^.]+
with capturing group:"module%.([^.]+)%.color"
– Wiktor Stribiżew"module%.([^.]+)%.([^.]+)%color"
also work for cases where there are more than 1 of these keys? I might need to do something like this in the future. – Mayron[^.]+
matches any consecutive chars other than.
one or more times. I guess yes. If you need to restrict the chars to letters and digits use%w+
instead. If you need to match any 0+ chars use.-
(to get to the first.color
) or.+
(to match up to the last.color
). – Wiktor Stribiżew