【发布时间】:2018-10-20 20:15:00
【问题描述】:
我发现了一个与此类似的问题,但给出的答案不适用于我的情况。
让我解释一下:
我正在开发一个视觉小说风格的文本框作家。基本功能是:从动态 texfield 'dialogueText' 读取文本,将其存储为字符串,清除文本框并添加回存储的字符串字符。它工作得很好,但我想要替换双括号之间的文本的功能,例如((playerName)),括号中指定的变量的值。将括号之间的内容保存为字符串也可以,但是我必须找到一种方法来打印括号之间指定的变量的值。
例子:
var playerName:String = "Anon";
function playFrame(frame:String):Function {
return function(evt:Event = null):void{
...
dialogueLine = dialogueText.text;
for(var i:int = 0; i < dialogueLine.split("((").length - 1; i++){
var dialogueVar:String = dialogueLine.substring(dialogueLine.indexOf("((") + 2, dialogueLine.indexOf("))"));
//dialogueVar now contains whatever variable name is specified between (( ))
dialogueLine = dialogueLine.split("((" + dialogueVar + "))").join(***);
//In join, *** has to be something that uses dialogueVar to look up a variable with name 'dialogueVar' (e.g. playerName), and then give it's value (which in this case would be 'Anon')
}
dialogueText.text = "";
...
}
}
有人建议我为此使用 this[dialogueVar],但在使用 trace() 对其进行测试时,我得到“未定义”。有没有人可以选择不为每个可能的变量硬编码 switch 语句?
【问题讨论】:
-
我强烈反对使用闭包(您可以在其他函数中创建未命名的未绑定函数),原因有几个。其中之一是 this 引用,在闭包内部使用,它指向谁知道确切的位置,因为闭包没有绑定到任何特定对象。
-
然后,您需要一个对象,其中包含您想要的所有变量的集合,例如 var sessionVars:Object = {playerName:"Anon", playerGender:"F"};然后你得到一个带有 var aValue:String = sessionVars[variableName]; 的变量
-
我使用闭包的原因是因为我必须能够使用特定参数调用playFrame,即'next'、'prev'和要跳转到的帧标签的名称。据我所知,这是唯一可行的方法。不过,您使用对象对变量进行分组的建议似乎很有希望,我会试一试!
标签: string actionscript-3 var