Last active
December 3, 2019 02:06
-
-
Save d3x0r/1e466f61bad9f8192f872bd5637a8beb to your computer and use it in GitHub Desktop.
Dynamic object context(?)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a snipper to test the idea of context-sensitive commands.... | |
// | |
// The command is `n` which is a short for 'go north' | |
// from a REPL standpoint, just taking the input 'n' and passing it to vm.runInContext() works | |
// | |
// However, that also limits to just that sandbox for commands, but I'd want at least 2... | |
// that is 'mine' or the current one of the object, and the other for the room that the object | |
// is in... | |
// But then I guess also extension provided by attachments (aim camera (at) target) if you're | |
// holding a camera... | |
const vm = require('vm'); | |
var context1 = { | |
get n() { | |
console.log( "Leaving north..." ); | |
} | |
, run(o) { | |
o.doCommand.call(this); | |
} | |
, next : null | |
} | |
var context2 = { | |
get n() { | |
console.log( "No Exit in that direction..." ); | |
} | |
, run(o) { | |
o.doCommand.call(this); | |
} | |
, next : null | |
} | |
var myObject = { | |
doCommand() { | |
this.n; | |
} | |
} | |
var myObject2 = { | |
doCommand() { | |
// this 'n' is always undefined.... although 'this.n' does work | |
n; | |
} | |
} | |
var x = {get n() { console.log('North.');}}; | |
// if in node context 'this' has to be 'global' | |
Object.getOwnPropertyNames( x ).forEach( (prop) => Object.defineProperty(this, prop, Object.getOwnPropertyDescriptor(x, prop)) ); | |
n; | |
context1 = vm.createContext( context1 ); | |
context2 = vm.createContext( context2 ); | |
// this doesn't work form myObject2... | |
context1.run(myObject ) | |
context2.run(myObject ) | |
// this doesn't use 'my object' but runs the 'n' getter directly... | |
vm.runInContext( "n", context1 ); | |
vm.runInContext( "n", context2 ); | |
// these don't work.... | |
if(0) { | |
context1.next = myObject2.doCommand; | |
vm.runInContext( "next.call(this)", context1 ); | |
context2.next = myObject2.doCommand; | |
vm.runInContext( "next.call(this)", context2 ); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment