LuaJ load from String instead of Path

996 Views Asked by At

today I tried the LuaJ library and I really enjoy it, the only problem i have with it, is that I can't load from a String containing the functions, instead I can only load of a string containing the filepath.

Here is the code that I tried to load from a String:

LuaValue globals = JsePlatform.standardGlobals();       
globals.get("load").call( LuaValue.valueOf(luascript)); //Exception in this line

With this code I get the following exception:

Exception in thread "LWJGL Application" org.luaj.vm2.LuaError: attempt to call nil
at org.luaj.vm2.LuaValue.checkmetatag(Unknown Source)
at org.luaj.vm2.LuaValue.callmt(Unknown Source)
at org.luaj.vm2.LuaValue.call(Unknown Source)
at Screens.MainMenu.<init>(MainMenu.java:122)

The code that works, but that I don't want, because I need to load it from a string, instead of a filepath is this:

LuaValue globals = JsePlatform.standardGlobals();
globals.get("dofile").call( LuaValue.valueOf(pathtoluascript) );

So my question is, how do i load it from a string instead of a path?

1

There are 1 best solutions below

0
On

Put the code in the load method for the Globals objects, and call after the load. Then you can use the get method of the Globals object with the function name and (optionally) arguments:

Globals gl = JsePlatform.standardGlobals();
gl.load("function TestF(v1, v2)\n\tprint('Test function, v1: ' .. v1, 'v2: ' .. v2)\n\treturn v2\nend").call();

LuaValue lv = gl.get("TestF").call( LuaValue.valueOf("LUAJ2"), LuaValue.valueOf("Test2"));

System.out.println(lv.toString());

LuaValue lv contains the return value of the function you called (again, optional).

Alternatively, to load and call a script instead of a specific named function, you can do the following:

Globals gl = JsePlatform.standardGlobals();
LuaValue lv = gl.load("print('Hello, world!')");

// When you're ready to run the script:
lv.call();