英文:
How to mutate sequential table value in Fennel?
问题
我有一个在Fennel中的表格,看起来像这样:
(local tbl [1 [:a :b :c] 3])
我想要将内部表格中的值 :c
更改为 :e
。
在Lua中,我可以简单地执行如下操作:
tbl[2][3] = "e"
然而,在Fennel中,似乎无法直接通过以下方式更改表中的值:
(set (. (. tbl 2) 3) :e)
我可以想到以下方法,但它看起来很繁琐,特别是当我需要执行大量类似的操作时:
(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) ; removed-table -> [:a :b :e]
(table.insert tbl outter-index removed-table) ; tbl -> [1 [:a :b :e] 3]
是否有一种方法可以在Fennel中更改表中的值?如果不能,请问有没有比我所做的更简单的方法?
英文:
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?
答案1
得分: 1
你正在寻找tset
来设置表字段:
(local tbl [1 [:a :b :c] 3]) ; 构造本地表 tbl = {1, {"a", "b", "c"}, 3}
(tset tbl 2 3 :e) ; 设置 tbl[2][3] = "e"
(print (. tbl 2 3)) ; 打印 tbl[2][3] 以验证它是否生效
这将打印 e
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论