LUA 嵌套 string.gmatch 语法格式

问题描述 投票:0回答:1

我正在努力处理一些嵌套的 gmatch 函数(使用等效的 LUA 代码)

假设我有 (3) 个结构,每个结构都可以提高随机技能动作;

["building1"] = { effect = "+1 Improve Lifestyle, +1 Quell Unrest (Magic), random note"},
["building2"] = { effect = "+2 Hire Adventurers, +1 Trade Commodities"},
["building3"] = { effect = "just some random notes"}

为了简单起见,我有一个循环遍历每个记录......它将效果数据捕获到“sEffects”中。 然后,我尝试使用 gmatch ... 将其拆分以查找(加号),后跟(数字)和(空格)。

我可以使用以下命令将文本分成几行;

    for sLine in string.gmatch(sEffects, "([^,]+)") do
      nCount = nCount +1;
      Debug.chat("line " .. nCount .. " = " .. sLine);

生成以下输出;

line 1 = +1 Improve Lifestyle
line 2 = +1 Quell Unrest (Magic)
Line 3 = random note
Line 1 = +2 Hire Adventurers
Line 2 = +1 Trade Commodities
Line 1 = just some random notes

但是,我需要将其分为(奖励)和(技能)......同时排除任何不以“+”(数字)开头的行。

类似这样的东西;

bonus=1, skill=Improve Lifestyle
bonus=1, skill=Quell Unrest (Magic)
bonus=2, skill=Hire Adventurers
bonus=1, skill=Trade Commodities

它捕获(奖励)和(技能),同时忽略所有其他数据。

也许是这样的(如果我能弄清楚 gmatch 语法)

for bonus, skill in string.gmatch(sLine, "([^+%d]+)") do
  Debug.chat("bonus= " .. bonus);
  Debug.chat("skill= " .. skill);
end

如何格式化 gmatch 搜索以使其执行以下操作?

  1. 忽略任何没有“+”的行
  2. 忽略“+”前面的空格
  3. 返回“+”号后的小数作为第一个变量
  4. 返回 (+)(小数)(空格)之后的行的剩余部分作为第二个变量
string lua match
1个回答
0
投票

既然我陈述了这个问题,我想我找到了解决它的方法。

      local pos = string.find(sLine, "+");  
      if pos == nil then
        -- do nothing
      else
        local sEnd = string.len(sLine);
        nBonus = tonumber(string.sub(sLine, pos+1, pos +1))
        sAction = string.sub(sLine, pos+3, sEnd)
        Debug.chat("bonus=" .. nBonus .. ", skill=" .. sAction .. "]");
      end

首先,我检查 sLine 是否包含加号......这解决了#1

为了解决 #2 和 #3 ...我使用返回的位置 +1 来分配 nBonus

对于#4 ...我可以使用位置返回+3(因此它也会跳过数字后面的空格)...并让它返回所有内容直到行尾。

现在返回以下内容;

bonus=1, skill=Improve Lifestyle
bonus=1, skill=Quell Unrest (Magic)
bonus=2, skill=Hire Adventurers
bonus=1, skill=Trade Commodities
© www.soinside.com 2019 - 2024. All rights reserved.