使全局环境只能访问(Lua) [英] Making global environment access-only (Lua)

查看:20
本文介绍了使全局环境只能访问(Lua)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我嵌入了 Lua 并希望脚本能够读取全局表但不会自动写入它,因此两个脚本可以编写具有相同名称的变量而不会相互覆盖,但仍然能够向全局表添加内容.我真的无法解释得比这更好:

I embedded Lua and want scripts to be able to read the global table but not automatically write to it so two scripts can write variables with the same name without overwriting eachother but still being able to add stuff to the global table. I can't really explain it better then this:

脚本 1

var1 = "foo"
_G.var2 = "bar"

脚本 2

print(var1) -- Prints nil
print(var2) -- Prints 'bar'

我试图通过做这样的事情来实现这一点(脚本"是一个函数)

How I tried to accomplish this is by doing something like this (The 'scripts' being a function)

newScript = function(content)
    Script = loadstring(content)()
    env = setmetatable({},{__index = _G})
    setfenv(Script,env)
    return Script
end

我的 Lua 绑定是 LuaJ,为了提供所有信息,这里也是代码:

My Lua binding is LuaJ, for the sake of giving all information here is that code too:

private LuaValue newScript(String content){
        LuaTable envMt = new LuaTable();
        envMt.set(INDEX, _G);
        LuaTable env = new LuaTable();
        env.setmetatable(envMt);

        LuaClosure func = (LuaClosure) _G.get("loadstring").call(valueOf(content));

        thread = new LuaThread(func,env);
        thread.resume(NIL);
        return thread;
}

推荐答案

这是我用来返回只读表的函数:

Here's a function I use to return a read-only table:

function ro_table (t)
  local t = t
  if t then
    return setmetatable({}, 
      { __index=t, 
        __newindex= function(_,_,_) error ("Attempt to modify read-only table") end, 
      })
  else
    return nil
  end
end

因此,对于您的代码,您将拥有以下内容:

So for your code, you'd have the following:

newScript = function(content)
    Script = loadstring(content)()
    setfenv(Script,ro_table(_G))
    return Script
end

请注意,这不会递归地工作,因此如果您将任何表定义为全局(甚至任何内置函数),则可以更改内容,但不能替换表本身.

Note that this does not work recursively, so if you have any table defined as a global (or even any of the built-in functions) the contents can be changed, but the table itself cannot be replaced.

这篇关于使全局环境只能访问(Lua)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆