javalualuaj

Input from user in Luaj


How can I get user input for io.read()?

As I saw on GitHub, in Globals.java there is this code:

public InputStream STDIN  = null;

So I tried:

Globals globals = JsePlatform.standardGlobals();
globals.STDIN = System.in;
globals.load(new JseBaseLib());
globals.load(new PackageLib());
globals.load(new OsLib());
LuaValue chunk = globals.load("a=io.read(); print(a)");
chunk.call();

But it did not work.


Solution

  • Your code is supposed to work as-is. In fact, you shouldn't even have to do all of that; even just this is supposed to work:

            Globals globals = JsePlatform.standardGlobals();
            LuaValue chunk = globals.load("a=io.read(); print(a)");
            chunk.call();
    

    The reason it's not working for you is that there was a bug in LuaJ 3.0.2, fixed by commit 14745ba76a10 ("Fix call io.read, file:read without params."). Unfortunately, no release has been made since that commit. You can either get the fix by building LuaJ from source (but this is nontrivial on modern systems; see pull request #113), or work around the problem by doing io.read('*l') instead of io.read().