如何使用模式,以缩短仅匹配字符串

如何使用模式,以缩短仅匹配字符串

问题描述:

我有抓住外围类型的列表,匹配他们看看他们是否有效的类型,然后它们是否有效执行特定类型的代码的程序。如何使用模式,以缩短仅匹配字符串

但是,有些类型可以共享部分名称,唯一不同的是它们的层次,我想将它们与有效外设列表中列出的基类型进行匹配,但我无法弄清楚使用模式来匹配它们,而不会返回nil的模式,但不匹配所有内容。

这里是为了证明我的问题代码:

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 

如果我尝试这样运行它,所有的thermalexpansioncells不能被识别为有效外设,如果我添加匹配的语句模式,它适用于thermalexpansioncells,但对于其他任何情况返回nil并导致异常。

我怎么做一个匹配语句只返回匹配的事情缩短字符串,返回的东西,不要原始字符串?

这可能吗?

如果短版不包含任何特殊字符从Lua模式,你可以使用以下命令:

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 
+2

您也可以使用该方法调用语法甚至更短,更可读的代码,例如:结果=长:比赛(“富”)或长 – tonypdmtr 2015-04-03 13:33:36

+0

@tonypdmtr是这好得多:) – ryanpattison 2015-04-03 13:35:23

基于the comment,您还可以使用string.find看到类型匹配的外设名称:

for i,v in ipairs(connectedPeripherals) do 
    local Valid = CheckValidity(v) 
    if Valid then Valid() end 
end 

其中,CheckValidity将从validPeripherals返回键:

function CheckValidity(name) 
    for n, b in pairs(validPeripherals) do 
     if name:find(n) then return n end 
    end 
    return false 
end 
+0

我不能手动指定connectedPeripherals'的'内容那样,我只能这样做,为示范的目的,但实际的程序中,该表将自动填充,每次程序运行时可以是不同的。 'connectedPeripherals'由一个'peripherals.getNames()'方法填充,该方法自动用连接的外设名称填充表,所以我不能在其中创建一个哈希表,而没有其他改变表的内容,我不知道如何做到这一点。 – 2015-04-03 08:58:25

+0

@MarkKramer更新答案 – hjpotter92 2015-04-03 09:08:25