lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

And JavaScript is not just for web pages.. Qt native scripting is done with it.

(I did tip them on Lua, but they said the decision had already been made..)

26.1.2005 kello 00:57, David Given kirjoitti:

Okay, technically this is off-topic, but given the ongoing discussions of language design it probably serves as a useful cautionary tale on how to take a reasonably good language and louse up a feature beyond all recognition.

I also program in Javascript. Javascript is, at its core, actually quite a nice language, strikingly similar to Lua but with a C-like syntax. (In fact, I think it should be possible to statically translate Javascript into Lua by simply converting the syntax.)

Javascript has two associative array types: Objects, which are created with {}, and Arrays, which are created with []. In fact, they're both the same kind of underlying thing; Arrays are just Objects with helper methods attached.

Object properties can be accessed by using object.propertyname or object["propertyname"], just like Lua. The second syntax makes them look just like associative arrays, and indeed they're very useful as such. However, just like Lua you end up with problems in that your data collides with your method names.

But that's all right, because you don't have to use strings. You can use them as associative arrays with other types, too. Dates, integers, floating point numbers, and so on.

They even work with objects. Sort of.

var o1 = {name: "object1"}
var o2 = {name: "obejct2"}
var assocarray = {}
assocarray[o1] = 1
assocarray[o2] = 2

This runs fine. Unfortunately...

print(assocarray[o1]) --> 2
print(assocarray[o2]) --> 2

What's going on here?

Closer inspection of the ECMA standard reveals that Objects and Arrays are, in fact, only keyed on strings. They do an implicit string conversion when you pass in the key, using the built-in toString() method. A bit of experimentation reveals...

print(o1.toString()) --> "[object Object]"
print(o2.toString()) --> "[object Object]"

Aaaah! *All* objects, no matter what their content, become the *same* string! Which means that if you use them as keys to an associative array, all objects are the *same* key!

Now, *that*'s braindead. You probably won't be surprised to find out that Javascript has no proper hashing ability at all; and that o1==o2, o1<o2, and o1>o2 are all false; and so making an associative array that can be keyed on any arbitrary object is actually rather hard. (Which I need to do. I have a solution, though.)

It's definitely damning with faint praise to say that Lua manages to avoid this kind of mishap, but can I just say that on the whole I've found the level of thought involved with the Lua design to be most refreshing.

[insert interesting .sig here]