Andreas Rozek      

LuaJava_02 - conversion of Lua values into a string within Java

"JavaFunction"s get their arguments from the Lua stack as "LuaObject"s. "LuaJava_02" examines the bahaviour of a LuaObject's toString method depending on the type of the original Lua value.

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

LuaJava_02

The script itself is extremely simple and should not require any further explanation. After an invocation of the form
 

  java luna.LuaJava LuaJava_02.lua

it produces the following output:

  LuaJava_02 - how are LuaObjects converted into strings within Java?

  Output of 'println(arg,' <-> ',tostring(arg))' depending on 'arg':
    nil      -> nil <-> nil
    true     -> true <-> true
    false    -> false <-> false
    1        -> 1 <-> 1
    1.23     -> 1.23 <-> 1.23
    1.23e45  -> 1.23E45 <-> 1.23E45
    'Test'   -> Test <-> Test
    {1,2,3}  -> Lua Table <-> table: 006DAF00
    Function -> Lua Function <-> function: 006DF730
    <class>  -> class java.lang.System <-> userdata: 006D9180

  Output of 'io.stdout:write(tostring(arg))' depending on 'arg':
    nil      -> nil
    true     -> true
    false    -> false
    1        -> 1
    1.23     -> 1.23
    1.23e45  -> 1.23e+045
    'Test'   -> Test
    {1,2,3}  -> table: 006D95D0
    Function -> function: 006DF730
    Thread   -> thread: 006D9390
    <class>  -> userdata: 006D9180

Most of the output looks as expected - the interesting line is explicitly marked.

Objects of (Lua) type "thread" must not be passed to Java functions - trying to invoke their "toString" method will just throw a java.lang.NullPointerException - for what reason is unclear to the author.

The initial problem (mentioned in a previous version of this web page), that integers are always converted to strings using a floating-point format, has meanwhile be solved (and does no longer appear in the above output). The formatting problem came from the behaviour of the LuaObject.toString() method:

  • Lua numbers (represented by a LuaObject) are always converted to strings using a floating-point format;
  • Lua strings (represented by a LuaObject) seem to be analyzed (within the toString() method) and - when their content appears as a valid Lua number - be converted into a number which is then converted back into a string using the floating-point format mentioned above.

With the help of Thiago Ponte, the author therefore modified his print/println functions (and all similar ones) to check for the original type of any given Lua argument and handle Lua numbers and strings explicitly.

Source Code

The source code of this script is publically available:

Disclaimer

Please, also consider the author's Disclaimer!


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