Andreas Rozek      

LuaJava_04 - the natural Java Equivalents of Lua Types

When LuaJava is used to invoke a Java method from within Lua, it might have to decide which concrete method out of a set of possible methods (with the same name but different signatures - i.e. number and type of arguments) might be appropriate.

LuaJava_04 checks which Java argument type is preferred by LuaJava, when it has to look for an equivalent of a given Lua type. It does so by offering multiple copies of the same Java method - each with a different type of argument which might be a primitive one or one of a few foreseen Java classes.

Please, also consider my "Hints for Reading" and the "List of Recent Changes"!
(Problems displaying this page? Ugly graphics? Please, click here)

LuaJava_04

The script itself is extremely simple and should not require any further explanation. The accompanying Java source may be compiled using
 

  javac LuaJava_04.java

and does not even need the luajava package. The resulting class file should be copied to a place where it can be found by the Java class loader (e.g., into a directory which is automatically scanned by the Java extension mechanism).

After an invocation of the form
 

  java luna.LuaJava LuaJava_04.lua

the script produces the following output

LuaJava_04 - what are the "natural" Java equivalents of Lua types?

  Lua2Java(nil)          -> (crashes)
  Lua2Java(true)         -> boolean (true)
  Lua2Java(123)          -> byte (123)
  Lua2Java(12345)        -> byte (57)
  Lua2Java(1234567)      -> byte (-121)
  Lua2Java(123456789)    -> byte (21)
  Lua2Java(123.456)      -> byte (123)
  Lua2Java(12.34e56)     -> byte (-1)
  Lua2Java('Test')       -> String (Test)
  Lua2Java({})           -> (generic) Object
  Lua2Java(JavaClass)    -> (generic) Object
  Lua2Java(JavaInstance) -> (generic) Object

which looks extremely interesting:

  • never pass the Lua value nil to a Java method - it will crash;
  • boolean and literal (string) values are treated as boolean's or String's - as one might expect;
  • any kind of number is treated as a byte - which is the worst LuaJava can do;
  • tables and userdata values are treated like generic object's - even if there might be a method with an argument which fits better;

It seems as if one should look very carefully at the Java method (and its signatures) before one tries to invoke it using LuaJava - otherwise, the result of the method invocation might not be what has been expected...

Source Code

The source code of this script and its accompanying Java class is publically available:

Disclaimer

Please, also consider the author's Disclaimer!


http://www.Andreas-Rozek.de/LuaJava/Acquainting/LuaJava_04_en.html   (last Modification: 25.11.2004)