11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 BlakeQu
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidLuaExample
2 | update to Lua 5.3.3 and LuaJava ported to Android example
3 |
4 | [![License][licence_svg]][licence_url]
5 | [![Download][bintray_svg]][bintray_url]
6 |
7 | # Import
8 | add to build.gradle,${latest.version} is [![Download][bintray_svg]][bintray_url]
9 | ```
10 | dependencies {
11 | compile 'com.blakequ.luajava:luajava:${latest.version}'
12 | }
13 | ```
14 | maven
15 | ```
16 |
17 | com.blakequ.luajava
18 | luajava
19 | ${latest.version}
20 | pom
21 |
22 | ```
23 |
24 |
25 | # How to use
26 | you can download example and study how to use.
27 | add proguard rules
28 | ```
29 | # luajava
30 | -keep class org.keplerproject.luajava.**{*;}
31 | # For native methods
32 | -keepclasseswithmembernames class * {
33 | native ;
34 | }
35 | ```
36 |
37 | ## 1. init lua
38 |
39 | init lua file only once after start app
40 | ```
41 | private void initLua(){
42 | mLuaState = LuaStateFactory.newLuaState();
43 | mLuaState.openLibs();
44 | //push Log object to lua, in lua using like: Log:i(TAG, "this log can show in AS logcat window")
45 | try {
46 | mLuaState.pushObjectValue(Log.class);
47 | mLuaState.setGlobal("Log");
48 | } catch (LuaException e1) {
49 | // TODO Auto-generated catch block
50 | e1.printStackTrace();
51 | }
52 | }
53 | ```
54 |
55 | ## 2. add lua file to raw
56 | ```
57 | app/src/main/res/raw/luafile.lua
58 |
59 | function GetVersion(info, intvalue)
60 | Log:i("LuaLog", info..intvalue)
61 | print('this log')
62 | return 1
63 | end
64 | ```
65 |
66 | ## 3. invoke lua function
67 | ```
68 | private void executeLuaFile()
69 | {
70 | mLuaState.getGlobal("GetVersion");
71 | mLuaState.pushString("reload lua test");// input params
72 | mLuaState.pushNumber(10);
73 | mLuaState.call(2, 1);//2 input, 1 output
74 | String result = mLuaState.toString(-1);
75 | if (result == null){
76 | System.out.println("GetVersion return empty value");
77 | }else {
78 | System.out.println("GetVersion return value"+result);
79 | }
80 | }
81 | ```
82 |
83 | ## 4. invoke lua and error handle
84 | ```
85 | private void executeLuaFile2()
86 | {
87 | //in lua file not exist this method:GetNotMethod
88 | mLuaState.getGlobal("GetNotMethod");
89 | mLuaState.pushString("reload lua test");// input params
90 | mLuaState.pushNumber(10);//not use pushInteger
91 | //if using call will throw exception(can not catch), so you must use pcall
92 | //success to invoke method if return 0, otherwise is error.
93 | int retCode = mLuaState.pcall(2, 1, -1);//2 input, 1 output
94 | String result = mLuaState.toString(-1);
95 | if (retCode != 0){
96 | LogUtils.e(TAG, "Fail to invoke GetNotMethod by lua errorCode:"+retCode+" errorMsg:"+result);
97 | }else {
98 | if (result == null){
99 | System.out.println("GetVersion return empty value");
100 | }else {
101 | System.out.println("GetVersion return value"+result);
102 | }
103 | }
104 | }
105 | ```
106 |
107 | # Link
108 | - [AndroLua-mkottman](https://github.com/mkottman/AndroLua)
109 | - [AndroLua-new](https://github.com/lendylongli/AndroLua)
110 | - [LuaScriptCore](https://github.com/vimfung/LuaScriptCore)
111 |
112 |
113 | [bintray_svg]: https://api.bintray.com/packages/haodynasty/maven/AndroidLua/images/download.svg
114 | [bintray_url]: https://bintray.com/haodynasty/maven/AndroidLua/_latestVersion
115 | [licence_svg]: https://img.shields.io/badge/license-Apache%202-green.svg
116 | [licence_url]: https://www.apache.org/licenses/LICENSE-2.0
117 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion '25.0.0'
6 | defaultConfig {
7 | applicationId "com.plusub.androidluaexample"
8 | minSdkVersion 18
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | signingConfig signingConfigs.debug
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | tasks.withType(JavaCompile) {
23 | options.encoding = "UTF-8"
24 | }
25 |
26 | dependencies {
27 | // compile fileTree(dir: 'libs', include: ['*.jar'])
28 | // compile project(':luajava')
29 | compile 'com.blakequ.luajava:luajava:1.0'
30 | compile 'com.android.support:appcompat-v7:25.0.0'
31 | }
32 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\studio_sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # luajava
20 | -keep class org.keplerproject.luajava{*;}
21 | # For native methods
22 | -keepclasseswithmembernames class * {
23 | native ;
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/plusub/androidluaexample/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.plusub.androidluaexample;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
10 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/assets/ObjectAlgorithm.lua:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/assets/ObjectAlgorithm.lua
--------------------------------------------------------------------------------
/app/src/main/java/com/plusub/androidluaexample/StringUtils.java:
--------------------------------------------------------------------------------
1 | package com.plusub.androidluaexample;
2 |
3 | /**
4 | * Copyright (C) BlakeQu All Rights Reserved
5 | *
6 | * Licensed under the blakequ.com License, Version 1.0 (the "License");
7 | * Unless required by applicable law or agreed to in writing, software
8 | * distributed under the License is distributed on an "AS IS" BASIS,
9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 | * See the License for the specific language governing permissions and
11 | * limitations under the License.
12 | *
13 | * author : quhao
14 | * date : 2017/2/15 14:57
15 | * last modify author :
16 | * version : 1.0
17 | * description:
18 | */
19 |
20 | public class StringUtils {
21 |
22 | public static boolean isEmpty(String str){
23 | if (str == null || str.length() == 0) return true;
24 | return false;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_jnitest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
19 |
20 |
26 |
27 |
33 |
34 |
40 |
41 |
46 |
47 |
52 |
53 |
59 |
60 |
61 |
62 |
63 |
71 |
72 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/raw/hello.lua:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/app/src/main/res/raw/hello.lua
--------------------------------------------------------------------------------
/app/src/main/res/raw/luafile.lua:
--------------------------------------------------------------------------------
1 | --
2 | -- Created by IntelliJ IDEA.
3 | -- User: PLUSUB
4 | -- Date: 2015/10/16
5 | -- Time: 11:09
6 | -- To change this template use File | Settings | File Templates.
7 | --
8 | str = "are you china"
9 | VERSION = 1
10 | function functionInLuaFile(key)
11 | --print log
12 | Log:i("LuaLog", "over setcontent")
13 | return ' Function in Lua file . Return : '..key..'!'..str
14 | end
15 |
16 | function callAndroidApi(context,layout,tip)
17 | tv = luajava.newInstance("android.widget.TextView",context)
18 | tv:setText(tip)
19 | layout:addView(tv)
20 | end
21 |
22 | function reloadMethod(self, info)
23 | Log:i("LuaLog", "method origial "..info)
24 | return ' Function in Lua file.' ..info
25 | end
26 |
27 | function GetVersion(info, intvalue)
28 | Log:i("LuaLog", info..intvalue)
29 | -- 测试返回值,调用时mLuaState.call(1, 1);在这里可以是下面4中情况
30 | -- return nil
31 | -- return
32 | -- 没有return也没有影响
33 | return VERSION
34 | end
35 |
36 | -- 错误处理测试
37 | function testErrorHandler()
38 | Log:i("LuaLog", '----xpcall有错误---')
39 | -- xpcall接收第二个参数——一个错误处理函数,当错误发生时,Lua会在调用桟展看(unwind)前调用错误处理函数,于是就可以在这个函数中使用debug库来获取关于错误的额外信息了
40 | status = xpcall(myfunction, myerrorhandler)
41 | Log:i("LuaLog", '----xpcall无错误带返回值---')
42 | -- 返回三个参数:状态,返回值,错误,xpcall (f, msgh [, arg1, ···])这个传入参数arg1需要5.2以上才能支持http://stackoverflow.com/questions/30125726/how-to-use-xpcall-with-a-function-which-has-parameters
43 | status1, ret, err = xpcall(myfunction3, myerrorhandler, 5, 6)
44 | -- 5.2以下版本不能传入参数,只能用函数包装参数
45 | -- status1, ret, err = xpcall(myfunction4, myerrorhandler)
46 | Log:i("LuaLog", 'myfunction3 result '..(status1 and "true" or "false"))
47 | if ret ~= nil then
48 | Log:i("LuaLog", 'myfunction3 ret '..ret)
49 | end
50 | if err ~= nil then
51 | Log:i("LuaLog", 'myfunction3 err '..err)
52 | end
53 |
54 | Log:i("LuaLog", '----pcall---')
55 | -- pcall接收一个函数和要传递个后者的参数,并执行,执行结果:有错误、无错误;返回值true或者或false, errorinfo。
56 | status, err = pcall(testPcall, 33)
57 | -- status, err = pcall(function(i) testPcall(i) end, 33)
58 | -- if pcall(function(i) testPcall(i) end, 33) then
59 | if status == true then
60 | -- 没有错误
61 | Log:i("LuaLog", 'test right')
62 | else
63 | -- 一些错误
64 | Log:e("LuaLog", 'test error== '..err)
65 | end
66 | Log:i("LuaLog", '----end---')
67 | end
68 |
69 | function myfunction ()
70 | -- n = n/nil
71 | myfunction2()
72 | end
73 |
74 | function myfunction2 ()
75 | -- 位运算
76 | n = 1024>>2
77 | Log:i("LuaLog", 'bit value1:'..n)
78 | n = 1024|2
79 | Log:i("LuaLog", 'bit value2:'..n)
80 | n = 1024~2
81 | Log:i("LuaLog", 'bit value3:'..n)
82 | n = 1024&0
83 | Log:i("LuaLog", 'bit value4:'..n)
84 | n = ~1
85 | Log:i("LuaLog", 'bit value5:'..n)
86 | -- 异常抛出
87 | n = n/nil
88 | end
89 |
90 | -- 5.2以上才能带参数
91 | function myfunction3(a, b)
92 | if a ~= nil and b ~= nil then
93 | Log:i("LuaLog", 'myfunction3 value is a:'..a..' b:'..b)
94 | return a + b
95 | end
96 | return 0
97 | end
98 | -- 5.1以下要传参需要无参数
99 | function myfunction4()
100 | n = n/nil
101 | myfunction3(1,3)
102 | end
103 |
104 | function myerrorhandler( err )
105 | Log:i("LuaLog", "ERROR:"..err..'\n'..debug.traceback("Stack trace"))
106 | end
107 |
108 | function testPcall(i)
109 | print(i)
110 | n = n/nil
111 | error('error..11 ')
112 | end
113 |
114 |
--------------------------------------------------------------------------------
/app/src/main/res/raw/luafile1.lua:
--------------------------------------------------------------------------------
1 | --
2 | -- Created by IntelliJ IDEA.
3 | -- User: PLUSUB
4 | -- Date: 2015/10/16
5 | -- Time: 11:09
6 | -- To change this template use File | Settings | File Templates.
7 | --
8 | str = "are you china"
9 | function functionInLuaFile(key)
10 | --print log
11 | Log:i("LuaLog", "reload lua file")
12 | return ' Function in Lua file222222 . Return : '..key..'!'..str
13 | end
14 |
15 |
16 | function callAndroidApi(context,layout,tip)
17 | tv = luajava.newInstance("android.widget.TextView",context)
18 | tv:setText(tip)
19 | layout:addView(tv)
20 | end
21 |
22 | function reloadMethod(self, info)
23 | Log:i("LuaLog", "method reload "..info)
24 | return ' Function in reload Lua file.' ..info
25 | end
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidLuaExample
3 |
4 | Hello world!
5 | Settings
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | def getLocalProperty(String key) {
3 | if (!localPropertiesFile().exists()) {
4 | return null
5 | }
6 |
7 | Properties properties = new Properties()
8 | properties.load(localPropertiesFile().newDataInputStream())
9 | return properties.getProperty(key)
10 | }
11 |
12 | def localPropertiesFile() {
13 | return project.rootProject.file('local.properties');
14 | }
15 |
16 | def isForUpload2Maven() {
17 | return getLocalProperty("for.upload") == "true"
18 | }
19 |
20 | //获取当前时间
21 | def releaseTime() {
22 | return new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC"))
23 | }
24 |
25 | buildscript {
26 | repositories {
27 | jcenter()
28 | maven {
29 | url "https://plugins.gradle.org/m2/"
30 | }
31 | }
32 | dependencies {
33 | classpath 'com.android.tools.build:gradle:2.3.0'
34 |
35 | // NOTE: Do not place your application dependencies here; they belong
36 | // in the individual module build.gradle files
37 | //using for upload to bintray lib
38 | File file = project.rootProject.file('local.properties')
39 | if (file.exists()) {
40 | Properties properties = new Properties()
41 | properties.load(file.newDataInputStream())
42 | boolean upload2maven = properties.getProperty("for.upload") == "true"
43 | if (upload2maven) {
44 | println ':global:include upload 2 maven classpath'
45 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
46 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
47 | classpath "gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.13.1"
48 | }
49 | }
50 | }
51 | }
52 |
53 | allprojects {
54 | repositories {
55 | jcenter()
56 | }
57 | }
58 |
59 | task clean(type: Delete) {
60 | delete rootProject.buildDir
61 | }
62 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # Android configuration
21 | COMPILE_SDK_VERSION=android-25
22 | BUILD_TOOLS_VERSION=25.0.0
23 | MIN_SDK_VERSION=18
24 | TARGET_SDK_VERSION = 23
25 |
26 | # Dependency versions
27 | SUPPORT_LIBRARY_VERSION=25.0.0
28 |
29 | # bintray
30 | GROUP=com.blakequ.luajava
31 | VERSION_CODE=1
32 | VERSION_NAME=1.0
33 | ARTIFACT_NAME=AndroidLua
34 | SITE_URL=https://github.com/haodynasty/AndroidLuaExample
35 | ISSUE_URL=https://github.com/haodynasty/AndroidLuaExample/issues
36 | SCM_URL=https://github.com/haodynasty/AndroidLuaExample.git
37 | ARTIFACT_DESCRIPTION=android lua bridge
38 | ISSUE_SYSTEM=github
39 | SCM_CONNECTION=scm:git@github.com:haodynasty/AndroidLuaExample.git
40 | SCM_DEV_CONNECTION=scm:git@github.com:haodynasty/AndroidLuaExample.git
41 | LICENCE_DIST=repo
42 | LICENCE_NAME=The Apache Software License, Version 2.0
43 | LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
44 | DEVELOPER_ID=haodynasty
45 | DEVELOPER_NAME=Blakequ
46 | DEVELOPER_EMAIL=blakequ@gmail.com
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haodynasty/AndroidLuaExample/f51699da7c2a07e8c7ddc4ebb3fd29a5cccf0f45/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Feb 17 15:03:15 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/luajava/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/luajava/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion COMPILE_SDK_VERSION
5 | buildToolsVersion BUILD_TOOLS_VERSION as String
6 |
7 | defaultConfig {
8 | minSdkVersion MIN_SDK_VERSION
9 | targetSdkVersion TARGET_SDK_VERSION
10 | versionCode VERSION_CODE as int
11 | versionName VERSION_NAME as String
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | //屏蔽gradle检测到c自己调用jni
23 | //http://www.liuling123.com/2016/05/android-studio-gradle-ndk-config.html
24 | sourceSets {
25 | main {
26 | jni.srcDirs = [] //屏蔽gradle的jni生成过程
27 | jniLibs.srcDirs = ['src/main/jniLibs']//设置目标的so存放路径
28 | }
29 | }
30 |
31 | }
32 |
33 | //Compile JNI source via NDK
34 | task ndkBuild(type: Exec) {
35 | // def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
36 | def ndkDir = android.ndkDirectory
37 | //注:在mac下使用ndk-build ,在win下使用ndk-build.cmd
38 | //notice: in mac use /ndk-build , in win use /ndk-build.cmd
39 | commandLine "$ndkDir/ndk-build.cmd", '-C', 'src/main/jni',
40 | "NDK_OUT=$buildDir/ndk/obj",
41 | "NDK_APP_DST_DIR=$buildDir/ndk/libs/\$(TARGET_ARCH_ABI)"
42 | }
43 |
44 | task copyJniLibs(type: Copy, dependsOn:['ndkBuild']) {
45 | from fileTree(dir: file(buildDir.absolutePath + '/ndk/libs'), include: '**/*.so')
46 | into file('src/main/jniLibs')
47 | }
48 |
49 | tasks.withType(JavaCompile) {
50 | compileTask -> compileTask.dependsOn 'ndkBuild','copyJniLibs'
51 | }
52 |
53 | task cleanNative(type: Exec, description: 'Clean JNI object files') {
54 | def ndkDir = android.ndkDirectory
55 | commandLine "$ndkDir/ndk-build.cmd",
56 | '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
57 | 'clean'
58 | }
59 |
60 | clean.dependsOn 'cleanNative'
61 |
62 | dependencies {
63 | compile fileTree(dir: 'libs', include: ['*.jar'])
64 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
65 | exclude group: 'com.android.support', module: 'support-annotations'
66 | })
67 | compile 'com.android.support:appcompat-v7:25.0.0'
68 | testCompile 'junit:junit:4.12'
69 | }
70 |
71 | //执行bintrayUpload之前必须执行gradlew install生成poms文件(build/poms)
72 | if (isForUpload2Maven()) {
73 | println ':library:include upload 2 maven methods'
74 | apply from: 'https://raw.githubusercontent.com/haodynasty/JCenter/master/installv1.gradle'
75 | apply from: 'https://raw.githubusercontent.com/haodynasty/JCenter/master/bintrayv1.gradle'
76 | apply from: 'https://raw.githubusercontent.com/haodynasty/JCenter/master/license.gradle'
77 | }
78 |
--------------------------------------------------------------------------------
/luajava/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\studio_sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/luajava/src/androidTest/java/org/keplerproject/luajava/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package org.keplerproject.luajava;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("org.keplerproject.luajava.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/luajava/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/CPtr.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: CPtr.java,v 1.4 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | /**
28 | * An abstraction for a C pointer data type. A CPtr instance represents, on
29 | * the Java side, a C pointer. The C pointer could be any type of C
30 | * pointer.
31 | */
32 | public class CPtr {
33 |
34 | /**
35 | * Compares this CPtr to the specified object.
36 | *
37 | * @param other a CPtr
38 | * @return true if the class of this CPtr object and the
39 | * class of other are exactly equal, and the C
40 | * pointers being pointed to by these objects are also
41 | * equal. Returns false otherwise.
42 | */
43 | public boolean equals(Object other) {
44 | if (other == null)
45 | return false;
46 | if (other == this)
47 | return true;
48 | if (CPtr.class != other.getClass())
49 | return false;
50 | return peer == ((CPtr) other).peer;
51 | }
52 |
53 |
54 | /* Pointer value of the real C pointer. Use long to be 64-bit safe. */
55 | private long peer;
56 |
57 | /**
58 | * Gets the value of the C pointer abstraction
59 | *
60 | * @return long
61 | */
62 | protected long getPeer() {
63 | return peer;
64 | }
65 |
66 | /* No-args constructor. */
67 | CPtr() {
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/Console.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: Console.java,v 1.7 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | import java.io.BufferedReader;
28 | import java.io.InputStreamReader;
29 |
30 | /**
31 | * Simple LuaJava console.
32 | * This is also an example on how to use the Java side of LuaJava and how to startup
33 | * a LuaJava application.
34 | *
35 | * @author Thiago Ponte
36 | */
37 | public class Console {
38 |
39 | /**
40 | * Creates a console for user interaction.
41 | *
42 | * @param args names of the lua files to be executed
43 | */
44 | public static void main(String[] args) {
45 | try {
46 | LuaState L = LuaStateFactory.newLuaState();
47 | L.openLibs();
48 |
49 | if (args.length > 0) {
50 | for (int i = 0; i < args.length; i++) {
51 | int res = L.LloadFile(args[i]);
52 | if (res == 0) {
53 | res = L.pcall(0, 0, 0);
54 | }
55 | if (res != 0) {
56 | throw new LuaException("Error on file: " + args[i] + ". " + L.toString(-1));
57 | }
58 | }
59 |
60 | return;
61 | }
62 |
63 | System.out.println("API Lua Java - console mode.");
64 |
65 | BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
66 |
67 | String line;
68 |
69 | System.out.print("> ");
70 | while ((line = inp.readLine()) != null && !line.equals("exit")) {
71 | int ret = L.LloadBuffer(line.getBytes(), "from console");
72 | if (ret == 0) {
73 | ret = L.pcall(0, 0, 0);
74 | }
75 | if (ret != 0) {
76 | System.err.println("Error on line: " + line);
77 | System.err.println(L.toString(-1));
78 | }
79 | System.out.print("> ");
80 | }
81 |
82 | L.close();
83 | } catch (Exception e) {
84 | e.printStackTrace();
85 | }
86 |
87 | }
88 | }
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/JavaFunction.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: JavaFunction.java,v 1.6 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | /**
28 | * JavaFunction is a class that can be used to implement a Lua function in Java.
29 | * JavaFunction is an abstract class, so in order to use it you must extend this
30 | * class and implement the execute method. This execute
31 | * method is the method that will be called when you call the function from Lua.
32 | * To register the JavaFunction in Lua use the method register(String name).
33 | */
34 | public abstract class JavaFunction {
35 |
36 | /**
37 | * This is the state in which this function will exist.
38 | */
39 | protected LuaState L;
40 |
41 | /**
42 | * This method is called from Lua. Any parameters can be taken with
43 | * getParam. A reference to the JavaFunctionWrapper itself is
44 | * always the first parameter received. Values passed back as results
45 | * of the function must be pushed onto the stack.
46 | *
47 | * @return The number of values pushed onto the stack.
48 | */
49 | public abstract int execute() throws LuaException;
50 |
51 | /**
52 | * Constructor that receives a LuaState.
53 | *
54 | * @param L LuaState object associated with this JavaFunction object
55 | */
56 | public JavaFunction(LuaState L) {
57 | this.L = L;
58 | }
59 |
60 | /**
61 | * Returns a parameter received from Lua. Parameters are numbered from 1.
62 | * A reference to the JavaFunction itself is always the first parameter
63 | * received (the same as this).
64 | *
65 | * @param idx Index of the parameter.
66 | * @return Reference to parameter.
67 | * @see LuaObject
68 | */
69 | public LuaObject getParam(int idx) {
70 | return L.getLuaObject(idx);
71 | }
72 |
73 | /**
74 | * Register a JavaFunction with a given name. This method registers in a
75 | * global variable the JavaFunction specified.
76 | *
77 | * @param name name of the function.
78 | */
79 | public void register(String name) throws LuaException {
80 | synchronized (L) {
81 | L.pushJavaFunction(this);
82 | L.setGlobal(name);
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/LuaException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: LuaException.java,v 1.6 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | /**
28 | * LuaJava exception
29 | *
30 | * @author Thiago Ponte
31 | */
32 | public class LuaException extends Exception {
33 | /**
34 | *
35 | */
36 | private static final long serialVersionUID = 1L;
37 |
38 | public LuaException(String str) {
39 | super(str);
40 | }
41 |
42 | /**
43 | * Will work only on Java 1.4 or later.
44 | * To work with Java 1.3, comment the first line and uncomment the second one.
45 | */
46 | public LuaException(Exception e) {
47 | super((e.getCause() != null) ? e.getCause() : e);
48 | //super(e.getMessage());
49 | }
50 | }
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/LuaInvocationHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: LuaInvocationHandler.java,v 1.4 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | import java.lang.reflect.InvocationHandler;
28 | import java.lang.reflect.Method;
29 |
30 | /**
31 | * Class that implements the InvocationHandler interface.
32 | * This class is used in the LuaJava's proxy system.
33 | * When a proxy object is accessed, the method invoked is
34 | * called from Lua
35 | *
36 | * @author Rizzato
37 | * @author Thiago Ponte
38 | */
39 | public class LuaInvocationHandler implements InvocationHandler {
40 | private LuaObject obj;
41 |
42 |
43 | public LuaInvocationHandler(LuaObject obj) {
44 | this.obj = obj;
45 | }
46 |
47 | /**
48 | * Function called when a proxy object function is invoked.
49 | */
50 | public Object invoke(Object proxy, Method method, Object[] args) throws LuaException {
51 | synchronized (obj.L) {
52 | String methodName = method.getName();
53 | LuaObject func = obj.getField(methodName);
54 |
55 | if (func.isNil()) {
56 | return null;
57 | }
58 |
59 | Class retType = method.getReturnType();
60 | Object ret;
61 |
62 | // Checks if returned type is void. if it is returns null.
63 | if (retType.equals(Void.class) || retType.equals(void.class)) {
64 | func.call(args, 0);
65 | ret = null;
66 | } else {
67 | ret = func.call(args, 1)[0];
68 | if (ret != null && ret instanceof Double) {
69 | ret = LuaState.convertLuaNumber((Double) ret, retType);
70 | }
71 | }
72 |
73 | return ret;
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/luajava/src/main/java/org/keplerproject/luajava/LuaStateFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * $Id: LuaStateFactory.java,v 1.4 2006/12/22 14:06:40 thiago Exp $
3 | * Copyright (C) 2003-2007 Kepler Project.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining
6 | * a copy of this software and associated documentation files (the
7 | * "Software"), to deal in the Software without restriction, including
8 | * without limitation the rights to use, copy, modify, merge, publish,
9 | * distribute, sublicense, and/or sell copies of the Software, and to
10 | * permit persons to whom the Software is furnished to do so, subject to
11 | * the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be
14 | * included in all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | package org.keplerproject.luajava;
26 |
27 | import java.util.ArrayList;
28 | import java.util.List;
29 |
30 | /**
31 | * This class is responsible for instantiating new LuaStates.
32 | * When a new LuaState is instantiated it is put into a List
33 | * and an index is returned. This index is registred in Lua
34 | * and it is used to find the right LuaState when lua calls
35 | * a Java Function.
36 | *
37 | * @author Thiago Ponte
38 | */
39 | public final class LuaStateFactory {
40 |
41 | private final static String LUAJAVA_LIB = "luajava";
42 | private final static boolean isLuaLibLoaded;
43 |
44 | /**
45 | * Opens the library containing the luajava API
46 | */
47 | static {
48 | boolean loaded = false;
49 | try {
50 | System.loadLibrary(LUAJAVA_LIB);
51 | loaded = true;
52 | } catch (UnsatisfiedLinkError e) {
53 | e.printStackTrace();
54 | }
55 | isLuaLibLoaded = loaded;
56 | }
57 |
58 | /**
59 | * Array with all luaState's instances
60 | */
61 | private static final List