Lua vs. Obj-C
Lua
For some time now I’ve been digging into Lua. Coming from Python, the power of a clean syntax and good documentation is impossible to ignore.Lua is a powerful, fast, lightweight, embeddable scripting language.It’s that exotic, super-fast scripting language that very few use, right? Partially right. It’s extensively used in the gaming industry (e.g. World of Warcraft) usually together with C++.
Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping.
Lua comes with a console, which is great tool for fast experimenting of logic and syntax.
Lua + iOS
All fine and dandy, but how can this help me on iOS development? Stefan found the right answer: iPhone Wax .
Wax is a framework that lets you write native iPhone apps in Lua. It bridges Objective-C and Lua using the Objective-C runtime. With Wax, anything you can do in Objective-C is automatically available in Lua!”As anyone with iOS development experience knows, Obj-C is very strict about classes, requiring a certain mindset to write good, maintainable and modular applications. Wax doesn’t alter this approach at all.
Corey Johnson, main guy behind Wax
Memory management is another worry that goes away in Wax, because of the automatic garbage collection.
By this point, Wax looked completely different than any other write-quick-iphone-apps gimicks out there, including PhoneGap, Titanium, Rhomobile, Corona SDK. Do note that I mention “iPhone apps”, since the result of Wax is not cross platform. Well, a solid application should take advatage of the hardware platform and the only part that can be cross platform is the interface, even that within certain limits.
Cocoa with a sprinkle of Lua
Wax looked good in theory. A UITabBarController is a UITabBarController, a delegate is a delegate, 3rd party libs work how they are intended to (Facebook, ASIHTTPRequest, custom written ones). Now let’s see it in practice.I gave Wax a run-around for 1 week. During that time I tried using most of the UITouch, Cocoa elements and some 3rd party libraries. The results were good. The interface is just as responsive as building directly in Obj-C.
After that test week, the decision of using Wax for the rest of app development seemed obvious, even more, Wax seems like a valuable addition to the development cycle.
Side-by-side example and benchmark
Here’s a small benchmark of memory usage by the same application, written in Wax and in Obj-C. The application used is Fortune Crunch from Mark’s tutorial on MobileTuts+.Objective-C code (can be seen in the source code of the tutorial too):
- // FortuneCrunchAppDelegate.h
- //
- #import <UIKit/UIKit.h>
-
- @class FortuneCrunchViewController;
-
- @interface FortuneCrunchAppDelegate : NSObject <UIApplicationDelegate> {
- UIWindow *window;
- FortuneCrunchViewController *viewController;
- }
-
- @property (nonatomic, retain) IBOutlet UIWindow *window;
- @property (nonatomic, retain) IBOutlet FortuneCrunchViewController *viewController;
-
- @end
-
-
-
- // FortuneCrunchAppDelegate.m
- //
- #import "FortuneCrunchAppDelegate.h"
- #import "FortuneCrunchViewController.h"
-
- @implementation FortuneCrunchAppDelegate
-
- @synthesize window;
- @synthesize viewController;
-
-
- #pragma mark -
- #pragma mark Application lifecycle
-
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
-
- // Override point for customization after application launch.
-
- // Add the view controller's view to the window and display.
- [self.window addSubview:viewController.view];
- [self.window makeKeyAndVisible];
-
- return YES;
- }
-
- - (void)dealloc {
- [viewController release];
- [window release];
- [super dealloc];
- }
-
-
- @end
-
-
-
- // FortuneCrunchViewController.h
- //
-
- #import <UIKit/UIKit.h>
-
- @interface FortuneCrunchViewController : UIViewController {
-
- IBOutlet UIButton *fortuneCookieButton;
- IBOutlet UILabel *fortuneLabel;
-
- }
-
- @property(nonatomic, retain) IBOutlet UIButton *fortuneCookieButton;
- @property(nonatomic, retain) IBOutlet UILabel *fortuneLabel;
-
- -(IBAction)crunchCookie:(id)sender;
-
- @end
-
-
-
- // FortuneCrunchViewController.m
- //
- #import "FortuneCrunchViewController.h"
-
- @implementation FortuneCrunchViewController
-
- @synthesize fortuneCookieButton;
- @synthesize fortuneLabel;
-
- // This method changes the cookie image when the button is pressed:
-
- -(IBAction)crunchCookie:(id)sender {
- NSLog(@"In crunchCookie");
- [fortuneCookieButton setImage:[UIImage imageNamed:@"cookie-crunched.png"]
- forState:UIControlStateNormal];
-
- fortuneLabel.hidden = NO;
-
- }
-
- // These methods are related to memory management:
-
- - (void)viewDidUnload {
- [fortuneCookieButton release];
- fortuneCookieButton = nil;
- }
-
- -(void)dealloc {
- [fortuneCookieButton release];
- [fortuneLabel release];
- [super dealloc];
- }
-
- @end
Lua code:
- -- AppDelegate.lua
- waxClass{"AppDelegate", protocols = {"UIApplicationDelegate"}}
-
- require "FortuneCrunchViewController"
-
- function applicationDidFinishLaunching(self, application)
- local frame = UIScreen:mainScreen():bounds()
- self.window = UIWindow:initWithFrame(frame)
- self.window:setBackgroundColor(UIColor:whiteColor())
- local fc = FortuneCrunchViewController:init()
- self.window:addSubview(fc:view())
- self.window:makeKeyAndVisible()
- end
-
- -- FortuneCrunchViewController.lua
- waxClass{"FortuneCrunchViewController", UIViewController}
-
- function crunchCookie(self, sender)
- self.button = self:view():viewWithTag(1)
- self.button:setImage_forState(UIImage:imageNamed('cookie-crunched.png'), UIControlStateNormal)
- self.label = self:view():viewWithTag(2)
- self.label:setHidden(false)
- end
-
- function init(self)
- self.super:initWithNibName_bundle("FortuneCrunchViewController", nil)
- return self
- end
Objective-C

Wax/Lua

As expected, Wax has a small foot-print.
Conclusion
Most of the people dislike the syntax of Obj-C and it does slow down development. Speed and maintainability are of great value for new apps and here is an awesome alternative!Categories: Objective C iphone mobile



Discussion
As much as I dislike ObjC syntax, I dislike "underscorized" versions of Cocoa method names even more.
Unfortunately Cocoa uses ridiculously verbose names, which makes some sense in ObjC, but is a huge annoyance elsewhere.
So ridiculously verbose names make sense in Obj-C because it has a ridiculously designed syntax anyway? :-)
I like your review of Luau vs Obj-C. I have been programming in Obj-C since I left C++ in 2002, which I had worked with for 5 years. For a language people truly hate after learning Obj-C, C++ has no peer. But that's just my very biased opinion...
But I do have to take issue with your statement that Obj-C syntax is disliked and slows down development. I don't know who makes up the population of "most people". I can say it's not the "most people" I have known for the last 9 years from both programming in Obj-C on being the organizer of a Cocoa and Cocoa Touch group that started in 2003. Obj-C syntax, like any new syntax, takes getting used to. And the Cocoa and Cocoa Touch API sets take time to learn, just like another set. But slowing down development? If anything, because Obj-C is very nearly self-documenting in method construction, dynamically typed (I once wrote an app using only id for the types and it worked fine), protocols (great for plug-in's) and categories (to enhance a class without having to subclass is a huge time saver) allow for rapid, not delayed, development.
Your other point that Obj-C is strict with classes and requires a certain mindset to write modular, maintainable code had me scratching my head. I'm not sure how anyone would classify the message pattern or key-value-coding/observing traits in Obj-C as requiring a certain mindset, other than a flexible, not strict, one. Perhaps you're referring to the lack of multiple inheritance? Delegates seem to be a better alternative without the downsides that multiple inheritance brings.
I think the more time you spend with Obj-C, rather than trying to avoid it, the more you will appreciate its strengths and see why the iOS app dev cycle produces such a great bang for the buck.
Jim, "dynamic typing" is usually defined as runtime inferring of type and it's only offered by Lua in this death-match. What Obj-C has is a glorified version of "void *" - the void pointer available in C, now wearing the hat of a generic type called 'id' that's also cursed with a limitation - it can only point to objects.
BTW, if you want to get a taste of real flexibility try some interpreted languages. The more time you spend away from that abusive Obj-C, the more you'll appreciate freedom ;-)
this is a poor comparison, given all the template code you didn't remove and didn't put any functionality into. good job, fox development news.
Stefan, Objective-C objects do store their type, and messages are fully dynamic; like in a scripting language (but unlike in C or C++ with a void *), you can send any arbitrary message to an id, and it will succeed or fail depending on whether the object actually implements the selector. So I don't see your point.
comex, what you describe is message handling. Dynamic typing is something else. A good starting point in learning about it is, as usual, wikipedia:
http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
Stefan, can you give an example of what you think is possible in a dynamically typed language but not in Objective-C? (With objects, that is; of course Objective-C shows its C heritage by having primitive values that are not objects.)
On the contrary, Stefan. I think *you* are misunderstanding what "message passing" is like in ObjC. In ObjC message passing is equivalent to runtime virtual function dispatch. You often declare variables as "id", which is a pointer to an object whose type is only known at runtime (e.g. a dynamic type, just as described in your wiki link). If you want to know the type of something, you can use [myObj class] to get the type directly, or use something more polymorphic like [myObj respondsToSelector:@selector(mySelector)]. Other dynamic typing info can be retrieved with the conformsToProtocol, isKindOfClass and isMemberOfClass selectors. So while this is certainly more verbose than LUA's dynamic types, it's about dynamic as types can get.
Stefan,
I think you might consider reading Apple's Obj-C Runtime Programming Guide.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
It will help fill-in the gaps you have about Obj-C's object creation and method invocation and dynamic binding of methods to messages, as are laid bare in your comments.
Um.... Your Obj-C code LOOKS longer only because you implemented several methods that you did not implement in LUA (lines 45- 100)
Not a good example.
About a third of that Objective-C code is unnecessary. It's empty implementations of methods from the template. Pare down the Objective-C stuff and they're about the same amount of code.
The difference between [self.window makeKeyAndVisible] and self.window:makeKeyAndVisible() is negligible.
I'd say unfamiliarity with Objective-C slows down development, but that's true of any language or tool.
As some of you made the observation that the Obj-C code had some extra noise, hence I have removed it. The thing is that the noise was created by XCode and it's easy to ignore with some eye training.
Hope this helps now.
comex, here's what I know is possible with dynamic typing:
foo = 1
Notice how I don't have to specify a type for the variable 'foo'. The interpreter will figure it out at runtime.
foo = 'bar'
Here I've just changed the variable's type. The interpreter is flexible enough to detect this and act as expected. And if you're nervous at the thought that I won't be protected from a mistake by the type checking that comes with statically typed languages like Obj-C, then let me introduce you to a brand new line of thinking: the programmer knows best. And, also, if you need a GUI tool to generate some of the code for you, you are doing it wrong. Coding is about control.
Alex, why are you explaining me what message passing is when I talk about dynamic typing? Because the word "dynamic" applies to both of them? They are very different concepts, nonetheless.
Jim, same thing. Not relevant to the discussion at hand.
Tudor, the guys are right, a side-by-side comparison should implement exactly the same things.
As much as I love lua I don't like this approach. Mostly because the method names have such poor match in lua. I think Tim Burks Nu programming language: http://programming.nu/about is a much better approach. Example code defining a makeBindings method:
(- makeBindings is
(@mailboxController bind:"contentArray" toObject:@controllerAlias withKeyPath:"selection.mailboxes" options:nil)
(@mailboxController setObjectClass:Mailbox)
Nu is a flexible dynamic language just like Lua, but specifically designed for Objective-C and to match its syntax. It also comes with a "bake" functionality so you can later convert your Nu code to Objective-C code. I think that is a more powerful approach than Lua + wax.
Stefan,
Objective-C is not statically typed and Interface Builder does not generate code. Those two facts were established over twenty years ago.
I've learned that most developers simply dislike the [target message] style, mostly due to a lack of exposure to anything other than the instance.method() style. That's hardly a way to judge a language though.
It should also be noted that you can write Mac apps with Python and Ruby, in much the same way as Lua on iOS.
Erik, any improvement on Obj-C is welcomed but Nu doesn't seem to do much about most of the shortcomings:
https://github.com/timburks/nu/blob/master/examples/MailDemo/nu/maildemo.nu
And then there's variable name prefixing to indicate the type...
Terry, if you think that Objective-C is not statically typed, drop the type from your variables (including 'id') and see what happens. We don't need to use historical evidence. We can test it right now.
I was referring to Xcode when talking about GUI tools that write some of the code but are unable to also read and understand it for you. Not that Interface Builder is much different, but I can cut some slack to people using graphical interfaces to create a GUI ;-)
The argument against "most developers" who "simply dislike the [target message] style" has one flaw - you're arguing against something that wasn't stated. We can't build straw-men and shred them to pieces with our favorite arguments, now can we?
Yes, Python can be used to write OS X software, but we're talking about iOS.
Stefan,
You appear to have a narrower definition of dynamically typed than pretty much everybody else. That makes debate rather difficult.
As for XCode, yes, the templates aren't great, but there's no requirement to use them. You can use a blank file or create your own templates. You don't even need to do your editing in XCode. And I thought this was about Objective-C, not XCode.
The dislike of Objective-C's syntax wasn't stated? It's right in the conclusion of the original post.
Terry, I'm open to other definitions besides "type inferred at runtime so only values have type and variables don't". What do you have in mind?
My criticism of XCode generating code in the place of the programmer comes as a response to the argument that Obj-C programming is simplified by it. Dropping the IDE would defeat the original argument and Obj-C would remain a productivity killer.
The original post states that "most of the people dislike the syntax of Obj-C and it does slow down development". You took "syntax" as a place-holder for "message passing paradigm"?
Stefan,
id foo = [NSNumber numberWithInt:1];
Notice how the type for the variable 'foo' indicates only that it is an object (since, again, only objects are dynamically typed); I don't have to specify that it's a NSNumber.
foo = @"bar";
Here I've just changed the variable's type, and everything acts as expected. For example, I can try to get its length:
[foo length]
At runtime, this will succeed if foo contains a NSString (or any other object that implements length; you can do duck typing), and throw an exception if it doesn't.
Darn it, Comex, you stole my thunder. Stefan, what Comex is pointing out, if you'd read Apple's Runtime Programming Guide (which you clearly have not) is dynamic message to method binding. In your earlier example, hidden in the background, is the very same process that Comex is pointing out in his post. Read the Runtime Guide; then post.
comex, check out Apple's specs for Clang: http://clang.llvm.org/docs/BlockLanguageSpec.txt
They introduced a new type called "block" that is similar to the function type. The 'id' is simply a block reference, or - in other words - a pointer. So congratulations, you managed to use a block reference in order to reference blocks! Squint a little, lower the lights, have a beer and it will look a lot like dynamic typing although it's really static. Much like a thai girl with Adam's apple, if you know what I mean :-)
Stefan,
Please tell me you're not serious about the Block post...you have been exposed to blocks, right?
Jim, dynamic message passing and dynamic typing are not related. Don't let the word "dynamic" confuse you. They are different concepts.
Oh, you can post even if you're still confused. It's OK, really.
Wow, these comments got slightly out of control...
Thanks for the informative post Tudor!
I'm also coming from a Python background and found Lua to be an easy language to pick up, and it's definitely very useful for rapid development.
I'm curious as to why you've put Corona in the same boat as PhoneGap, Titanium and RhoMobile?
I have actually been playing with Corona SDK recently, and it looks very promising for building native applications on iOS and Android using Lua, in particular for custom animations.
(btw, contrary to the theme of the above comments, I'm not trying to attack you in any way, I would just like to get your opinion :) )
Nick
@Nick: Yeah, it seems like the comments got a little out-of-control.
Thank you for piping in. Cheers!
Stefan,
Confused? No...
Your rather individualistic definition of dynamic typing ensures that to continue a discussion of Obj-C as a dynamic typed language would be pointless.
Stefan,
Some comments to your statements:
"any improvement on Obj-C is welcomed but Nu doesn't seem to do much about most of the shortcomings:
https://github.com/timburks/nu/blob/master/examples/MailDemo/nu/maildemo.nu"
Could you please elaborate. How does not address the shortcommings. The link show perfectly well the advantages of Nu over both
lua and Objective-C IMHO. I can try to condense more concretly why I think Nu is better suited.
1. Matches Objective-C syntax perfectly.
2. More natural syntax for closures.
3. Get the power of using a LISP. You can actually write LISP macros, which are very powerfull, which is not possible in Lua despite its lispiness.
4. Can be "baked"/converted to Objective-C code for tuning particular parts of the program.
5. Object model matches Objective-C object model perfectly because Nu was designed from the ground up for it instead of trying to match an existing language like Nu to it. MacRuby is essentially what iPhone Wax is and Tim Burks gets into a lot of detail of why that is not a good idea.
"And then there's variable name prefixing to indicate the type..."
No, @ and $ are used to indicate scope not type. Nu is dynamically typed you never indicate the type using any kind of prefix. @ is used for instance variables and $ for global variables. Nu got this from ruby. In a lot of ways Nu is ruby with Objective-C/LISP syntax.
With respect to the static vs dynamic discussion I think you are talking a bit passed each other. I hope I can help clarify a few points.
1. Objective-C is a superset of C, so all primitive types, structs etc are statically typed.
2. The smalltalk inspired addon which gives Objective-C an object system is actually dynamically typed but it supports static type hinting.
What does that mean? It means to help catch type mistakes you can write the type in the source code and get compiler warnings, to help you fix potential problems. Note however that it is just hints. I can point to a NSView object with a pointer having a NSString static type hint. It doesn't matter at runtime, I can send it NSView messages without any problems. To the runtime it looks no different than if I had used a NSView type hint at compile type. "id" means I don't care about what the type is, don't give me compiler warnings for sending the "wrong" message. If Objective-C's OO system was in fact statically typed then message passing would not be necessary. Objective-C could have used method invokation the same way as C++ and Java does. In a statically typed language you can't ivoke methods on an object which the compiler can't determine at compile time that it supports. Objective-C lets you send messages to objects which the compiler can't know at compile time whether the object will respond to or not.
Ok, let's discuss Nu:
1. it doesn't match the Obj-C syntax because it tries to be a Lisp (and fails at it, largely due to those silly Obj-C conventions that insists on keeping)
2. natural for whom? not Obj-C programmers
3. if you want the power of Lisp, just use Lisp instead of Nu and its lack of proper S-expressions. I mean, how do you explain something like: (10 times: (do (i) (set x (+ x 1)) (set y x))) ? Are numbers operators? Do labels have magic consequences? What is that, I don't even...
4. nubake doesn't do a "conversion" to Obj-C. It simply writes functions that return Nu code that needs to be interpreted by a Nu interpreter. I don't see the point in that, but the author seems to think that "this can be useful for simplifying and adding tamper-resistance to Nu applications".
5. If your goal is to use a language other than Obj-C but have Obj-C like object syntax, I guess Nu gets an extra point for doing that.
Here's what the Nu site has to say about those variable prefixes it calls "sigils":
'The use of sigils to indicate variable type. A leading "@" denotes instance variables, "$" marks global variables, and "__" marks a variable as a generated symbol'
So 2 for scope and one for some sort of type.
'id' is not a way to avoid compiler warnings. It's implemented as a pointer to a generic type. My guess is that the compiler will read a fixed size header at that location in memory and obtain the information it needs to read the whole object - which, obviously, can use a variable amount of memory depending on the class.
That's all fine and dandy, but if you call that "dynamic typing" you might as well call C a dynamically typed language because you can do the same thing with a "void *" and some pointer math.
Stefan, it feels like you are using a lot of strawmen here.
I don't think Nu tries to be a LISP. My understanding is that Tim Burks is basically a guy that liked ruby. He wanted a ruby that would fit well with Objective-C. Nu is a way of doing ruby in a way that fit nicely with naming conventions in Objective-C. Using LISP like syntax helped achieve this. Being LISP is not a goal in itself.
You say "fails to be a LISP", what exactly do you mean by that? Sure it is not regular LISP but it is LISPish enough to treat code as data and support macros. That is where most of the power of LISP comes from.
2.
(10 times: (do (i)
(set x (+ x 1))
(set y x)))
is more natural than say:
10:times(function(i)
x = x + 1
y = x
end)
Not that you can call methods on lua numbers like that. But you know if you could.
5. Yeah, but why would you want lua over Nu if you are doing iOS and OS X development and need to use API designed for Objective-C?
Sure Nu is not perfect, but I don't see what lua brings to the table in this context. Don't get me wrong I love lua, I use it everyday, but that is with C and C++ code which follow function naming conventions which match better with lua.
void * and id are not the same thing because you can not send arbitrary messages or invoke arbitrary functions on void.
"'id' is not a way to avoid compiler warnings. It's implemented as a pointer to a generic type. My guess is that the compiler will read a fixed size header at that location in memory and obtain the information it needs to read the whole object - which, obviously, can use a variable amount of memory depending on the class."
No Stefan, the compiler is not doing that. That is not what compilers do. You seem to confuse the compiler with the runtime. Basically all message sending to ObjC objects are done at runtime as if the object was of type id. [obj message:x] is essentially turned into
objc_msgSend(obj, "message:", x) C function call during compilation. objc_msgSend() takes arguments of type id. There are not different functions for NSString, NSArray, NSSet etc. In other words no static type checking. id contains a pointer to a class struct. objc_msgSend() will basically do a hashtable lookup with key "message:" for a function pointer and pass this function obj and x. The function will know how to interpret obj to fetch member data, because at this point we know the type. But this all happens at runtime. We didn't figure out the type at compile time.
If you are familiar with how dynamic languages like lua, ruby, python and javascript is implemented then this should all sound very familiar.
You're right, it's the runtime not the compiler that needs to identify the class of a generic object a certain id points to.
I don't see the relevance of the message sending part of your analysis. Once the object's class has been identified, the rest is easy.
Let's dig some more in the objc_msgSend() function (actually a class of functions) by looking at this file: http://www.opensource.apple.com/source/gcc/gcc-5666.3/gcc/objc/objc-act.c . Here are some interesting lines:
objc_object_reference = xref_tag (RECORD_TYPE, objc_object_id);
objc_object_type = build_pointer_type (objc_object_reference);
type = build_function_type (objc_object_type,tree_cons (NULL_TREE, objc_object_type, tree_cons (NULL_TREE, objc_selector_type, NULL_TREE)));
umsg_decl = builtin_function (TAG_MSGSEND, type, 0, NOT_BUILT_IN, NULL, NULL_TREE);
And from http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW1 - Apple's specs - we have this piece of info:
"id is defined as pointer to an object data structure:
typedef struct objc_object {
Class isa;
} *id;
Every object thus has an isa variable that tells it of what class it is an instance. Since the Class type is itself defined as a pointer:
typedef struct objc_class *Class;"
So there, not a "void *" but a struct pointer. The runtime is then able to identify the class and do whatever it needs to do. Now let's discuss the "dynamic typing" again. The dynamic part in Obj-C happens only at runtime and only if requested specifically with a certain generic object/class type - 'id'. That is not what I expect from dynamic typing. I expect compile/interpretation time typing without me assigning any type to the variable. To get such a behavior from Obj-C you'd need to change the syntax so that untyped variables are automatically considered of type id. Even then, it would only work for objects and classes. Quite a limitation. However, there must be some C trick to include the other types in this mechanism. Some pointer to a union or struct maybe?
Anyway, the mechanisms to implement a dynamic typing system are there, but whoever controls the language specs is not interested in providing this to the programmers. They just did the runtime part because they need it.
Stefan,
That's similar to how most VMs implement dynamic typing. I'm not familiar with Lua, but Python has:
#define PyObject_HEAD \
_PyObject_HEAD_EXTRA \
Py_ssize_t ob_refcnt; \
struct _typeobject *ob_type;
typedef struct _object {
PyObject_HEAD
} PyObject;
In this case, ob_type is equivalent to Objective-C's isa.
>The dynamic part in Obj-C happens only at runtime
>and only if requested specifically with a certain
>generic object/class type - 'id'.
>That is not what I expect from dynamic typing.
As I said earlier, your definition is narrower than everybody else's definition. This makes debate difficult and ultimately pointless. We'll continue to disagree as we don't agree on a definition.
More importantly, how do I get these comments to stop sending me email?
Stefan,
The point you make, "...it's the runtime not the compiler that needs to identify the class of a generic object a certain id points to. " works with your earlier post of Wikipedia's article on Dynamic Typing, which states,
"A programming language is said to be dynamically typed when the majority of its type checking is performed at run-time as opposed to at compile-time."
By not resolving the object until runtime, Obj-C is following the traits of Dynamic Typing. How many objects to be resolved at runtime depends upon whether they are statically or dynamically--using "id"--typed.
And when you write,
"I don't see the relevance of the message sending part of your analysis."
you're not seeing that by doing so, Obj-C only deepens it Dynamic Typing traits, specifically,
"In dynamic typing, values have types but variables do not; that is, a variable can refer to a value of any type." As a generic type, id can point to anything. How id is resolved in the runtime environment to an object is the interesting point.
While an object's "isa" points to its Class, a Class's "isa" points to the object's meta Class. In the runtime environment, an object’s meta Class' "isa" pointer points up the class hierarchy until eventually, if no match is found, it is forwarded, or points, to the root class of the hierarchy. The Objective-C runtime environment permits the sending of a message to an object that may not respond and, rather than responding or simply dropping the message, an object can forward the message to an object that can respond. Messaging is dependent upon the "isa" pointer.
More importantly for "id", while one can separate dynamic typing from messaging, as you mentioned earlier, such a separation in Obj-C is cosmetic since both matching an "id" to an actual object type and dynamic message binding are part of the same process, all of which starts with the "isa" pointer.
This may not fit what you might expect from dynamic typing, but it does fit the general definition as exampled by the entry you linked to in Wikipedia.
And this has been one of the most interesting dialogues I've had in awhile that forced me to learn more about Obj-C and its dynamic and runtime traits.
This is an extremely useful article relevant to the debate occurring in this thread.
http://blog.steveklabnik.com/what-to-know-before-debating-type-systems-0
comex, you're right.
Terry, you're now able to unsubscribe from email notifications through a link in the email.
Jim, message passing only proves class inheritance. On the other hand, I'm willing to accept that 'id' provides a dynamic type system.
Jon, thanks for that article. It helped me narrow down my main complaint to the lack of implicit typing in Obj-C. I can understand that the mix of dynamic and static type systems can be blamed on the C compatibility layer, but there's no excuse for the lack of implicit typing for objects.
I just want to add that.
True that Objective-C is not a pure dynamic type language but it is still a very dynamic language.
u can do this in javascript.
var i = 1;
but you can't do this in Objective-C.
id i = 1;
Second point I want to make is that, Objective C is still to me the best languages to write in, especially for iOS development. There's still valid reason to add scripting language to Objective C, especially for game development. For those who felt against it partly because of its syntax, its too unfortunate.
Never had you been able to mix C/C++ into a language directly. And still use meta programming. And this is why Objective C is fast. It had runtime, but no byte code. Its all C underneath a great language.
Third and lastly, Objective C strength truly shine when it come to its API design and engineering. You write less code, more powerful code not just because of the language, but also the API. NSNotificationCenter, Core Animation, Core Graphics, Core Foundation to name a few.
Lua, by its own, is pretty hard to write and requires you to rethink everything. Imagine everything is a table, no class or object, they are all fake up using tables. This is Lua at it fundamental.
So to sum up, I couldn't agree with the argument of this blog post and those who are against Objective C.
lxcid, that's duck typing that js has and Obj-C lacks.
In order to understand the various shortcomings of Obj-C you need to expand your horizon and learn a few other languages. I promise you'll have fun ;-)
Yes there should realize the reader to RSS my feed to RSS commentary, quite simply
Leave a Comment :
Leave a Comment