Search code examples
lualua-tablelua-patterns

How to use patterns to shorten only matching strings


I have a program that grabs a list of peripheral types, matches them to see if they're a valid type, and then executes type-specific code if they are valid.

However, some of the types can share parts of their name, with the only difference being their tier, I want to match these to the base type listed in a table of valid peripherals, but I can't figure out how to use a pattern to match them without the pattern returning nil for everything that doesn't match.

Here is the code to demonstrate my problem:

connectedPeripherals = {
    [1] = "tile_thermalexpansion_cell_basic_name",
    [2] = "modem",
    [3] = "BigReactors-Turbine",
    [4] = "tile_thermalexpansion_cell_resonant_name",
    [5] = "monitor",
    [6] = "tile_thermalexpansion_cell_hardened_name",
    [7] = "tile_thermalexpansion_cell_reinforced_name",
    [8] = "tile_blockcapacitorbank_name"
}

validPeripherals = {
    ["tile_thermalexpansion_cell"]=true,
    ["tile_blockcapacitorbank_name"]=true,
    ["monitor"]=true,
    ["BigReactors-Turbine"]=true,
    ["BigReactors-Reactor"]=true
}

for i = 1, #connectedPeripherals do

    local periFunctions = {
        ["tile_thermalexpansion_cell"] = function()
            --content
        end,
        ["tile_blockcapacitorbank_name"] = function()
            --content
        end,
        ["monitor"] = function()
            --content
        end,
        ["BigReactors-Turbine"] = function()
            --content
        end,
        ["BigReactors-Reactor"] = function()
            --content
        end
    }

    if validPeripherals[connectedPeripherals[i]] then periFunctions[connectedPeripherals[i]]() end
end

If I try to run it like that, all of the thermalexpansioncells aren't recognized as valid peripherals, and if I add a pattern matching statement, it works for the thermalexpansioncells, but returns nil for everything else and causes an exception.

How do I do a match statement that only returns a shortened string for things that match and returns the original string for things that don't?

Is this possible?


Solution

  • If the short version doesn't contain any of the special characters from Lua patterns you can use the following:

    long = "tile_thermalexpansion_cell_basic_name"
    
    result = long:match("tile_thermalexpansion_cell") or long
    print(result) -- prints the shorter version
    
    result = long:match("foo") or long
    print(result) -- prints the long version