Skip to content
A scripting system which makes the Java classes available in Lua scripts. This is a read-only mirror of the GitLab repository.
Java HTML
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.settings
examples
libs Fixed incorrect filename. Nov 15, 2019
src/org/bonsaimind/jluascript Added missing documentation. Jan 26, 2020
test/org/bonsaimind/jluascript
.classpath
.gitignore
.project
CHANGES
CONTRIBUTE
LICENSE Initial commit. Aug 6, 2018
README
build.xml
code-formatter.xml Initial commit. Aug 6, 2018

README

jLuaScript
==========

jLuaScript allows to to write Lua scripts which have full access and control of
Java classes. It utilizes LuaJ for executing Lua code. The idea is to be able
to write Lua scripts which have complete access to the Java ecosystem and can
use the Java classes and instances with a simple syntax.

A similar project is [jLua](https://github.com/nirhal/JLua), which is using
a different syntax for accessing the Java classes and also uses
a native-compiled Lua engine.


License
-------

jLuaScript is licensed under LGPLv3.


Dependencies
------------

Please see the attached license files for details.

 * [BCEL](https://commons.apache.org/proper/commons-bcel/), Apache
 * [javassist](https://www.javassist.org/), Mozilla Public License
 * [LuaJ](https://sourceforge.net/projects/luaj/), BSD-like


Usage
-----

The scripts executed by jLuaScript are Lua scripts which have all
the capabilities of Lua scripts but also can access the whole Java ecosystem.

Even though an `import`-like function is used to define classes, it is not
necessary to import all implicitly used classes, only those which are used
explicitly.

Before a static instance of a class can be used, it must either be loaded or
imported. Afterwards the static functions can be accessed through dot syntax.
A new instance can be created through the static "new" function. Instance
methods can be accessed with the colon syntax.

### Global Functions

#### loadClass(String)

`loadClass(String)` allows to load a single, static instance of the given class.

    local Paths = loadClass("java.nio.file.Paths")
    local path = Paths.get("/etc", "apt", "sources.list");

#### loadJar(String...)

`loadJar(String...)` allows to add a single jar to the classpath which is being
used by the environment. It accepts String varargs for the single path elements,

    loadJar("/opt", "someapp", "lib", "somelib.jar")
    
    import("com.somelib.Function")
    
    Function.execute()

#### import(String)

`import(String)` loads and imports a single, static instance of the given class.
The static instance is set as global variables with the name of the class, and
also the fully qualified name is being made available.

    import("java.nio.file.Paths")
    
    local path = Paths.get("/etc", "apt", "sources.list");
    local path = java.nio.file.Paths.get("/etc", "apt", "sources.list");

`import(String)` does also return the static instance which just has been
imported.

    local P = import("java.nio.file.Paths");
    
    local path = P.get("/etc", "apt", "sources.list");

Note that jars must be loaded before the classes can be imported and that
the order of functions is important because the classpath is extended
dynamically.

### Global variables

#### ARGS

A table which holds all arguments for the script. Can be empty if there are
none.

#### CWD

The current working directory, as it exists in the process environment.

#### DIR

The current working directory, as it exists in the process environment.

#### HOME

The home directory of the user, as it exists in the process environment.

#### SCRIPT_DIR

A global String variable which contains the directory of the currently being
executed script, absolute and platform-specific. Can be nil if no file is being
executed.

#### SCRIPT_FILE

A global String variable which contains the file of the currently being executed
script, absolute and platform-specific. Can be nil if no file is being executed.

#### WORKING_DIR

The current working directory, as it exists in the process environment.

### Extended String

The global `string` value has been extended with the following Java functions:

 * charAt
 * concat
 * contains
 * contentEquals
 * endsWith
 * equalsIgnoreCase
 * indexOf
 * isEmpty
 * lastIndexOf
 * length
 * matches
 * replace
 * replaceAll
 * replaceFirst
 * split
 * startsWith
 * substring
 * toLowerCase
 * toUpperCase
 * trim

### Embedding

jLuaScript can be run stand-alone and execute given scripts, or it can be
embedded into your application.

The main class is the `LuaEnvironment`, it allows you to execute files and
scripts directly from a `String`.

    LuaEnvironment environment = new LuaEnvironment();
    
    try {
        environment.execute("print(\"Hello World!\")");
    } catch(ScriptExecutionException e) {
        e.printStackTrace();
    }

You can also access returned values from the script:

    LuaEnvironment environment = new LuaEnvironment();
    
    try {
        String value = environment.execute("return \"abc\"");
    } catch(ScriptExecutionException e) {
        e.printStackTrace();
    }

If you need to limit the available functionality, you have two options:

 1. You override `LuaEnvironment.loadDefaultLibraries` and only load
    the functionality you want to have available.
 2. You use a custom SecurityManager which limits what classes can be accessed.

Even though `LuaEnvironment` provides you with a way to set a classloader, you
might need to load it already in a confined environment.


Examples
--------

See the "examples" directory and the unit tests for further examples.

The classic "Hello World!" example.

    -- Note that System is one of the classes which are imported by default.
    System.out:println("Hello World!")

Working with BigDecimals.

    import("java.math.BigDecimal")
    
    local valueA = BigDecimal.new("1.02")
    local valueB = BigDecimal.new("5.44")
    local result = valueA:add(valueB)
    
    System.out:println(result:toString())

One can also access additional jars, for example EvalEx.

    loadJar(SCRIPT_DIR, "evalex.jar")
    
    import("java.math.BigDecimal")
    import("com.udojava.evalex.Expression")
    
    local expression = Expression.new("1 + sqrt(17) * 5.433839 + a")
    expression:with("a", BigDecimal.new("3.77722"))
    
    local result = expression:eval()
    
    System.out:println(result)

Implementing an interface:

    import("java.lng.Runnable")
    
    local RunnableImpl = Runnable.implement({
        run = function()
            -- Put logic here.
        end
    })
    
    local runnableInstance = RunnableImpl.new()
    
    runnableInstance:run()

### Using as a lib

The environment can also be called from other applications:

    LuaEnvironment environment = new LuaEnvironment();
    
    // Add a default import.
    environment.importClass(SomeImportantClass.class);
    
    // Add a global variable, given object is a Java object.
    environment.addToEnvironment("someObject", someObject);
    
    // Execute the actual script from a String.
    Object returnedValue = environment.execute(script);
You can’t perform that action at this time.