lua 字符串索引表并解压

ast*_*r94 5 lua

我在 lua 中有一个表,其中填充了带有字符串索引的项目。不幸的是,众所周知,lua 并没有以完美(无头痛)的方式处理这个问题,因为#运算符 和table.unpack()无法工作

t = {}
t['b'] = 2
t['a'] = 1

print("l:", #t)
print("t:", table.unpack(t))
Run Code Online (Sandbox Code Playgroud)

返回:

l:  0
t:
Run Code Online (Sandbox Code Playgroud)

有解决方案来计算项目(即:计算 lua 中的字符串索引表),但我无法找到替代品,table.unpack()有人可以帮忙吗?

所需的输出是:(2 1与我添加它们的顺序相同)

Nic*_*las 4

Lua 表以任意顺序存储非数组元素。如果不控制生成元素的顺序,解包就毫无价值。因此不可能有效地解压表的非数组部分。

现在,你仍然可以这样做;您只是无法控制订单。所以不清楚重点是什么,但代码如下所示:

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
Run Code Online (Sandbox Code Playgroud)

但是,如果您有一个数组表,其中包含要提取的键列表以及提取它们的顺序,那么您可以编写一个使用此类表的 unpack 函数:

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"}))
Run Code Online (Sandbox Code Playgroud)