LuaJava
A Script Tool for Java

Examples

Hello World using LuaJava

This example is a simple Hello World application using LuaJava printing both from Lua and Java.

Hello.java

public class Hello
{
  public static void main(String[] args)
  {
    LuaState L = LuaStateFactory.newLuaState();
    L.openLibs();
    
    L.LdoFile("hello.lua");
    
    System.out.println("Hello World from Java!");
  }
}

hello.lua

print("Hello World from Lua!")

Accessing a DataBase

This example uses Java JDBC to access a database from Lua.

TestJDBC.java

public class TestJDBC
{
  
  public static void main(String[] args) throws Exception
  {
    // gets a java.sql.Connection and creates a Statement

    Class.forName("org.hsqldb.jdbcDriver");
    Connection con = DriverManager.getConnection(
	                    "jdbc:hsqldb:hsql://localhost:9002",
	                    "sa", "");
    Statement st = con.createStatement();
    
    try
    {
      st.execute("DROP TABLE luatest");
    }
    catch (Exception ignore) {}
    
    st.execute([[CREATE TABLE luatest 
               (id int not null primary key, 
               str varchar, number double)]]);
    
    for(int i = 0 ; i < 10 ; i++)
    {
      st.executeUpdate(
          "INSERT INTO luatest (id, str, number) values(" + 
          i + ", '" + 2*i + "', " + 
          System.currentTimeMillis() + ")");
    }
    
    // creates a Lua State and register the basic libraries
    
    LuaState L = LuaStateFactory.newLuaState();
    L.openLibs();
    
    // registers the statement in the global 'st'
    
    L.pushObjectValue(st);
    L.setGlobal("st");
    
    // execute file testJDBC.lua
    
    int err = L.LdoFile("testJDBC.lua");

    L.close();
    st.close();
    con.close();
  }
}

testJDBC.lua

do
-- tests if object Statement is nil
if st == nil then
    print("Error. st object is nil")
    return
end

local st = st
_G.st = nil

function createSQLProxy(t)

    local tableName = t
    
    local function i (t,k)
    
        local id = tonumber(k)
        if not id then
            return nil
        end
        
        local function mi (t,k)
        
            local sql = "select "..k.." from "..
                        tableName.." where id="..id
            local rs = st:executeQuery(sql)
            if not rs:next() then
                rs:close()
                return nil
            end
            
            local res = rs:getString(1)
            rs:close()
            
            return res
        end
        
        local res = {}
        setmetatable(res, {__index = mi})
        return res
    end
    
    local res = {}
    setmetatable(res, {__index = i })
    return res
end

end


proxy = createSQLProxy("luatest")

print(proxy[1].str)
print(proxy[1].number)

Valid XHTML 1.0!

$Id: examples.html,v 1.17 2007/01/23 22:37:28 thiago Exp $