如何在Fennel中变异顺序表的值?

huangapple go评论43阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月19日 18:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定