Lua with Java
LuaJava allows Lua scripts to run within Java. The Lua interpreter (plus some binding code) is loaded using JNI.
Here is an example script:
sys = luajava.bindClass("java.lang.System")
print ( sys:currentTimeMillis() )
(Note that there is no require 'luajava'
needed because we are running within LuaJava.)
newInstance
creates a new instance of an object of a named class.
strTk = luajava.newInstance("java.util.StringTokenizer",
"a,b,c,d", ",")
while strTk:hasMoreTokens() do
print(strTk:nextToken())
end
Which can also be expressed as
StringTokenizer = luajava.bindClass("java.util.StringTokenizer")
strTk = luajava.new(StringTokenizer,"a,b,c,d", ",")
...
LuaJavaUtils is a little set of utilities to make using LuaJava easier. The java.import
module provides an import
function which works like the Java statement of this name.
require 'java.import'
import 'java.util.*'
strTk = StringTokenizer("a,b,c,d", ",")
...
This module modifies the global Lua environment so that undeclared globals are first looked up in the import list, and made into class instances if possible; the call
metamethod is also overloaded for these instances so we can say Class()
rather than luajava.new(Class)
.
There are also a few little Java classes to get around a limitation of LuaJava, which is that one cannot inherit from full classes.
-- a simple Swing application.
require 'java.import'
import 'java.awt.*'
import 'java.awt.event.*'
import 'javax.swing.*'
import 'java.awt.image.*'
import 'javax.imageio.*'
import 'java.io.*'
-- this is for PaintPanel and Painter...
import 'org.penlight.luajava.utils.*'
bi = ImageIO:read(File(arg[1] or "bld.jpg"))
w = bi:getWidth(nil);
h = bi:getHeight(nil);
painter = proxy("Painter", {
painter = function(g)
g:drawImage(bi, 0, 0, nil)
end
})
f = JFrame("Image")
f:setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
canv = PaintPanel(painter)
canv:setPreferredSize(Dimension(w,h))
f:add(JScrollPane(canv))
f:pack()
f:setVisible(true)
LuaJava only supports Java 1.4, so nifty features like generics and variable argument lists are not supported. Also, currently error handling is a little primitive.
Kahlua is a project to completely implement the Lua engine in Java. The target platform is the reduced runtime J2ME found in mobile phones; the main example is a little Lua interpreter which can run on your phone.
Another option is luaj which targets both J2ME and J2SE and "unique direct lua-to-java-bytecode compiling".