探究 lua 在 Android 中的应用

5,306 阅读1分钟

根据前面的文章 Android 与 Lua 可以大概了解 Lua 。在 Android(移动设备)中,可以通过灵活加载 Lua 脚本,使应用更加灵活,轻松面对多变的需求。luajava 在 jni 层主要实现了5个方法,借助这5个方法lua几乎可以使用所有的java类了。

Java 和 lua 交互

关于 java 和 lua 交互的大概有两个项目。 一个是 luajava,通过 java 的 jni 功能,java 与 c 交互,然后 c 调用 lua ,延伸出来的有 AndroLua。还有在 Android 平台的 lua 编辑器 AndroLua+,用来开发 Android。

还有一个 luaj,纯 java 实现的 Lua 解释器,基于 Lua 5.2.x。前面介绍的 LuaSdkView 就是基于 luaj 修改的。在 lua 调用任意 java 类方面,LuaSdkView 实现了一些通用的类来创建java对象,调用方法。

接下来看 luaj 的具体使用。

java 调用 lua

hello.lua 文件

print '----hello.lua---'

function sum( num1, num2 )
    return num1 + num2
end

function getName()
    return 'hanks'
end

Test.java 文件


// 加载 lua 文件
Globals G = JsePlatform.standardGlobals();
LuaValue scriptValue = G.load("print 'hello, world'");
scriptValue.call();// 打印出 hello, world

G.get("dofile").call(LuaValue.valueOf("hello.lua")); // 打印出 ----hello.lua---

LuaValue sumFuc = G.get("sum");
LuaValue sum = sumFuc.call(LuaValue.valueOf(5), LuaValue.valueOf(3));
System.out.println(sum.toint()); // 打印出 8

LuaValue getNameFun = G.get("getName");
LuaValue name = getNameFun.call();
System.out.println(name.tojstring());  // 打印出 hanks

lua 调用 java

直接调用

local Thread = luajava.bindClass('java.lang.Thread')
print(Thread) // 打印 class java.lang.Thread

定义 hyperbolic.java

public class hyperbolic extends TwoArgFunction {

    public hyperbolic() {
    }

    public LuaValue call(LuaValue modname, LuaValue env) {
        LuaValue library = tableOf();
        library.set("sinh", new sinh());
        library.set("cosh", new cosh());
        env.set("hyperbolic", library);
        return library;
    }

    static class sinh extends OneArgFunction {
        public LuaValue call(LuaValue x) {
            return LuaValue.valueOf(Math.sinh(x.checkdouble()));
        }
    }

    static class cosh extends OneArgFunction {
        public LuaValue call(LuaValue x) {
            return LuaValue.valueOf(Math.cosh(x.checkdouble()));
        }
    }
}

testhyperbolic.lua 进行调用

require 'hyperbolic'

print('hyperbolic', hyperbolic)
print('hyperbolic.sinh', hyperbolic.sinh)
print('hyperbolic.cosh', hyperbolic.cosh)

print('sinh(0.5)', hyperbolic.sinh(0.5))
print('cosh(0.5)', hyperbolic.cosh(0.5))

Globals globals = JsePlatform.standardGlobals();
globals.loadfile("testhyperbolic.lua").call();

/* 打印
hyperbolic  table: 61e717c2
hyperbolic.sinh function: sinh
hyperbolic.cosh function: cosh
sinh(0.5)   0.5210953
cosh(0.5)   1.127626
*/

文章来自: hanks.pub