2013-11-15 120 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和复制的一致性不能保证:不要这样做。” –