@Helgef: If only you'd read/experimented more, you could have uncovered this ...
Code: Select all
;AHK v2
;create a map with a customisable default value
oMap := Map()
oMap.DefineProp("__Item", {Get:Func("MyFuncGet"), Set:Func("MyFuncSet")})
oMap.DefaultValue := "MyDefaultValue"
MsgBox(oMap["UknKey"])
oMap["MyKey"] := "MyValue"
MsgBox(oMap["MyKey"])
return
MyFuncGet(obj, key)
{
;MsgBox(A_ThisFunc "`r`n" key)
if !obj.Has(key)
return obj.DefaultValue
else
return Map.Prototype.GetOwnPropDesc("__Item").Get.Call(obj, key)
}
MyFuncSet(obj, value, key)
{
;MsgBox(A_ThisFunc "`r`n" key "`r`n" value)
return Map.Prototype.GetOwnPropDesc("__Item").Set.Call(obj, value, key)
}
Thanks. Your example is quite structurally different to what I was imagining, but great all the same. I've rewritten it without the fat-arrow functions, to make it clearer what's going on behind the scenes.
Code: Select all
oMap := new m("MyDefaultValue")
oMap.default := "MyDefaultValue"
MsgBox(oMap["UknKey"])
oMap["MyKey"] := "MyValue"
MsgBox(oMap["MyKey"])
MsgBox(oMap.default)
oMap.default := "NewDefaultValue"
MsgBox(oMap["UknKey"])
return
class m extends map
{
;__new(default := "") => this.default := default
;rewritten without fat-arrow functions:
__new(default := "")
{
return this.default := default
;this.default := default ;can we omit 'return'?
}
;__item[key] => this.has(key) ? base[key] : this.default
;rewritten without fat-arrow functions:
__item[key]
{
get
{
;return this.has(key) ? base[key] : this.default
return this.has(key) ? base.__Item[key] : this.default ;equivalent to line above
}
set
{
;return base[key] := value
return base.__Item[key] := value ;equivalent to line above
}
}
}
I had noticed two examples, here, but wasn't trying to use the 'extends' approach:
Objects - Definition & Usage | AutoHotkey v2
https://lexikos.github.io/v2/docs/Objects.htm
class Array2D extends Array
...
ShorterProperty[] => Expression which calculates property value
@nnnik/Helgef/others: Btw if default value functionality were made built-in for maps/arrays, what would you prefer?
One of these? Something else? Cheers.
obj.Default := "value"
obj.DefaultValue := "value" [perhaps this]
obj.SetDefault("value")
obj.SetDefaultValue("value")