2013-11-15 118 views
5

我想一個腳本加載到將出口,未來的腳本執行將取決於功能Redis的,但試圖定義全局函數調用失敗,同樣適用於全局變量:腳本試圖創建全局變量

redis 127.0.0.1:6379> EVAL "function alex() return 3.1415 end" 0 
(error) ERR Error running script (call to f_f24a5a054d91ccc74c2629e113f8f639bbedbfa2): user_script:1: Script attempted to create global variable 'alex' 

如何定義全局函數和變量?

+0

添加LUA腳本除非你想要這樣的答案:不要定義全局變量:P –

+0

@Tommaso對於混淆抱歉,但問題是關於全局變量。 – Alex

回答

8

文件scripting.c在源代碼展望

/* This function installs metamethods in the global table _G that prevent 
* the creation of globals accidentally. 
* 
* It should be the last to be called in the scripting engine initialization 
* sequence, because it may interact with creation of globals. */ 
void scriptingEnableGlobalsProtection(lua_State *lua) { 
    char *s[32]; 
    sds code = sdsempty(); 
    int j = 0; 

    /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html. 
    * Modified to be adapted to Redis. */ 
    s[j++]="local mt = {}\n"; 
    s[j++]="setmetatable(_G, mt)\n"; 
    s[j++]="mt.__newindex = function (t, n, v)\n"; 
    s[j++]=" if debug.getinfo(2) then\n"; 
    s[j++]=" local w = debug.getinfo(2, \"S\").what\n"; 
    s[j++]=" if w ~= \"main\" and w ~= \"C\" then\n"; 
    s[j++]="  error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n"; 
    s[j++]=" end\n"; 
    s[j++]=" end\n"; 
    s[j++]=" rawset(t, n, v)\n"; 
    s[j++]="end\n"; 
    s[j++]="mt.__index = function (t, n)\n"; 
    s[j++]=" if debug.getinfo(2) and debug.getinfo(2, \"S\").what ~= \"C\" then\n"; 
    s[j++]=" error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n"; 
    s[j++]=" end\n"; 
    s[j++]=" return rawget(t, n)\n"; 
    s[j++]="end\n"; 
    s[j++]=NULL; 

    for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j])); 
    luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua"); 
    lua_pcall(lua,0,0,0); 
    sdsfree(code); 
} 

scriptingEnableGlobalsProtection的文檔字符串表示的意圖是(不使用local)通知常見的錯誤的腳本作者。

它看起來這是不是安全功能,所以我們有兩個解決方案:

人們可以刪除此保護:

local mt = setmetatable(_G, nil) 
-- define global functions/variables 
function alex() return 3.1415 end 
-- return globals protection mechanizm 
setmetatable(_G, mt) 

或者使用rawset

local function alex() return 3.1415 end 
rawset(_G, "alex", alex) 
+0

我愛你,你已經找到了一個方法來做到這一點。黑客精神爲贏!不過,我會建議人們不要使用這種方法。從Redis文檔中可以清楚看到,意圖是通過強制腳本不駐留在服務器上來簡化服務器管理(這通過基於SHA的高速緩存高效完成)。將功能注入全局範圍會顛覆這種意圖。精彩的黑客攻擊,亞歷克斯。 –

+0

可以使用全局作用域來存儲通用代碼。另一種方法是使用模板引擎將所有腳本編譯爲一個發送給Redis的腳本。我更喜歡前者 - 使用redis客戶端並使用所有的實用程序更容易。請注意,Redis在實踐中的操作從來不簡單或清晰。 – Alex

+1

從'EVAL'上的Redis文檔:「如果用戶使用Lua全局狀態混亂,AOF和複製的一致性不能保證:不要這樣做。」 –