I wanted to implement a function to read from a table the value of a sequence index for a key.
A hypothetical example:
Instead of this:
func `[]=`*[V](form: FormTableRef, key: string, pair: tuple[index: BackwardsIndex, value: V]) =
form.table[key][pair[0]] = pair[1]
formData["test"] = (0, "abc")
This work fine.
But I want this:
func `[][]=`*[V](form: FormTableRef, key: string, index: BackwardsIndex, value: V) =
form.table[key][index] = value
formData["test"][0] = "abc"
But the last function doesn't work!
Any idea how to make this work?
What about
func `[]=`*[V](form: FormTableRef, key: string, index: BackwardsIndex, value: V) =
form.table[key][index] = value
formData["test", 0] = "abc"
I think that this should work for you
Make it a two-step process:
import tables
type
FormTableSeq[T] = seq[T]
FormTableRef[T] = ref object
table: Table[string, FormTableSeq[T]]
proc `[]`*[T](f: FormTableRef[T], key: string): var seq[T] =
f.table[key]
proc `[]`*[T](s: FormTableSeq[T], index: BackwardsIndex): T =
s[index]
proc `[]=`*[T](s: FormTableSeq[T], index: BackwardsIndex, val: T) =
s[index] = val
var formData = FormTableRef[int]()
formData.table["three"] = @[ 3, 7, 9 ]
formData.table["ten"] = @[ 10, 20, 30 ]
echo formData["three"][1]
formData["three"][2] = 6
echo formData["three"][2]
Thanks @Yardanico, I also found out that the httpcore module has a similar notation: https://github.com/nim-lang/Nim/blob/version-1-4/lib/pure/httpcore.nim#L156
It works with a small change:
func `[]=`*[V](form: FormTableRef, key: string, value: V) =
form.table[key][0] = value
func `[]=`*[V](form: FormTableRef, key: string, index: int | BackwardsIndex, value: V) =
form.table[key][index] = value
formData["test"] = "abc"
formData["test", 0] = "def"
formData["test", 1] = "ghi"
formData["test", ^1] = "jkl"
The goal is to replace tables with duplicate keys that were deprecated in version 1.4.