Indexing arrays programatically with a variable
Hello,
we have a case where we want to access an array element programatically:
(set [some_index 3])
(reval my_signal.my_array<some_index> 0)
This however does not work. It is reading the whole my_signal.my_array<some_index> as a variable name and I can't seem to figure out how to make it evaluate some_index so that eventually compiles to this: my_signal.my_array<3>.
I managed to do it by defining a custom operator:
index_signal = lambda seval, args: seval.eval(
str(args[0]) + "<" + str(seval.eval(args[1])) + ">"
)
wal.register_operator("index_signal", index_signal)
then doing
(define indexed_value (index_signal "my_signal.my_array" some_index))
Only then I can successfully evaluate the index.
It would be nice if whatever between <> is evaluated rather then being taken as is.
Hi,
Thanks for being patient, I had a few very busy weeks.
I had indexing problems like this myself. You can solve cases like this with a similar idea to index_signal in pure WAL for example, with a macro like this.
(defmacro get-index [signal idx]
`(get (symbol-add ',signal "<" ,idx ">")))
Evaluating whatever is between <> would be handy. However, this could potentially clash with signals in the waveform. I will think about it, if you have any ideas feel free to share :)
Thank you for the reply.
I see. I guess I wasn't aware of the symbol-add operator. So this is what we use to create a symbol that we build at runtime, am I correct?
Yes, with symbol-add you can concatenate multiple symbols, strings, or numbers at runtime. E.g.
>-> (symbol-add 'a 'b 3 (+ 2 2) "-def")
ab34-def
Great! Maybe consider adding it to the documentation so other people can see the feature. You can close the issue.