查看文件scripting.c中的源代码
void scriptingEnableGlobalsProtection(lua_State *lua) { char *s[32]; sds pre = sdsempty(); int j = 0; 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) thenn"; s[j++]=" local w = debug.getinfo(2, "S").whatn"; s[j++]=" if w ~= "main" and w ~= "C" thenn"; s[j++]=" error("script attempted to create global variable '"..tostring(n).."'", 2)n"; s[j++]=" endn"; s[j++]=" endn"; s[j++]=" rawset(t, n, v)n"; s[j++]="endn"; s[j++]="mt.__index = function (t, n)n"; s[j++]=" if debug.getinfo(2) and debug.getinfo(2, "S").what ~= "C" thenn"; s[j++]=" error("script attempted to access unexisting global variable '"..tostring(n).."'", 2)n"; s[j++]=" endn"; s[j++]=" return rawget(t, n)n"; s[j++]="endn"; s[j++]=NULL; for (j = 0; s[j] != NULL; j++) pre = sdscatlen(pre,s[j],strlen(s[j])); luaL_loadbuffer(lua,pre,sdslen(pre),"@enable_strict_lua"); lua_pcall(lua,0,0,0); sdsfree(pre);}
的doc字符串
scriptingEnableGlobalsProtection表示意图是将常见错误通知脚本作者(不使用
local)。
看来这不是安全功能,所以我们有两个解决方案:
可以删除此保护:
local mt = setmetatable(_G, nil)-- define global functions / variablesfunction alex() return 3.1415 end-- return globals protection mechanizmsetmetatable(_G, mt)
或使用
rawset:
local function alex() return 3.1415 endrawset(_G, "alex", alex)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)