1

I am loading different Lua scripts using LuaJ into the globals environnment as follows in Java:

globals = JmePlatform.standardGlobals();
LuaValue chunk = globals.load(new FileInputStream(luaScriptA), scriptName, "t", globals);
chunk.call();

My problem is that if for example the scriptName happens to be require, print, error, math or any other name that already exists in globals after calling

globals = JmePlatform.standardGlobals();

, the script will in fact replace/override the actual functionality such as print.

Is there any simple way to prevent this from happening?

Unfortunately a test such as:

if (globals.get(scriptName) != Globals.NIL) {
    //then dont allow script load
}

will not work for me as there are cases that it should actually override an existing script, when the script is updated.

AvdB
  • 65
  • 7

1 Answers1

1

I recommend never storing libraries in the global scope, for exactly this reason. See http://www.luafaq.org/#T1.37.2 for a way of loading modules and libraries using required. I'm not sure if this works on LuaJ, but if it implements require correctly, you can make a loader function and put it in package.loaders.

Basically, you define your libraries like this:

-- foo.lua
local M = {}

function M.bar()
    print("bar!")
end

return M

And import them like this:

-- main.lua
local Foo = require "foo"
Foo.bar() -- prints "bar!"

See the documentation of require for implementing the loading function.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85