将字符串保存在 lua table 中

save strings in lua table

有人知道将键和值保存到 table 的解决方案吗?我的想法行不通,因为table的长度是0,应该是3.

local newstr = "3 = Hello, 67 = Hi, 2 = Bye"

a = {}
for k,v in newstr:gmatch "(%d+)%s*=%s*(%a+)" do 
    --print(k,v)
    a[k] = v
end

print(#a)

输出正确。

运行 for k,v in pairs(a) do print(k,v) end 检查您的 table.

的内容

问题是长度运算符,默认情况下它不能用于获取任何 table 的元素数量,但序列。

请参考Lua手册:https://www.lua.org/manual/5.4/manual.html#3.4.7

When t is a sequence, #t returns its only border, which corresponds to the intuitive notion of the length of the sequence. When t is not a sequence, #t can return any of its borders. (The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys.)

仅当您知道 t 是一个序列时才使用长度运算符。这是一个 Lua table 整数索引 1,..n 没有任何间隙。

您没有序列,因为您只使用了非数字键。这就是为什么 #a 是 0

获取任何 table 元素数量的唯一安全方法是对它们进行计数。

local count = 0
for i,v in pairs(a) do
  count = count + 1
end

您可以将@Piglet' 代码放在 a 的元 table 中作为方法 __len,用于 table 使用长度运算符 [=13] 的键计数=].

local newstr = "3 = Hello, 67 = Hi, 2 = Bye"

local a = setmetatable({},{__len = function(tab)
local count = 0
for i, v in pairs(tab) do
 count = count + 1
end
return count
end})

for k,v in newstr:gmatch "(%d+)%s*=%s*(%a+)" do 
    --print(k,v)
    a[k] = v
end

print(#a) -- puts out: 3

如果 table 仅包含一个序列,#a 使用方法 __len 的输出甚至是正确的。

您可以在 Lua 沙盒中在线查看...
...复制和粘贴。
就像我一样。