Lua學習 2) —— Android與Lua互調

來源:互聯網
上載者:User

標籤:android   style   java   color   strong   os   

2014-07-09

一、Android類調用lua並回調

Android調用Lua函數,同時把類作為參數傳遞過去,然後再Lua中回調類的函數

調用lua

mLuaState = LuaStateFactory.newLuaState();mLuaState.openLibs();mLuaState.LdoString(KKLua.loadAssetsString(mContext, "lua/swallow.lua"));//將lua轉換為字串mLuaState.getField(LuaState.LUA_GLOBALSINDEX, "luaUpdate");//擷取lua中的functionmLuaState.pushJavaObject(this);//傳遞參數mLuaState.call(1, 0);//一個參數, 0個傳回值

回調的介面

public void luaDraw(int imageId, int x, int y, int scale) {//注意也必須要是public, lua才能調用到System.out.println("imageId, x, y, scale: " + imageId + ", " + x + ", " + y + ", " + scale);}
lua代碼
function luaUpdate(luaCanvas)  luaCanvas:luaDraw(0, 1, 2, 1)end

二、luajava介紹( 在LuaJava庫裡麵包含的)

lua中是沒有類的,luajava庫中有個luajava可以建立java中的類,並調用。下面介紹幾個方法

①newInstance(className, ...)

說明:可以根據類名建立一個Java類,同時返回一個lua變數與Java類對應。這樣在lua中就可以直接調用Java中的方法了。

obj = luajava.newInstance("java.lang.Object")-- obj is now a reference to the new object-- created and any of its methods can be accessed.-- this creates a string tokenizer to the "a,b,c,d"-- string using "," as the token separator.strTk = luajava.newInstance("java.util.StringTokenizer",     "a,b,c,d", ",")while strTk:hasMoreTokens() do    print(strTk:nextToken())end

②bindClass(className)

說明:可以讓lua中的變數對應一個Java的類(是類,不是執行個體),這樣就可以用lua的這個變數建立執行個體以及調用靜態類

sys = luajava.bindClass("java.lang.System")print ( sys:currentTimeMillis() )-- this prints the time returned by the function.

③new(javaClass)

說明:這個就是在②的基礎上建立的

str = luajava.bindClass("java.lang.String")strInstance = luajava.new(str)


④createProxy(interfaceNames, luaObject)

⑤loadLib(className, methodName)

這兩個方法目前還沒用到,以後會用了再介紹

以上,謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.