LuaJava
Ferramenta de scripts para Java

Exemplos

"Olá Mundo" usando LuaJava

Este exemplo é um aplicativo simples "Olá Mundo" que usa o LuaJava para imprimir de Lua e 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("Olá Mundo de Java!");
  }
}

hello.lua

print("Olá Mundo de Lua!")

Acesso a um banco de dados

Este exemplo usa Java JDBC para acessar um banco de dados a partir de Lua.

TestJDBC.java

public class TestJDBC
{
  
  public static void main(String[] args) throws Exception
  {
    // obtém uma java.sql.Connection e cria um 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() + ")");
    }
    
    // cria um estado Lua e registra as bibliotecas básicas
    
    LuaState L = LuaStateFactory.newLuaState();
    L.openLibs();
    
    // registra a instrução no 'st' global
    
    L.pushObjectValue(st);
    L.setGlobal("st");
    
    // executa o arquivo testJDBC.lua
    
    int err = L.LdoFile("testJDBC.lua");

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

testJDBC.lua

do
-- testa se o Statement é nil
if st == nil then
    print("Erro. Objeto st é 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 = mi})
    return res
end

end


proxy = createSQLProxy("luatest")

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

Valid XHTML 1.0!

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