Lua “如何制作全局变量”;不变的;在卢阿/卢阿?

Lua “如何制作全局变量”;不变的;在卢阿/卢阿?,lua,luaj,readonly-variable,Lua,Luaj,Readonly Variable,说明 我正在做一个LuaJ程序,下面是一个lib脚本,如下所示: 函数foo() 印刷品(“foo”); 结束 我希望foo函数可以在其他脚本中直接调用(无require),但在不同的脚本中执行不可变。(即使脚本覆盖了它,它也会像其他脚本中的原始方式一样执行。) 例如,下面是脚本1: foo=function() 印刷品(“酒吧”); 结束 下面是脚本2: foo(); 做了什么 我看到了这两个问题。它们确实有效,但不能解决这个问题 我尝试在每次执行脚本或设置local\u ENV

说明

我正在做一个LuaJ程序,下面是一个lib脚本,如下所示:

函数foo()
印刷品(“foo”);
结束
我希望
foo
函数可以在其他脚本中直接调用(无
require
),但在不同的脚本中执行不可变。(即使脚本覆盖了它,它也会像其他脚本中的原始方式一样执行。)

例如,下面是脚本1:

foo=function()
印刷品(“酒吧”);
结束
下面是脚本2:

foo();
做了什么

我看到了这两个问题。它们确实有效,但不能解决这个问题


我尝试在每次执行脚本或设置
local\u ENV
时加载lib,但由于可能会有从Java到Lua的进一步回调,因此无法正常工作

现在,我通过创建一个
Globals
并在每次加载Java脚本时加载lib脚本来处理它,如下所示:

publicstaticvoidmain(字符串[]args){
loadAndCallViaDifferentienV(libPath,script1);
loadAndCallViaDifferentienV(libPath,script2);
}
静态void loadAndCallViaDifferentienV(字符串libPath、字符串scriptPath){
Globals Globals=jsepplatform.standardGlobals();
loadfile(libPath.call();
loadfile(scriptPath).call();
}

它工作得很好,但成本很高。有更好的方法吗?

我假设您想保护三个函数不被覆盖:
foo1
foo2
print

-- define foo1 and foo2 inside protected table instead of as usual globals
local protected = {}

function protected.foo1()  
   print("foo1");
end

function protected.foo2()
   print("foo2");
end

-- if a function to be protected already exists, remove it from globals:
protected.print = print
print = nil

-- Now set the metatable on globals
setmetatable(_G, {
   __index = protected,
   __newindex =
      function(t, k, v)
         if not protected[k] then
            rawset(t, k, v)
         end
      end
})
现在,您可以从其他模块调用
foo1
foo2
print
,而无需
require
,但您不能覆盖它们:

-- the script 1:
foo1 = function()
   print("bar");
end
foo1();   -- original protected.foo1() is invoked

我假设您想保护三个函数不被覆盖:
foo1
foo2
print

-- define foo1 and foo2 inside protected table instead of as usual globals
local protected = {}

function protected.foo1()  
   print("foo1");
end

function protected.foo2()
   print("foo2");
end

-- if a function to be protected already exists, remove it from globals:
protected.print = print
print = nil

-- Now set the metatable on globals
setmetatable(_G, {
   __index = protected,
   __newindex =
      function(t, k, v)
         if not protected[k] then
            rawset(t, k, v)
         end
      end
})
现在,您可以从其他模块调用
foo1
foo2
print
,而无需
require
,但您不能覆盖它们:

-- the script 1:
foo1 = function()
   print("bar");
end
foo1();   -- original protected.foo1() is invoked