So I’ve been doing some Lua integration too. I use Kahlua and I’ve never used or even looked at LuaJ but hopefully the functionality will be similar. I mainly integrate through adding “libraries” (tables of functions) to the Lua environment. Example - A (heavily shortened) library for programming ship behaviour. I know the casting is bit messed up but I couldn’t see a better way of doing it:
public class ShipLib {
private final Ship ship;
public ShipLib(Ship ship) {
this.ship = ship;
}
/**
*
* @param callFrame
* @param nArguments
* @return
*/
public int Ship_thrust(LuaCallFrame callFrame, int nArguments) {
if(nArguments < 2) {
throw new IllegalArgumentException("Less Than 2 Arguments");
}
int index = (int) (double) (Double) callFrame.get(0);
float thrust = (float) (double) (Double) callFrame.get(1);
ship.getThruster(index).setThrust(thrust);
return 0;
}
/**
* m
* @param callFrame
* @param nArguments
* @return
*/
public int Ship_position(LuaCallFrame callFrame, int nArguments) {
callFrame.setTop(3);
callFrame.set(0, Double.valueOf(ship.getPosition().getTranslation().getX()));
callFrame.set(1, Double.valueOf(ship.getPosition().getTranslation().getY()));
callFrame.set(2, Double.valueOf(ship.getPosition().getTranslation().getZ()));
return 3;
}
/**
* m/s
* @param callFrame
* @param nArguments
* @return
*/
public int Ship_velocity(LuaCallFrame callFrame, int nArguments) {
callFrame.setTop(3);
callFrame.set(0, Double.valueOf(ship.getVelocity().getX()));
callFrame.set(1, Double.valueOf(ship.getVelocity().getY()));
callFrame.set(2, Double.valueOf(ship.getVelocity().getZ()));
return 3;
}
public KahluaTable getLib() {
KahluaTable table = Computer.getTable();
table.rawset("thrust", new JavaFunction() {
@Override
public int call(LuaCallFrame callFrame, int nArguments) {
return Ship_thrust(callFrame, nArguments);
}
});
table.rawset("nthrusters", new JavaFunction() {
@Override
public int call(LuaCallFrame callFrame, int nArguments) {
return Ship_nthrusters(callFrame, nArguments);
}
});
table.rawset("position", new JavaFunction() {
@Override
public int call(LuaCallFrame callFrame, int nArguments) {
return Ship_position(callFrame, nArguments);
}
});
table.rawset("velocity", new JavaFunction() {
@Override
public int call(LuaCallFrame callFrame, int nArguments) {
return Ship_velocity(callFrame, nArguments);
}
});
return table;
}
}
So I call getLib() and add that table to the runtime for scripts that involve doing things with a ship. Then that script can call these methods.
Getting functionality programmable in Lua is even easier. Just a matter of running a script ehen you want to do something.