将表字符串转换为实际表

时间:2017-03-10 05:20:08

标签: lua

local t = "{{2173,1},{2160,5}}"
print(#t) -- 19?? wrong

如何转换为以数字显示?

local t = {{2173,1},{2160,5}}
print(#t) -- 2 correct

2 个答案:

答案 0 :(得分:4)

您可以通过loadloadstring(取决于您的Lua版本)运行字符串,该字符串将返回您要查找的表格:

local t = "{{2173,1},{2160,5}}"
t = (loadstring or load)("return "..t)()
print(#t) -- 2

答案 1 :(得分:2)

以下是您提供的输入的临时解决方案:

local s = "{{2173,1},{2160,5}}"
local t = {}
local n = 0
for a,b in s:gmatch("(%d+),(%d+)") do
        n = n + 1
        t[n] = {a,b}
end
for k,v in ipairs(t) do print(k,v[1],v[2]) end