Search code examples
javalualuaj

Luaj / Java: org.luaj.vm2.LuaError: loop or previous error loading module


I am learning the Luaj library and I am trying to implement the hyperbolic example in a unit test:

@Test
public void testHyperbolicLuaScriptExample() throws Exception {
    URL luaScriptUrl = Thread.currentThread().getContextClassLoader().getResource("hyperbolic.lua");
    Assert.assertNotNull(luaScriptUrl);
    String luaScriptUrlPath = luaScriptUrl.getPath();
    File luaScriptFile = new File(luaScriptUrlPath);
    FileInputStream luaScriptFileInputStream = new FileInputStream(luaScriptFile);
    Prototype luaScriptPrototype = LuaC.instance.compile(luaScriptFileInputStream, "");
    Globals luaScriptStandardGlobals = JsePlatform.standardGlobals();
    LuaClosure luaClosure = new LuaClosure(luaScriptPrototype, luaScriptStandardGlobals);
    LuaValue luaValue = luaClosure.call();
}

hyperbolic.java is constructed as per the example

import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.*;

public class hyperbolic extends TwoArgFunction {

    public hyperbolic() {}

    public LuaValue call(LuaValue moduleName, LuaValue environment) {
        LuaValue library = tableOf();
        library.set("sinh", new sinh());
        library.set("cosh", new cosh());
        environment.set("com.apple.aide.lua.hyperbolic", library);
        return library;
    }

    static class sinh extends OneArgFunction {
        public LuaValue call(LuaValue x) {
            return LuaValue.valueOf(Math.sinh(x.checkdouble()));
        }
    }

    static class cosh extends OneArgFunction {
        public LuaValue call(LuaValue x) {
            return LuaValue.valueOf(Math.cosh(x.checkdouble()));
        }
    }
}

And the in hyberbolic.lua

require 'hyperbolic'

return {"x", hyperbolic.sinh(0.5), "y", hyperbolic.cosh(0.5)}

However the test produces the following error

org.luaj.vm2.LuaError: @hyperbolic.lua:3 loop or previous error loading module 'hyperbolic'
    at org.luaj.vm2.LuaValue.error(Unknown Source)
    at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
    at org.luaj.vm2.LuaClosure.execute(Unknown Source)
    at org.luaj.vm2.LuaClosure.call(Unknown Source)
    at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
    at org.luaj.vm2.LuaClosure.execute(Unknown Source)
    at org.luaj.vm2.LuaClosure.call(Unknown Source)
    at com.example.LuaScriptExecutionTest.testHyperbolicLuaScriptExample(LuaScriptExecutionTest.java:52)

What does this error mean and how do I fix it?


Solution

  • And the in hyberbolic.lua (sic, should be hyperbolic)

    require 'hyperbolic'
    

    You require a module with the same name as the file in which require happens, which leads to a loop (that's what the error message is about). Simply rename the current file (hyperbolic.lua) and the error should go away.