0

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?

Zero
  • 1
  • 1
  • 2
  • I'm not familiar with LuaJ but I found this example in LuaJ homepage. It may help you: `chunk = globals.load(new StringReader("print 'hello, world'"), "main.lua"); ` – Meysam Dec 08 '14 at 13:19
  • Thanks for the response, when I tried that, the IDE shows me this error: The method load(LuaValue) in the type LuaValue is not applicable for the arguments (StringReader, String) – Zero Dec 08 '14 at 13:30
  • this example was from LuaJ version 3.0 . which version do you use? – Meysam Dec 08 '14 at 13:33
  • I am using LuaJ-JSE-3.0, so that shouldn't be the problen, I think. – Zero Dec 08 '14 at 13:38
  • Ok I think I found it. You stored globals variable as LuaValue type. Change it and use it as Globals type. like this: `Globals globals = JsePlatform.standardGlobals();` – Meysam Dec 08 '14 at 13:42
  • Yep, i also noticed that, thanks a lot for the help, when working on something for a while, I overlook my mistakes, I guess, I will need to look more closely in the future. Again, thanks a lot. – Zero Dec 08 '14 at 13:46

1 Answers1

1

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();
MrScuffles
  • 11
  • 2