Introduction
Nowadays, Lua has become a more and more popular script language that is widely used in various fields of
applications, such as game programming, server-side applications, etc. Lua is based upon ANSI C libraries, designed as
a light-weight, high-quality, great flexibility, dynamic and embedding language, so many ready-made solutions and
open-sourced projects have been set up to support interaction between Lua and many other mainstream languages, such as
C, C++, Object C++, C#, Java, Python, etc. In this article, we will only show interests in the interoperations between
Lua and Java, especially in the Android game development environment. And, as usual, since this story may involve a lot
of tools, I list all of them below for your reference.
Introducing LuaJava and AndroLua
LuaJava is a scripting tool targeting the Java platform. The main goal of LuaJava is to allow scripts written in Lua
to manipulate components developed in Java. And further, like the way provided in C API in Lua, LuaJava also permits
Java components to be accessed from Lua using the same syntax that is used for accessing Lua's native objects. What's
more, LuaJava also allows Java to implement an interface using Lua.
The latest version of LuaJava is 1.1. You can
download the .dll and .jar components by unzipping the file luajava-1.1-win32-lua51.zip. And, of course,
you can research into the complete source code of LuaJava by unzipping the file luajava-1.1.zip. Both of
the preceding files can be obtained from http://files.luaforge.net/releases/luajava/luajava/LuaJava1.1. Hence, for general Java environments,
such as desktop development, Web server-side programming, you can directly use the above .dll and .jar files in the
file luajava-1.1-win32-lua51.zip. As far as the Android Java applications are concerned, though, things
become a bit tough.
About LuaJava examples
LuaJava is shipped with two simple examples which are both under the Console mode. One is a simplest
hello world level example that illustrates the basic usage of creating a Lua virtual machine and invoking the related
LdoFile method; the other is a rather complex one which shows how the Lua script can execute JDBC related
stuff.
In fact, you can find more snippets of examples of using LuaJava under the sub-folder test
in the source code project, where there are tens of files introducing the LuaJava usage in general Java Console or
desktop applications. What's worth noticing is, although these examples cannot be directly used in Android Java
applications you can find many how-to tips associated with LuaJava usage- that's enough!
As mentioned above, you
cannot use LuaJava in the above mode in Android Java applications. Regrettably, the LuaJava project did not provide the
ready-to-use library libluajava.so to be used abiding by the NDK JNI techniques. So, you can generate the
file libluajava.so by yourself (you can refer to my recent articles at Dotnetslackers related to Android
NDK). In fact, it is probable for you to meet some trouble if you are not pretty familiar with the above tools listed
in the beginning. But, don't worry – there is another ready-made project for you to rest upon – the AndroLua
project.
NOTEIf you are brave enough to try to build the file libluajava.so yourself, note there is a small
bug inside the c source file llex.c. But still don't worry –the author already gave the solution as illustrated in the
following figure.
Figure 1: The modified and corrected file llex.c in Lua 5.1.4

So, before building the library yourselves, you should first update the above file in the Lua
package.
Now, let's turn our conversation to another small popular open-source project -AndroLua.
About AndroLua
AndroLua (https://github.com/mkottman/AndroLua) is
a small luajava based and open-sourced project, created and maintained by mkottman. As introduced by the author,
AndroLua is a Lua interpreter ported to the Android platform, which bears the following features:
- it includes LuaJava, so that developers can access (almost) everything the Android API provides
- because writing code on the soft keyboard can be hard, developers can connect to it using TCP an upload
code from your computer
Since AndroLua is a ready-made Android project that embeds LuaJava, we can directly use the library
libluajava.so accompanying the project. Of course, you can rebuild the library using Android NDK and related tools as
explained in the AndroLua homepage.
So, starting from the next sections, we will ignore the Java desktop-styled
usage examples concerning LuaJava. Instead, we'll focus upon how to use the ready-made library libluajava.so
accompanying the project AndroLua to develop Android Java apps.
Example 1- Hello World
From now on, we are going to create some examples to show the practical interaction between Android Java code and
Lua VM. To do this, please first start up Eclipse and create an Android application named
FirstJavaLuaAPP.
Next, copy all LuaJava related .java files into the src folder in the project. This
is a MUST HAVE to integrate Lua into Android Java apps.
After that, create a sub folder named libs
in the project, under which you should create two sub-folders - armeabi and armeabi-
v7a.
Then, copy the library libluajava.so above to these two sub-folders - armeabi
and armeabi-v7a. Thus, the project will automatically locate this file and add related
reference.
Congratulations! Up till now you are done preparing for talk between Android Java code and Lua VM!
The first and simplest example code is shown below:
LuaStateFactory acts as a factory to manage the lifetime of possibly a group of Lua virtual machines each
of which is represented using a LuaState. But in typical cases, one virtual machine (i.e. one LuaState) is enough. By
invoking the method openLibs, the virtual machine gets ready for work.
Besides, the method
LdoString is like the method loadstring in Lua, which can set up and execute a long and
complex string composed of a large scrap of Lua statements. The subsequent method getGlobal is used to
get the value of the Lua global variable text. Very much similar to the interaction between C and Lua via
C API, by invoking the method getGlobal the value of the Lua variable will be pushed into the stack. So,
the following method toString is used to pop up the value from the stack top (the top element related
index is -1).
In the next section, we are going to delve into another usage of LuaJava.
Example 2- Invoking Lua Functions Case 1
In this example, we will discuss how to invoke simple and short functions defined in the embedding mode. Now, let's
look at the related Java code.
In the preceding code, we define a Lua function in the embedding mode, which requires one argument and
returns two values. After invoking the method LdoString, the Lua VM really sets up the script. Afterwards,
we use the method getLuaObject to retrieve the function imprime defined inside the Lua VM.
And then, within the try block we call the function imprime by passing two parameters, with the first one
– an Object array as the passed-in argument for the function imprime, the second one –an integer to
specify there will be two values returned from the function.
Finally, as you've seen, with the help of
LuaException, we can achieve the target of exception handling in this case.
Example 3- Invoking Lua Independent Functions and Pass Simple Values
In this section, we will learn how to invoke methods defined in the independent .lua files and pass simple
parameters. First, let's look at the simple lua function defined in the file testAdd.lua.
NOTEAs a general rule, the .lua files are recommended to be put under the sub-folder assets in the
project. Of course, they can also be put under more deeply sub-folders under assets. We just did do in our case.
The related Java code is as follows:
Note that possibly because of security Android does not permitting using the method LdoFile
of the Lua virtual machine, so in the above code we have to invoke another method LdoString instead. With
this idea, we have to resort to Java I/O approach to get the whole script related string. As for the rest code dealing
with retrieving the Lua method and making invocation, it has been discussed in the previous section.
Example 4- Passing Java Objects as Parameters
In this section, we are going to introduce a more complex sample in which we will pass a Java object as the
parameter into the independent Lua function defined in the file test1.lua (put under the folder assets).
As usual, let's take a look at the Lua script first.
Here, we use the Lua OOP technique to invoke the method inc of the object (corresponding to
the Java class PublicClassValue defined below) twice. Note the Lua print method related
output result cannot be captured in the Java code – we just want to show the related usage for your reference. At last,
we return the object.
Next, let's look at the Java class PublicClassValue related
code.
Here we defined a simple enough class with nothing complex to introduce. So, let's continue to see how
the Java code invokes the Lua related stuff.
In this case, the method getField bears the similar function as the method
getLuaObject above with which to retrieve the function test1 defined in the out Lua script
file. Then, by calling the method pushObjectValue the instance of the class PublicClassValue
is pushed into the Lua VM stack. After that, the method test1 is called via the method
call. Correspondingly, by invoking the method SetField the returned value of the method
test1 is stored into the Lua variable b. On the whole, here we gave another way to make the
Java code interact with the Lua script code.
Example 5- A Simple Game Case
In this section, we are going to construct a more practical example – a simple game case, in which we will use Lua
script to set up some game related parameter value.
First, let's look at the simple Lua function defined in the
file Monster.lua.
As is seen, the above script is also simple – setting up related values for each interested property. As
for the Java class Monster, it is also simple enough, as follows:
Note we've called the above method create passing the special property this
of the class Monster as the only parameter. Now, let's continue to look into the helper class Load
related code.
As is shown, the class Load serves as a helper class that can encapsulate the general
operations with various kinds of Lua objects. First, in the constructor, we load the .lua file via Java I/O technique
and then by calling the method LdoString we succeed in setting up the Lua VM and load the related script.
Next, in the method run we invoke the target Lua function by passing in only one parameter and returning
nothing. In fact, on ground of this rough class, you can build your own more practical and powerful helper classes that
encapsulate most of your game target's operations.
Finally, let's look at the main Java game code.
Just for conceptual illustration, the above code is very simple. Here, we constructed an instance of the
class Monster and finally output the value of its property Race- all the Lua related stuff
are hidden with the preceding helper class Load. That's all!
Figure 2 below gives the final
running-result of this example.
Figure 2: The simple Lua based Android game app output

Example 6- Use Lua with libgdx
As you may have known, libgdx is a high-performance, cross-platform Java 2D&3D game development framework targeting
the solid foundation for engines and games that can run on Windows, Linux, OSX and Android platforms. In this section,
I am going to simply introduce to you a hello-world level example which can show how to piece libgdx and Lua together
to construct a more powerful Android game. This sample is given at this url (http://code.google.com/p/libgdx-users/wiki/LuaTutorial).
As the
tutorial emphasized, to follow up the experiment you should first download the game engine libgdx from the url given at
the beginning of this article and make other related preparations. Since the above material is an open-sourced article,
I below will briefly summarize the overall realization of the project idea. By the way, for your convenience, I also
built a similar project in the downloadable source code package.
1. Create the project sketch
(1) Start up Eclipse to create an Android application named FirstLibGdxAndroidApp.
(2) Copy all LuaJava
related .java files into the src folder.
(3) Copy the libgdx related stuff to the proper position
in the project. To do this, create a sub folder named libs under which you should at least copy
gdx.jar, gdx-backend-android.jar, and two folders - armeabi and armeabi-
v7a (there are two required libraries, libandroidgl20.so and libgdx.so) from the
libgdx unzipped package.
(4). Add references to the .jar files. To do this, right click the project and select
Properties to open the Properties dialog. Then, in the Libraries tab hit the
'Add JARs...' button to add the above two .jar files in the libs folder.
(5) Copy the library
libluajava.so to the two folders armeabi and armeabi-v7a respectively. With
this file, we can achieve the Lua virtual engine support inside the Android Java environment.
2. Sample coding
First, create the main game class named AndroidGame that extends the class
AndroidApplication. This class mainly serves as the main entrance of the sample game. In fact, the real
interesting work is finished in another class Game below. The related code is as follows:
Now, let's create another class named Game that implements the interface
ApplicationListener (which is provided in libgdx).
Here, we ignore all the libgdx related explanation, but show interest in the helper class
LoadScript. In this case, the idea is load the .lua file(s) using Lua VM (all of which has been
encapsulated inside the constructor LoadScript in the class LoadScript) in the create
method. Then, in the render method invoke the related script method (via the
runScriptFunction method of the class LoadScript) to trigger some corresponding script-
targeting function.
Now, let's look at the core class LoadScript related programming:
With the previous example viewed, the core part of the above class should be the bold lines. And further,
the real nut lies in the code handle.readString. It's quite similar to that covered in the above Sample 5,
isn't it?
For more details, readers can refer to the url mentioned at the beginning of this article and the
similar project in the downloadable package.
Summary
In this article, you may have noticed although LuaJava has encapsulated most of the Lua VM manipulations on the Java
code side, there are still more waiting for your further exploration, such as familiarizing yourself with each LuaJava
API, putting LuaJava in your real game practice. To be honest, to fully master Android Java and Lua mixing programming
you should first bear a better understanding with the C API programming between C/C++ and Lua. On the whole, Lua is not
as easy as you may initially image. But once you grasp this tool it will help a great deal in most of your
games.
The last word is: although I've not provided most of the samples related running-time snapshots, all the
related examples in this article have indeed been test OK! Happy Android Java and Lua mixed programming!
About Xianzhong Zhu
 |
I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...
This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.
|
Please login to rate or to leave a comment.