2014-01-26 42 views
3

我正在寫在node.js的一個腳本,使用的Scripto,我試圖做一個零檢查,從數據庫中值: 這裏是js代碼(節點) -如何使用redis-scripto和redis DB在NULL中檢查null nil?

var redis = require("redis"); 
var redisClient = redis.createClient("6379","localhost"); 
var Scripto = require('redis-scripto'); 
var scriptManager = new Scripto(redisClient); 

var scripts = { 
    'test':'local function test(i) '+ 
    'if (i==nil) then return i end '+ 
    'local ch = redis.call("get", i) '+ 
    'if (ch==nil) then return ("ch is nil") '+ 
    'else return "1" '+ 
    'end end '+ 
    'return (test(KEYS[1]))', 
}; 

scriptManager.load(scripts); 
scriptManager.run('test', ["someInvalidKey"], [], function(err,result){ 
    console.log(err || result); 
}); 

但我無法進入「ch is nil」在if語句中...任何幫助?

回答

13

的Lua的片段:

redis.call("get", i) 

Redis的GET方法從不返回零,但它返回一個布爾值(假),如果沒有鍵存在。

你的代碼更改爲:

local function test(i) 
    if (i==nil) then 
    return 'isnil ' .. i 
    end 
    local ch = redis.call("get", i) 
    if (ch==nil or (type(ch) == "boolean" and not ch)) then 
    return ("ch is nil or false") 
    else 
    return "isthere '" .. ch .. "'" 
    end 
end 
return (test(KEYS[1])) 

或者更簡單(LUA平等不同類型之間的檢查是允許的,總是返回false):

local function test(i) 
    if (i==nil) then 
    return 'isnil ' .. i 
    end 
    local ch = redis.call("get", i) 
    if (ch==false) then 
    return ("ch is false") 
    else 
    return "isthere '" .. ch .. "'" 
    end 
end 
return (test(KEYS[1])) 

如果你用它玩多一點,你會發現你可以比這更簡單,但你會明白的。

希望這會有所幫助,TW

+0

非常感謝!有一些要點:) –

+0

不客氣! –