2014-02-19 109 views
2

我想在lua中有一個簡單的數據結構,類似於Java HashMap等價物。如何在Lua中創建等價的HashMap <Int, Int[]>

這樣做的目的是,我希望保持一個唯一的鍵'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 

回答

0

只需使用一個Lua表的用戶ID和與價值觀其他的Lua表索引有兩個條目:

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

假設字典是你問什麼:

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

棘手的部分是,密鑰是一個字符串,無法轉換爲Lua變量名稱,因此您必須圍繞每個密鑰與[]。我無法在Lua 5.1 reference manual中找到有關此規則的明確說明,但Lua wiki表示,如果一個密鑰「由下劃線,字母和數字組成,但不以數字開頭」,那麼它是否不需要[]當以上述方式定義時,否則方括號是必需的。

+0

嘗試這樣 私有靜態最後字符串READ_SCRIPT_IN_LUA = 「本地詞典= {」 + 「[ '77777'] = {254,24992},」 + 「[ '88888'] = {253, 24991},「+ 」['99999'] = {252,24990}「+ 」}「+ 」return dictionary「; Object o = jedis.eval(String.format(READ_SCRIPT_IN_LUA)); System.out.println(o.toString()); 輸出:[] 我做錯了什麼? –

0

這是解決方案的可能實施。

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 
相關問題