【问题标题】:How to create the equivalent of a HashMap<Int, Int[]> in Lua如何在 Lua 中创建等效的 HashMap<Int, Int[]>
【发布时间】:2014-03-19 20:45:40
【问题描述】:

我想在 lua 中有一个简单的数据结构,类似于 Java HashMap 等价物。

这样做的目的是我希望维护一个唯一键“userID”,该键映射到一组不断更新的两个值,例如;

'77777', {254, 24992}

关于如何实现这一点的任何建议?


-- Individual Aggregations
local dictionary = ?

-- Other Vars
local sumCount = 0
local sumSize = 0
local matches = redis.call(KEYS, query)

for _,key in ipairs(matches) do
    local val = redis.call(GET, key)
    local count, size = val:match(([^:]+):([^:]+))

    topUsers(string.sub(key, 11, 15), sumCount, sumSize)

    -- Global Count and Size for the Query
    sumCount = sumCount + tonumber(count)
    sumSize = sumSize + tonumber(size)
end

local result = string.format(%s:%s, sumCount, sumSize)
return result;

-- Users Total Data Aggregations
function topUsers()
  -- Do sums for each user
end

【问题讨论】:

    标签: data-structures dictionary lua redis hashmap


    【解决方案1】:

    假设字典就是你要问的:

    local dictionary = {
        ['77777'] = {254, 24992},
        ['88888'] = {253, 24991},
        ['99999'] = {252, 24990},
    }
    

    棘手的部分是键是一个不能转换为 Lua 变量名的字符串,所以你必须用[] 包围每个键。我在Lua 5.1 reference manual 中找不到对此规则的明确描述,但Lua wiki 表示,如果一个键“由下划线、字母和数字组成,但不以数字开头”,那么它只会这样做上述方式定义时不需要[],否则需要方括号。

    【讨论】:

    • 试过这个私有静态最终字符串 READ_SCRIPT_IN_LUA = "local dictionary = {"+ " ['77777'] = {254, 24992},"+ "['88888'] = {253, 24991} ,"+ "['99999'] = {252, 24990}"+ "}"+ " 返回字典";对象 o = jedis.eval(String.format(READ_SCRIPT_IN_LUA)); System.out.println(o.toString());输出:[] 做错什么了吗?
    【解决方案2】:

    只需使用一个由 userID 索引的 Lua 表,并使用另一个具有两个条目的 Lua 表:

    T['77777']={254, 24992}
    

    【讨论】:

      【解决方案3】:

      这是解决方案的可能实现。

      local usersTable = {}
      
      function topUsers(key, count, size)
          if usersTable[key] then
              usersTable[key][1] = usersTable[key][1] + count
              usersTable[key][2] = usersTable[key][2] + size
          else
              usersTable[key] = {count, size}
          end
      end
      
      function printTable(t)
          for key,value in pairs(t) do 
              print(key, value[1], value[2])
          end
      end
      

      【讨论】:

        猜你喜欢
        • 2014-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        • 2020-03-22
        • 2020-10-16
        • 2014-03-14
        • 1970-01-01
        相关资源
        最近更新 更多