praveen0894
praveen0894

Reputation: 76

Pass command line arguments in lua using java

I am trying to trigger lua script from java using below code and it is working fine.

Globals globals = JsePlatform.standardGlobals();
LuaValue chunk = globals.loadfile("com/example/hello.lua");
chunk.call();

Now I want to pass command line arguments to my lua script, can someone help mw with the code how to pass command line argument to lua file from java.

Upvotes: 0

Views: 167

Answers (1)

Luatic
Luatic

Reputation: 11201

You appear to be using LuaJ. First, Lua "chunks" are just special functions which get their arguments in the ... vararg. hello.lua might look as follows:

local arg1, arg2 = ...
print("arg1", arg1, "arg2", arg2)

Using Lua's loadfile, you could pass arguments simply as function arguments when executing the loaded chunk:

local chunk = assert(loadfile"hello.lua") -- compile & load the file, do not run it
chunk("first arg", "second arg") -- run the file with two args

Your current Java code calls chunk.call() without any arguments, which would be equivalent to chunk() in Lua. You can use the invoke method to pass a list of LuaValue arguments:

Just replace chunk.call(); with

chunk.invoke(new LuaValue[] {LuaValue.valueOf("first argument"), LuaValue.valueOf("second argument")});

to invoke the chunk with two arguments equivalent to the invokation in the above Lua example.

Upvotes: 1

Related Questions