Lua将字符串转换为表

我有一个需要被转换为表的字符串

    notes = "0,5,10,16"

如果我需要当前 notes 的第3个值,那么它就是10

    value = notes[3]
点赞
用户4984564
用户4984564

对于示例字符串,您可以执行以下操作

local notes_tab = {}
for note in notes:gmatch("%d*") do
   table.insert(notes_tab, tonumber(note))
end
2019-10-24 06:55:12
用户11298075
用户11298075

我们可以改变所有字符串的 __index 元方法以返回用逗号分隔的第 n 个元素。然而,这样做会出现一个问题,我们不能再像 notes:gmatch(",?1,?") 那样使用它了。参见这个老的 StackOverflow 帖子。可以通过检查是否使用字符串或其他值调用了 __index 来解决问题。

notes = "0,5,10,16"

getmetatable("").__index = function(str, key)
    if type(key) == "string" then
        return string[key]
    else
        next_value = string.gmatch(str, "[^,]+")
        for i=1, key - 1 do
            next_value()
        end
        return next_value()
    end
end

print(notes[3])  --> 10

string.gmatch 返回一个函数,我们可以迭代它,因此调用它 n 次将导致返回第 n 个数字。

for 循环确保所有我们想要的数字之前都已经被 gmatch 迭代了。

根据您想要对数字执行的操作,您可以将其作为字符串返回或立即将其转换为数字。

2019-10-24 07:13:43
用户107090
用户107090

如果你信任这些字符串,你可以重用 Lua 解析器:

notes = "0,5,10,16"
notes = load("return {"..notes.."}")()
print(notes[3])
2019-10-24 23:28:42