I have a table in Fennel that looks like this
(local tbl [1 [:a :b :c] 3])
I want to change the value :c
in the inner table to :e
.
In Lua I could do something simple as
tbl[2][3] = "e"
However, for Fennel it seems that I can't mutate the value from the table directly using something like this
(set (. (. tbl 2) 3) :e)
I could come up with the following, but it looks cumbersome especially when I need to perform a big number of similar operations
(local (outter-index inner-index substitute-value) (values 2 3 "e"))
(local removed-table (table.remove tbl outter-index)) ; removed-table -> [:a :b :c]
(table.remove removed-table inner-index) ; removed-table -> [:a :b]
(table.insert removed-table inner-index substitute-value) ; remove-table -> [:a :b :e]
(table.insert tbl outter-index removed-table) ; tbl -> [1 [:a :b :e] 3]
Is there a way to mutate a value in table in Fennel at all? Or if not just to make it simpler than I did?
You're looking for tset
to set a table field:
(local tbl [1 [:a :b :c] 3]) ; construct local tbl = {1, {"a", "b", "c"}, 3}
(tset tbl 2 3 :e) ; set tbl[2][3] = "e"
(print (. tbl 2 3)) ; print tbl[2][3] to verify that it worked
This will print e
.