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

查看:83
本文介绍了使仅全局环境访问(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天全站免登陆