0

Is there a way to index an object in JavaScript like a Metatable in Lua?

Like for example:

var obj = {a:"a",b:"b",properties:{c:"c",d:"d"}}
metatable(obj,obj.properties) // Make it so that if you try to index something that's not inside the object it will go to the parameter one
console.log(obj.a) // "a"
console.log(obj.c) // "c"

To LMD: How do I do it for multiple objects? Like for example:

var objs = [
obj1 = {name:"Button";class:"button";properties:{text:"Press this"}]
]
for (i in objs){
metatable(objs[i],objs[i].properties)
}
console.log(objs.obj1.text) // "Press this"

1 Answers1

1

Yes: JavaScript has prototypes. These aren't exactly the same as Lua but can be used for simple metatable indexing purposes. One way to achieve your example would be as follows:

const properties = {c: "c", d: "d"} // prototype
const obj = Object.create(properties) // create object with prototype
obj.a = "a"; obj.b = "b";
console.log(obj.a) // "a"
console.log(obj.c) // "c"

Or if you already have the objects given, as in your second example, you may want to use Object.setPrototypeOf(object, prototype), which is comparable to setmetatable(object, {__index = prototype}) in Lua:

const objs = [{name:"Button", class:"button", properties: {text:"Press this"}}]
for (const obj of objs) Object.setPrototypeOf(obj, obj.properties)
console.log(objs[0].text) // "Press this"

that is, the metatable function you've been searching for literally is Object.setPrototypeOf!

Luatic
  • 8,513
  • 2
  • 13
  • 34