lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Nov 28, 2015 at 6:14 PM, Paul Merrell <marbux@gmail.com> wrote:
> Hi, All,
>
> I have a prototype table for substituting character strings with UTF8
> characters:
>
>   local tSub = {
> ["%-%-%-"] = "—",
> ["%-%-"] = "–",
> ["%.%.%."] = " … "}
>
> My problem is that the first key/value pair must be processed before
> the second key/value pair because of overlapping characters in the
> keys, but the order in which Lua returns table key/value pairs is
> unpredictable, leading to buggy results in the substitutions.
>
> Eventually the script would make many other substitutions, but I seem
> to be stuck here at the prototype stage because of the unpredictable
> return order.
>
> How might I work around this?
>
> Best regards,
>
> Paul

My solution would be to use two tables. Table 1 would be an array of
patterns in the order you want them checked. Table 2 would be the
table you depict above, using the patterns as keys for replacement
strings.

Then you would iterate over Table 1 with ipairs(), using the value on
each pass to index into Table 2 to fetch the corresponding
substitution string for a gsub() call.

So the code would look something like this:

local tSub = {
    ["%-%-%-"] = "—",
    ["%-%-"] = "–",
    ["%.%.%."] = " … "
}

local tPatts = {
    "%-%-%-",
    "%-%-",
    "%.%.%."
}

for _, patt in ipairs(tPatts) do
    -- "str" here is the string you're performing substitutions on
    str = str:gsub(patt, tSub[patt])
end