android执行lua脚本的方法

在android studio的 build.gradle里面加入luaj-android的依赖

compile group: 'com.reizx', name: 'luaj-android', version: '3.0.3'

下面是一个测试类

package com.test.luatest;

import org.junit.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.jse.JsePlatform;

public class LuaTest {
    @Test
    public void Test1() {
        String s = "";//lua脚本
        s += "x=3\r\n";
        s += "y=4\r\n";
        s += "print ('hello world!')\r\n";
        s += "function aa()\r\n";
        s += "print ('aaa')\r\n";
        s += "end\r\n";
        s += "aa()\r\n";
        s += "c=method1(x)\r\n";
        s += "d=test.method2(x,y)\r\n";
        s += "print (x..'π='..c)\r\n";
        s += "print ('x*y='..d)\r\n";

        Globals globals = JsePlatform.standardGlobals();//初始化lua
        globals.load(new TestMethod());//注入方法
        LuaValue chunk = globals.load(s);//加载自己写的脚本
        chunk.call();//执行脚本
        String d = globals.get("d").toString();//取得脚本里的变量d的值
        System.out.println("d:" + d);
    }

    public class TestMethod extends TwoArgFunction {
        /**
         * The implementation of the TwoArgFunction interface.
         * This will be called once when the library is loaded via require().
         *
         * @param modname LuaString containing the name used in the call to require().
         * @param env     LuaValue containing the environment for this function.
         * @return Value that will be returned in the require() call.  In this case,
         * it is the library itself.
         */
        public LuaValue call(LuaValue modname, LuaValue env) {
            //调用方式1 method1(x)
            env.set("method1", new Method1());
            env.set("method2", new Method2());

            //调用方式2 test.method1(x)
            LuaValue library = tableOf();
            library.set("method1", new Method1());
            library.set("method2", new Method2());
            env.set("test", library);
            return null;
        }

        //一个参数的方法
        class Method1 extends OneArgFunction {
            public LuaValue call(LuaValue x) {
                return LuaValue.valueOf(Math.PI * x.checkint());
            }
        }

        //两个参数的方法
        class Method2 extends TwoArgFunction {
            public LuaValue call(LuaValue x, LuaValue y) {
                return LuaValue.valueOf(x.checkint() * y.checkint());
            }
        }
    }
}

执行测试后,输出的内容如下

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值