LoginSignup
3

More than 3 years have passed since last update.

android(java)でluaJを使った電卓を作る

Last updated at Posted at 2019-06-23

前書き

hotmanです
通常電卓やプログラミング言語を処理するには構文解析する必要がありますが、luaJ等のインタプリタのライブラリを使えば、そいつが勝手に構文解析&実行してくれます
つまりは大幅な作業コストのカットになります
ではやり方の説明

luaJの導入

luaJダウンロードページからluaJを落としてきまして、解凍すると中にあるluaj-jse-3.0.1.jarを(プロジェクトフォルダー)/libsにぶちこんでやるぜ

activity_main.xml

今回作るのは電卓なので入力スペースと出力スペースを用意します

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:inputType="text"
        android:text=""
        android:textSize="50sp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text=""
        android:textSize="100sp" />
</LinearLayout>

MainActivity.java

luaJ使うだけ、
ちなみに
globals.load(text).call()
textをluaコードとして実行
globals.set(text,val)
textの変数名にvalを代入
globals.gat(text)
textの変数名に入っている値を取得
です

MainActivity.java
package com.test.gameeditor;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.luaj.vm2.*;
import org.luaj.vm2.lib.jse.*;
import android.widget.*;
import android.view.*;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Globals globals = JsePlatform.standardGlobals();
        final EditText et=findViewById(R.id.editText);
        final TextView tv=findViewById(R.id.textView);
        tv.setText("0");
        globals.set("x",0);
        et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                LuaValue chunk = globals.load("x="+et.getText().toString()).call();
                tv.setText(Integer.toString(globals.get("x").toint()));
                return false;
            }
        });
    }
}

むしろ前回のandoridでアニメーションより簡単まである

以上

あとがき

lua+javaは最高
エラーハンドリングがないのは仕様です


Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3