栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

脚本尝试创建全局变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

脚本尝试创建全局变量

查看文件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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/394488.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号