Lua中编辑具有不确定维度的多维表
2021-10-28 1:14:20
收藏:0
阅读:148
评论:1
我想要能够访问和编辑用户生成的表中的值,这个表可以有任意数量的维度。
比如,对于这个嵌套表:
table = {
'1',
{
'2.1',
'2.2'
},
{
{
'3.1.1',
'3.1.2'
},
'3.2'
},
}
我会有另一个表,它包含所需数据的位置,
loc = {3, 1, 2}
理想情况下,我希望能够访问并编辑表中的值,类似于使用table[3][1][2]
,但利用loc
表,
print(table[loc[1]][loc[2]][loc[3]]) --返回3.1.2
print(table[loc]) --这是类似于采用每个索引成员的表,以便按顺序获取表中的每个元素
我还想能够编辑这个表。
table[loc] = {'3.1.2.1', '3.1.2.2'}
我需要能够编辑全局表,所以不能使用this reddit thread中列出的方法,也尚未找到使用元表的正确方式。感谢您的帮助,谢谢。
原文链接 https://stackoverflow.com/questions/69747122
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
我认为你可以为此编写一个额外的函数。
function TreeGetValue(Tree, Location) local CorrectTree = true local Index = 1 local Dimensions = #Location local SubTable = Tree local Value --根据location找到最深的表 while (CorrectTree and (Index < Dimensions)) do local IndexedValue = SubTable[Location[Index]] if (type(IndexedValue) == "table") then SubTable = IndexedValue Index = Index + 1 else CorrectTree = false end end --获取最后一个值,无论其类型如何 if CorrectTree then Value = SubTable[Location[Index]] end return Value end
在此处,我们假定树最初的格式是正确的。 如果我们发现任何问题,我们将标志
CorrectTree
设置为false,以便立即停止。我们需要确保每个维度都有一个表,以便从中索引值。
> TreeGetValue(table, loc) 3.1.2
显然,编写“set”函数也很容易:
function TreeSetValue (Tree, Location, NewValue) local Index = 1 local Dimensions = #Location local SubTable = Tree --根据location找到最深的表 while (Index < Dimensions) do local IndexedValue = SubTable[Location[Index]] --如有需要,创建新的子表 if (IndexedValue == nil) then IndexedValue = {} SubTable[Location[Index]] = IndexedValue end SubTable = IndexedValue Index = Index + 1 end --设置或替换以前的值 SubTable[Location[Index]] = NewValue end
然后使用测试数据对其进行测试:
> TreeGetValue(table, loc) 3.1.2 > TreeSetValue(table, loc, "NEW-VALUE") > TreeGetValue(table, loc) NEW-VALUE