二、建立新項目
開啟Xcode,建立一個 Wax項目,該模板可以在 User Templates 中找到。
從現在開始,APP_ROOT將代表項目本身所在的路徑。
運行app,你將在iPhone模擬器中看到Hello Lua字樣。
三、開始使用Lua
並不需要在Xcode中編寫Lua代碼,它們全都在APP_ROOT/scripts目錄下,直接用你喜歡的文本編輯工具編輯它們好了。Wax標準庫檔案位於APP_ROOT/wax/lib/stdlib目錄下。這些全是你會用到的代碼!
如果你使用TextMate,從APP_ROOT目錄下執行rake tm,以便從項目開啟。還可以安裝wax-bundle已支援快速鍵。
如果你迷戀於Xcode,你可以試試 capgo.com's 的文法加亮外掛程式。
如果你使用的是vi或Emacs,你總不會連Lua支援都不會裝吧?
要建立一個TableView,首先建立一個檔案: APP_ROOT/scripts/MyTableViewController.lua
要建立新的OC控制器類,使用:
waxClass{"MyTableViewController",UITableViewController}
現在實現init函數,在裡面設定tableView的內容並調用父類的init方法(正如你在OC中所做的一樣)。
function init(self)
self.super:initWithStyle(UITableViewStylePlain)
-- Here are the tableView'scontents
self.things ={"Planes", "Trains", "Automobiles"}
return self
end
接下來實現UIDataSource協議方法。最終 MyTableViewController.lua 檔案如下所示:
waxClass{"MyTableViewController",UITableViewController}
function init(self)
self.super:initWithStyle(UITableViewStylePlain)
-- Here are thetableView's contents
self.things ={"Planes", "Trains", "Automobiles"}
return self
end
functionnumberOfSectionsInTableView(self, tableView)
return 1
end
functiontableView_numberOfRowsInSection(self, tableView, section)
return #self.things
end
functiontableView_cellForRowAtIndexPath(self, tableView, indexPath)
local identifier ="MyTableViewControllerCell"
local cell =tableView:dequeueReusableCellWithIdentifier(identifier) or
UITableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleDefault,identifier)
local thing =self.things[indexPath:row() + 1] -- Must +1 because Lua arrays are 1 based
cell:textLabel():setText(thing)
return cell
end
最後就是建立MyTableViewController樣本並加到主視窗中。這需要修改APP_ROOT/scripts/AppDelegate.lua。它跟我們在OC程式中的UIApplicationDelegate是一樣的。
require"MyTableViewController"
waxClass{"AppDelegate",protocols = {"UIApplicationDelegate"}}
functionapplicationDidFinishLaunching(self, application)
local frame =UIScreen:mainScreen():bounds()
self.window =UIWindow:initWithFrame(frame)
self.controller =MyTableViewController:init()
self.window:addSubview(self.controller:view())
self.window:makeKeyAndVisible()
end
運行程式…你已經用Lua建立了一個真正的UITableView!這真是太好了。
四、Wax framework安裝
在這裡下載framework:https://github.com/downloads/probablycorey/wax/wax.framework.zip
五、在項目中以framwork方式使用wax
1. 用Xcode開啟項目,將wax.framework拖到Xcode的frameworks組下。確保勾選"Copy items into destination group's folder"。
2. 建立init.lua(確保加到了應用程式束中)。在檔案中加入代碼:
puts("ZOMG, LUA IS RUNNING")
puts("Here is Lua talking to ObjC%s", tostring(UIApplication:sharedApplication()))
3. 開啟AppDelegate檔案,匯入wax標頭檔:
#import "wax/wax.h"
4. 在AppDelegate的application:didFinishLaunchingWithOptions:方法中加入:
wax_start("init.lua",nil);
// To add wax with extensions, use thisline instead
// #import "wax/wax_http.h"
// #import "wax/wax_json.h"
// #import"wax/wax_filesystem.h"
// wax_start("init.lua",luaopen_wax_http, luaopen_wax_json, luaopen_wax_filesystem, nil);
最後,build and run,你將在Xcode控制台重看到Lua輸出的內容。