如何在表中收集多个数据,然后像LUA中的连接字符串一样输出

时间:2014-03-31 08:10:14

标签: lua world-of-warcraft

我对LUA脚本完全不熟悉,并试图创建一个逐个接收数据的表,然后在同一函数中使用它来输出收集的数据。

function PremadeFrame_OnEvent(self, event, arg1, arg2)
  --start chat_msg_raid_leader
  if (event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" ) then
    battlegrounds = {};
    if string.find(arg1,"BGNUMBER") then
      number = string.match(arg1,"%d+");
      battlegrounds[number] = "";
      battlegrounds[number] = battlegrounds[number]..","..arg2;
      for k,v in pairs(battlegrounds) do
      DEFAULT_CHAT_FRAME:AddMessage ("\124c0000FFFF[BG Number:"..k.."]"..v.."");
      end
    end
  end
end

我尝试使用

添加其他数据的数据结尾
battlegrounds[number] = battlegrounds[number]..","..arg2;

但它只输出一个收到的数据,例如第一个玩家名称是Scarill,其他人是John,Max,它从Scarill,John,Max获取数据但输出如

[BG Number 43], Scarill

我希望它输出像

[BG Number 43] Scarill, Max
[BG Number 54] John

2 个答案:

答案 0 :(得分:1)

我猜PremadeFrame_OnEvent是一个事件回调函数。在每次调用时,都会在里面创建新的battlegrounds表,因此它只有一个项目是很自然的。要捕获的不仅仅是当前项目,您需要将battlegrounds设置在PremadeFrame_OnEvent之外,如下所示:

battlegrounds = {}

function PremadeFrame_OnEvent(self, event, arg1, arg2)
  --start chat_msg_raid_leader
  if (event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" ) then
    if string.find(arg1,"BGNUMBER") then
      number = string.match(arg1,"%d+")
      battlegrounds[number] = arg2
      for k,v in pairs(battlegrounds) do
        DEFAULT_CHAT_FRAME:AddMessage ("\124c0000FFFF[BG Number:"..k.."]"..v.."")
      end
    end
  end
end

因此每次在事件处理程序中都不会重新创建它。

答案 1 :(得分:0)

每次调用事件处理程序时都需要扩展字符串:

local battlegrounds = {}

function PremadeFrame_OnEvent(self, event, arg1, arg2)
  --start chat_msg_raid_leader
  if (event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" ) then
    if string.find(arg1,"BGNUMBER") then
      number = string.match(arg1,"%d+")
      if battlegrounds[number] == nil then
          battlegrounds[number] = arg2
      else
          battlegrounds[number] = battlegrounds[number] .. "," .. arg2
      end
      for k,v in ...

但如果PremadeFrame_OnEvent()可以使用相同的arg1arg2多次调用,但是您在字符串中重复,那么您需要将您的战场[数字]作为一个表并且只添加arg2如果尚未在该表中。示例(未测试,可能是语法错误):

local battlegrounds = {}

function PremadeFrame_OnEvent(self, event, arg1, arg2)
  --start chat_msg_raid_leader
  if (event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" ) then
    if string.find(arg1,"BGNUMBER") then
      local number = string.match(arg1,"%d+")
      if battlegrounds[number] == nil then
          battlegrounds[number] = {[arg2] = 1} -- use hash map, will be easiest to search for arg2 later
      else
          -- only add arg2 if not already in there:
          local bgn = battlegrounds[number] 
          if bgn[arg2] == nil then
              table.insert(bgn, arg2)
          end
      end

      for k,v in pairs(battlegrounds) do
          local msg = "\124c0000FFFF[BG Number:" .. k .. "]" .. table.concat(v, ',')
          DEFAULT_CHAT_FRAME:AddMessage(msg)
      end
    end
  end
end

文体说明:除非需要全局

,否则请尽量使用local