【问题标题】:multi key tuple to map a multi value tuple in Lua多键元组映射 Lua 中的多值元组
【发布时间】:2019-03-08 12:35:15
【问题描述】:

Lua 中是否有一个库支持从元组到元组的映射?我有一个键 {a,b,c} 来映射到一个值 {c,d,e} 有一些库,例如 http://lua-users.org/wiki/MultipleKeyIndexing 用于多键,但没有值是元组的地方。

【问题讨论】:

  • 将您的元组转换为字符串tostring(a)..";"..tostring(b)..";"..tostring(c) 并将此字符串用作索引。
  • 我没有看到链接库中值的类型有任何限制。

标签: lua


【解决方案1】:

这是使用 Egor 建议通过字符串连接生成密钥的一种方法。为表格制作自己的简单插入和获取方法,t。

local a, b, c = 10, 20, 30
local d, e, f = 100, 200, 300

local t = {}
t.key = function (k)
  local key = ""
  for _,v in ipairs(k) do
     key = key .. tostring(v) .. ";"
   end
   return key
end
t.set = function (k, v)
  local key = t.key(k)
  t[key] = v
end
t.get = function (k)
  local key = t.key(k)
  return t[key]
end

t.set ({a, b, c}, {d, e, f})           -- using variables
t.set ({40, 50, 60}, {400, 500, 600})  -- using constants

local w = t.get ({a, b, c})               -- using variables
local x = t.get ({40, 50, 60})            -- using constants

print(w[1], w[2], w[3])                   -- 100    200    300
print(x[1], x[2], x[3])                   -- 400    500    600

【讨论】:

  • 您的“插入”与table.insert 非常不同。请用“set”作为“get”的补语。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2014-10-06
  • 2013-06-11
  • 1970-01-01
  • 2019-05-09
  • 2012-09-08
相关资源
最近更新 更多