Page 1 of 1

[Javascript] __Index metamethod

Posted: Sat Aug 18, 2012 1:32 pm
by Nixola
Does Javascript have metatables and/or metamethods, like Lua? If it doesn't, how can I achieve a rasult similar to __index?

Re: [Javascript] __Index metamethod

Posted: Sat Aug 18, 2012 5:48 pm
by Roland_Yonaba
Hi,
Well I do not think Javascript have an __index feature.
Though, the closest feature, IMHO, is the prototype feature.

Re: [Javascript] __Index metamethod

Posted: Sun Aug 19, 2012 3:24 am
by Inny
The answer is it depends on what you're using it for.

If it's to simulate a class inheritance scheme, you use the function.prototype.member syntax and copying between objects.

If it's to simulate python's getattr/setattr, then no, Javascript doesn't have that kind of feature yet but the next ECMA standard is supposed to have one (get and set functions).

Re: [Javascript] __Index metamethod

Posted: Sun Aug 19, 2012 8:45 am
by Nixola

Code: Select all

If it's to simulate python's getattr/setattr, then no, Javascript doesn't have that kind of feature yet but the next ECMA standard is supposed to have one (get and set functions).
I don't know Python, so I don't know what you're talking about... I want to set a default table value instead of "undefined", I only have one table and no objects, so I don't have to inherit anything; it's almost exactly like the following:

Code: Select all

var t = ['NULL', 'Mark', 'Jack'];
n = {USERCOUNT};  //I don't know if this syntax is common or if it's relative to the forum I'm editing, anyway that gets a number equal to the number of users
for (i = 1; i <=n; i++) {
document.write(t[i]+"<br />");
}
If the Usercount increases and I don't update the table (I can't get it automatically) I get:

Code: Select all

Mark
Jack
undefined
but I'd prefer to set something else instead of undefined...

Re: [Javascript] __Index metamethod

Posted: Mon Aug 20, 2012 2:53 am
by Inny
I think the closest approximation is the Firefox extentions to javascript, one of which is __noSuchMethod__. However, being both javascript and firefox, and not lua or love, it's probably way off topic for this forum. You might want to search around on StackOverflow for a while to see what answers you can find.

Re: [Javascript] __Index metamethod

Posted: Mon Aug 20, 2012 8:49 am
by Nixola
Inny wrote:it's probably way off topic for this forum
That's why I posted in "General" and not in Support ;)
Anyway, if it's only Firefox that can help me I think that "undefined" instead of the username will be ok. Thanks, anyway