Original: http://luanova.org/ioswithlua/
This article discusses 3 ways to create iOS applications with Lua. This includes using LUA to create a complete application (Corona) to use LUA as a scripting element in the app (via wax or DIY). Before that, we need to ask ourselves two questions:
1, why use LUA.
2. Is Apple allowed to use LUA?
The two issues are closely related.
If you know nothing about Lua before then, I'll give you a brief overview of Lua. If you are familiar with Lua, you can skip this part of the content.
About LUA
Lua is an efficient, lightweight, embedded scripting language. Similar to Javascrip, Ruby, or Python. There are a lot of users like me who think Lua is a simple and elegant language.
Lua began in 1993 at the Zong Duo Catholic University of Rio de Janeiro, Brazil, in Roberto Ierusalimschy, Waldemar Celes and Luiz Henrique de Figueiredo. It applies in Mi Casa Verde, Adobe Lightroom, Celestia, Lighttpd,luatex, Nmap,wireshark, Cisco Adaptive Security Appliance, Pblua, and thousands Tens of thousands of games (including Grim Fandango (Avatar), World of Warcraft, Tap Tap Revenge (Jin Orchestra), etc.). LUA uses the MIT protocol-which means that Lua is largely free of commercial and non-commercial goals.
The main data-building mechanism of LUA is the combination of table-variable arrays and hash tables. Listing 1 lists a LUA Table, assuming we describe the car and its mileage per gallon. We can use string-type keys to store vehicle information, such as license and make. The digital subscript index is used to store a series of miles per gallon.
Listing 1: A Lua table type
Car_data = {license = ' XVW1942 ', make = ' Volvo ', model = ' XC70 ', 30, 31.3, 32.4, 34.0}
Print (car_data[1])--30
Print (car_data[' license '])--XVW1942
Print (Car_data.license)--XVW1942 (also!)
In Lua, array subscripts start at 1, not 0. '--' indicates that the comment begins until the end of the line. To your surprise, Lua is neither an object-oriented language nor a functional programming language. However, it also provides several mechanisms that allow you to customize your own advanced features. LUA contains a variety of object systems such as traditional OO systems and non-class OO systems such as the self language and IO language of Oracle. The translator notes that both are based on a generic language. LUA supports the "one class function" (the translator * is actually an anonymous function, and LUA can construct a function at run time and think of it as an object), closures, and Meta attributes (such as meta tables and meta methods). Lua is well adapted to the needs of functional programming.
For an introduction to LUA's object-oriented programming, read LUA programming (this book is a good introduction to all aspects of LUA). You should also read the LUA example on the Luawiki.
Listing 2 lists an implementation of the linked list class. The variable list is actually a table, which is used as the Metamodel for all linked list objects. It implements a class-like event-handling mechanism for backward lookup table indexes. The "List.__index=list" line allows us to create a method for the List object. Method is a function that is saved in the List meta table. When we call these functions of the list object, we will look up the definitions and run the functions in the List meta table.
This code shows a series of enhancements to LUA: multiple assignments (as well as functions returning multiple return values), the method calls the syntax sugar (': ' notation), similar to adding a self parameter in a function call, which is seen in many languages, from Python to OC.
Lists 2:linked List class
List = {}
List.__index = List
function List:new ()
Local L = {head = {},tail = {}, size = 0}
L.head.__next,l.tail.__prev = L.tail, L.head
Return setmetatable (l,self)
End
function List:first ()
If self.size > 0 Then
Returnself.head.next
Else
return Nil
End
End
function List:addfirst (elem)
Local node = {prev= Self.head, value = Elem,
Next = Self.head.next}
Node.next.prev =node
Self.head.next =node
Self.size =self.size + 1
End
MyList = List:new ()
Mylist:addfirst (12)
Print (Mylist:first ())
Here, I overlooked something important and interesting (like closures). But at least you've learned a little about Lua's fur. When we go into the iphone code later, we see more LUA code. For more information about LUA, please read this website.
iOS support script.
As with the two questions listed at the beginning of this article, especially the 2nd question: "Does the iphone allow LUA (or other interpreted languages)?" "After all, as early as Apple's IDP license agreement has stated," only the official Apple API and the built-in interpreter-supported explanatory code can be downloaded or used in the app.
In fact, in the outline of this article, Apple has changed the terms that prevent developers from using other languages other than OC and JavaScript (JavaScript can be used in web apps or local apps-via UIWebView) in apps (circa2010 April). More recently (20,109 months), Apple has changed the terms again, allowing the scripting language to be used.
But there are still a few important limitations. Even more important, although you can use LUA (and other scripting languages), your app doesn't allow users to download plug-ins from the Web (using an app to buy them). , nor can you allow users to write scripts, download scripts, and so on. There are a number of stores that use languages such as LUA (such as the orchestra).
Of course, the two most important role in the app's language of Lua is to create a plug-in system that allows users to write scripts themselves. There are many more.
How to use LUA in iOS development.
Although you cannot create a plug-in system for end users or allow users to write their own scripts, you can still develop your system in a plug-in way. This speeds up the development of prototypes and helps add new features in the next release. There's another benefit to using LUA, it allows you to make "rapid prototyping" (my favorite complaint: not to program in a closed way), to mitigate and not even require memory management, to allow more team members to participate in development (there are many LUA projects where no programmers are writing code), Application optimization is easier and provides a more robust persistence mechanism.
In short, Lua saves development time and lowers the development threshold. Life has become so easy and enjoyable. Assuming you've decided to use LUA, then how do we do it?
Corona
Ansca Mobile's corona allows you to fully use LUA to develop iOS apps and Android apps. You can compile iOS and Android programs with the same source code. That's why LUA, in fact, Corona, is so appealing: cross-platform.
Listing 3 is the entire source code for an app.
List 3:swirly The Main.lua in the Text application
Local W, h = display.stagewidth, display.stageheight
Local dx, dy, Dtheta = 5, 5, 5
Local background = display.newrect (0, 0, W, h)
Background:setfillcolor (255, 255, 255)
Local message = Display.newtext (' Hello from Corona ', W/2, H/2)
Message:settextcolor (0, 0, 200)
Local function Update (event)
Local Counter_spin =false
Message:translate (dx, DY)
Message:rotate (Dtheta)
If message.x > Wor message.x < 0 Then
dx=-1 * DX
Counter_spin = True
End
If message.y > Hor message.y < 0 Then
DY =-1 * dy
Counter_spin = True
End
If Counter_spin Then
Dtheta =-1 * dtheta
End
End
Runtime:addeventlistener (' enterframe ', update)
The Corona program can be developed with any text editor-I'm using Emacs. All the resources (images, sounds, data) used in the LUA source code must be in the same directory, and Corona need Main.lua files to start the app. You can test your code in the Corona emulator (Mac that supports Intel CPUs and power PCs). Figure 1 shows my Corona ide:emacs (including the Lua file Exit and Project window), the Corona terminal (which can print debug information from diagnostics), and the Corona emulator.
Figure 1: My Corona ' IDE '
Left to right (counterclockwise): Corona emulator, Emacs two windows (Source Code window and Project directory window), Corona terminal (output debug information).
To run the program on the physical hardware, use the Openfor Build command of the Corona Emulator. To compile with iOS, you should provide a provisioning profile (development or deployment)--yes, you don't need an IDP account--These two files are uploaded to the Ansca company's server along with the app code and resources, and the results are returned to you. To build on Android, you should have the proper signature certificate. Then, as the compilation progresses, upload your code to the ANSCA server. You don't have to install ANDROIDSDK. I haven't studied much, but the compiled. apk files and. App files already contain everything that your LUA code has handled in some way. A brief view indicates that it is not standard compiled LUA bytecode, but should be in a similar format.
The Corona Event system handles touch (including multi-touch), accesses GPs and accelerators, handles animations, and customizes events. It also has a powerful graphics system that allows you to draw circles, rectangles, and text. Recently added a polyline that allows you to draw polygons. You can display pictures. Corona allows you to group these objects together and transform them. Listing 4, excerpt from the code snippet of the solar system simulator, shows a simple example of combining multiple graphic objects. Other features supported by Corona include sound video playback, encryption algorithm library, Luasocket network library, SQLite Access library Luasqlite, etc. You can also access local components including TextField, alert, and Activityindicator. You can also use WebView to do things like login screens, and there is a sample program that provides a library to connect to Facebook. I recently saw a game (very expensive) using box2d physics engines, roles, and some OpenFeint features (like the leaderboard).
Listing 4: The Solar System application code fragment
function new (params)
Local color =params.color or Planet_colors[random (#planet_colors)]
Local radius =params.radius or Planetradius ()
Local Planet =display.newgroup ()
Planet.theta = 0
Local x = Params.x-ox
Local y = Params.y-oy
Planet.orbital_radius = sqrt (x*x+y*y)
Local body =display.newcircle (x + ox, y + Oy, radius, radius)
Body:setfillcolor (Unpack (color))
Planet:insert (Body,true)
Planet.body = Body
Planet.delta_theta = (40/planet.orbital_radius) * 0.1
Return Planet
End
Pass the table as a function parameter, you can use named parameters and provide a default value. So there will be a local radius = Params.radius Orplanetradius ().
Corona has done a lot for you, but at the same time there are many deficiencies. The biggest problem is access restrictions on local controls. Because of the limitations of the Corona emulator, its access to the local control is bad. In the simulator, local alerts and activityindicators are implemented using OS X equivalents instead of iOS widgets. TextField, textbox, and Web popups are not available when the emulator is running. This is painful when it comes to development.
Finally, there is no access to o-capi other than the ANSCA standard. Not only is a large number of standard libraries, but also 3rd party libraries are not available, such as APIs such as THREE20 or mobileads. Of course, with the release of the Corona Android version, you may not want to access the OC API because it limits your application's ability to cross-platform (or add complexity). It is best to extend it through Lua's CAPI, just as many cross-platform projects do.
My discussion in the Ansca group on their forum was very useful. With the release of version 2.0 (2010.9), Corona to each developer for $249 a year. For the game version, the fee is $349 per developer each year. Ansca's website suggests that the price of the game version is just a preview version. That means the price will be higher when the official version is released.
DIY
It's easy to put the LUA interpreter in the iOS app. Open a Xcode project to add Lua's source files (except LUA.C and LUAC.C command-line programs) to your project. Compile. You can use the standard LUAC API to create an explanation and run the source code, just like Ilua did. You can download this sample code in Http://github.com/profburke/ilua. Iluashell is a simple view-based application that provides two text boxes to users-one to enter the LUA code for the user, the other to be non-editable, just to show the results of the LUA code calculations.
This work is done with the Evaluate method, as shown in Listing 5. In the method, get the value of the 1th text field first, give it to the LUA interpreter to parse and execute, and then place the LUA output into the 2nd text field.
Listing 5 Evaluate method
-(void) Evaluate {
int err;
[Input Resignfirstresponder];
Lua_settop (L, 0);
Err = lual_loadstring (L, [Input.text
Cstringusingencoding:nsasciistringencoding]);
if (0!= err) {
Output.text = [NSString stringwithcstring:lua_tostring (L,-1)
Encoding:nsasciistringencoding];
Lua_pop (L, 1);
Return
}
Err = Lua_pcall (L, 0, Lua_multret, 0);
if (0!= err) {
Output.text = [NSString stringwithcstring:lua_tostring (L,-1)
Encoding:nsasciistringencoding];
Lua_pop (L, 1);
Return
}
int nresults =lua_gettop (L);
if (0 = nresults) {
Output.text = @ "<no results>";