我在 lua 中有一个表,由带有字符串索引的项目填充。不幸的是,众所周知,lua 并没有以完美( headless 痛)的方式处理这个问题,因为 #
运算符和 table.unpack()
不会工作
t = {}
t['b'] = 2
t['a'] = 1
print("l:", #t)
print("t:", table.unpack(t))
返回:
l: 0
t:
有计算项目的解决方案(即: counting string-indexed tables in lua ),但我找不到
table.unpack()
的替代品有人可以帮忙吗?所需的输出是:
2 1
(与我添加它们的顺序相同)
最佳答案
Lua 表以任意顺序存储非数组元素。如果没有对生成元素的顺序进行一些控制,解包是毫无值(value)的。因此,不可能有效地解压缩表的非数组部分。
现在,你仍然可以做到;你只是对订单没有任何控制权。所以不清楚重点是什么,但代码看起来像这样:
function unpack_unordered_recursive(tbl, key)
local new_key, value = next(tbl, key)
if new_key == nil then return end
return value, unpack_unordered_recursive(tbl, new_key)
end
function unpack_unordered(tbl)
local key, value = next(tbl)
if key == nil then return end
return value, unpack_unordered_recursive(tbl, key)
end
但是,如果您有一个数组表,其中包含要提取的键列表以及提取它们的顺序,那么您可以编写一个使用此类表的解包函数:
function unpack_indices(tbl, indices, curr_ix)
if curr_ix == nil then
return unpack_indices(tbl, indices, 1)
end
if curr_ix > #indices then
return
end
--Recursive call
return tbl[indices[curr_ix]], unpack_indices(tbl, indices, curr_ix + 1)
end
print("t:", unpack_indices(t, {"b", "a"}))
关于lua 字符串索引表并解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60727950/