objective-c与Lua的交互(二)

来源:互联网 发布:java [count] 编辑:程序博客网 时间:2024/06/05 20:53
第一贴是通过Lua脚本来启动。但是项目想做的是是在程序运行中,通过事件来触发,启动Lua脚本。找到了一个例子。
以下转发自:http://mobileorchard.com/announcing-iphone-wax-native-uikit-iphone-apps-written-in-lua/


Announcing iPhone Wax: Native UIKit iPhone Apps Written In Lua

[backcolor=transparent]by [backcolor=transparent]DAN GRIGSBY [backcolor=transparent]on [backcolor=transparent]30. SEP, 2009 [backcolor=transparent]in [backcolor=transparent]NEWS, RESOURCES, TIPS, TOOLS, TUTORIALS
[backcolor=transparent]
[backcolor=transparent]

Development Goes Faster With iPhone Wax

Early this summer I started playing around with MacRuby, which lets Rubyists create native OS-X applications. While I love Objective-C, scripting languages have speed-of-development, memory management simplicity, and other advantages. Getting Ruby running on the iPhone is challenging; while I’m sure it’ll get there, I wanted something sooner.
I started investigating how I might wire up — and then write native iPhone apps from — a scripting language. Lua was on my radar already. It’s compact, expressive, fast enough, and was designed to be embedded. Took only about 20 minutes to get the Lua interpreter running on the iPhone. The real work was to bridge Lua and all the Objective-C/CocoaTouch classes. The bridge had to work in two directions: it would need to be able to create CocoaTouch objects and also be able to respond to callbacks as part of the familiar delegate/protocol model.
I tweeted about my intentions. Corey Johnson responded that he’d been working along the same lines and, dang-it, his implementation was exactly what I had in mind. It’s called iPhone Wax, it’s brilliant, and Apple has already approved one app using it.
In the remainder of this post, I’ll walk you through getting it set up, show you how to creating a project featuring a UITableView, and close with a section on its roadmap and tools support.
Getting And Installing iPhone Wax
iPhone Wax is available on GitHub. You can either clone its repo or download a zip of the latest code. Once you’ve got the source, change to its directory, and type rake install — this will install an iPhone Wax project template in Xcode.
Hello World in Label, Courtesy of Lua and iPhone Wax

Let’s create a simple project:
    Open up XcodeSelect New Project from the File MenuUnder User Templates select the Wax itemSelect Wax iPhone App from the template listClick the Choose… buttonName your project and click the Save button

The iPhone Wax Xcode template does the heavy lifting, creates a project with a UIWindow and an embedded, bridged, ready to use Lua interpreter.
The iPhone Wax project template is a ready-made “Hello World” application. Build and Run the application to see it in action.
Using CocoaTouch/UIKit Classes From Lua With iPhone Wax

While still in the app from the previous step, take a look at the Lua source that drives the application: open init.lua in Xcode’s editor — you’ll find it under the scripts folder under in theGroups & Files panel.
The Lua-to-CocoaTouch/UIKit bridging syntax is easy to pick out from the example. After requiring the wax library, the code contains this instruction:

[pre][backcolor=transparent]window = UI.Application:sharedApplication():keyWindow()[/pre]
The Lua window variable will be assigned keyWindow property of the sharedApplication singleton/class-member of the UIApplication class. Note the absence of an alloc call. iPhone Wax takes care of memory management using hooks in Lua’s garbage collection routines; it sends a release message to the object on your behalf when the Lua disposes of its variable.
With the variable set operations can be performed on it:

[pre]window:setBackgroundColor(UI.Color:orangeColor())[/pre]
Here we’re calling the setBackgroundColor method on our window method and assigning it the orange color.
Next, the code creates a label and configures its attributes:

[pre]label = UI.Label:initWithFrame(CGRect(0, 100, 320, 40))label:setFont(UI.Font:boldSystemFontOfSize(30))label:setColor(UI.Color:orangeColor())label:setText("Hello Lua!")label:setTextAlignment(UITextAlignmentCenter)[/pre]
Finally, the label is made visible by adding it as a subview:

[pre]window:addSubview(label)[/pre]
Beyond Hello World: Delegates And A UITableView

To do real work, our Lua code needs to be able to respond to delegate callbacks. Let’s modify our sample to include a UITableView and use Lua to implement the UITableViewDelegate andUITableViewDataSource protocols.
Start by adding a new, blank file called TableViewController.lua to the project:
    Right-click or control-click on the scripts folder in the Groups & Files panelChoose Add > New File from the context menuClick the Other item user the Mac OS-X sectionSelect the Empty File icon and click NextName the file TableViewController.lua and click Finish
Paste this code into the new file:

[pre]waxClass("TableViewController", UI.TableViewController, protocols = {"UITableViewDelegate", "UITableViewDataSource"})function init(self)  self.super:init()  self.states = {"Michigan", "California", "New York", "Illinois", "Minnesota", "Florida"}  return selfendfunction viewDidLoad(self)  self:tableView():setDataSource(self)  self:tableView():setDelegate(self)  end-- DataSource-------------function numberOfSectionsInTableView(self, tableView)  return 1endfunction tableView_numberOfRowsInSection(self, tableView, section)  return #self.statesendfunction tableView_cellForRowAtIndexPath(self, tableView, indexPath)    local identifier = "TableViewCell"  local cell = tableView:dequeueReusableCellWithIdentifier(identifier)  cell = cell or UI.TableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleDefault, identifier)    cell:setText(self.states[indexPath:row() + 1]) -- Must +1 because lua arrays are 1 based  return cellend-- Delegate-----------function tableView_didSelectRowAtIndexPath(self, tableView, indexPath)  tableView:deselectRowAtIndexPath_animated(indexPath, true)  -- Do something cool here!end[/pre][ Update: there was a slight change to the waxClass API. An earlier version -- the one I used in my GitHub code -- expected the third argument to be a hash. So when you look at the GitHub code you'll see: waxClass("TableViewController", UI.TableViewController, {protocols = {"UITableViewDelegate", "UITableViewDataSource"}}) ]
Have a look at the top line, the one beginning with waxClass. This line is key. It declares a Lua class that bridges to CocoaTouch and declares the protocols it implements. The remainder of the code is the implementation of the constructor and the callbacks for the protocols.
Next, update init.lua to use the following:

[pre]require "wax"require "TableViewController"window = UI.Application:sharedApplication():keyWindow()tableViewController = TableViewController:init()window:addSubview(tableViewController:view())[/pre]
In this update, we've replaced the background color and label-related code with code that instantiates an instance of the TableViewController class and adds it to the view. Build and run the project to see the working table UI.
The source for the finished example is available on GitHub. You can either clone its repo or download a zip of the code.
Roadmap, Tools And A Google Group
Corey's SF Rentals uses iPhone Wax. iPhone Wax complete enough and stable enough to consider for real applications.
A TextMate bundle is in the works. Notably, it'll support transforming Objective-C method signatures copied into the pasteboard -- from, e.g., Xcode's documentation -- into Lua method calls when pasted into the code.
CocoaTouch methods can be verbose; because the bridge directly translates CocoaTouch method names the Lua function calls can be quite long. A similar problem exists with MacRuby; MacRuby includes a sub-project called Hot Cocoa that ads a thin layer of idiomatic Ruby to make the programs written with MacRuby feel more natural. We'll do something similar.
We've created an iPhone Wax Google Group to support developers and an official site is in the works.
I'll follow up this post with articles on the TextMate bundle, more details of how to use the bridge, and details on how the bridge functions.


附件是以上步骤的代码。



附件:  dcgrigsby-iPhone-Wax-Simple-Sample-App-ab2bb8e.zip (280 K) 下载次数:36
原创粉丝点击