lua 字符串索引表并解包

标签 lua

我在 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/

相关文章:

xml - 如何正确使用 Lua-XML 解析器 (lua expat/LuaXml)

lua - 如何在 love2d 中创建文本框

linux - 如何在同一个linux系统上拥有不同的lua版本

lua - "For each"在带有键值对的 lua 表中循环

c - 如何从 C 弹出/清理 Lua 调用堆栈

dynamic - Lua函数调用,参数列表在字符串中

javascript - 是否可以使用 Lua/Javascript 脚本使用新变量扩展 C# 对象?

string - 将整数转换为lua中的字符串?

oauth-2.0 - 无法使用 Bearer Token 通过 Keycloak 进行身份验证

lua - 如何使用 Lua 脚本在 Redis 中传递换行符