【问题标题】:Lua string to tableLua 字符串到表
【发布时间】:2020-02-20 06:26:35
【问题描述】:

我有一个字符串需要读取为表格

    notes = "0,5,10,16"

所以如果我需要当前音符的第三个值,即 10

    value = notes[3]

【问题讨论】:

  • 这有效lua-users.org/wiki/SplitJoin:函数字符串:split(sep) 本地 sep,字段 = sep 或 ":",{} 本地模式 = string.format("([^%s]+) ", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end testAsTable = notes.split(notes, ',')

标签: string lua


【解决方案1】:

如果您信任字符串,则可以重用 Lua 解析器:

notes = "0,5,10,16"
notes = load("return {"..notes.."}")()
print(notes[3])

【讨论】:

    【解决方案2】:

    对于示例字符串,您可以这样做

    local notes_tab = {}
    for note in notes:gmatch("%d*") do
       table.insert(notes_tab, tonumber(note))
    end
    

    【讨论】:

    • 我收到错误:尝试调用字符串值(本地'note')
    • 已修复;我在错误的地方更改了变量名;)
    【解决方案3】:

    我们可以更改所有字符串的__index 元方法以返回以逗号分隔的第n 个元素。然而,这样做会带来一个问题,即我们不能再做类似notes:gmatch(",?1,?") 的事情了。请参阅 this 旧 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 迭代。
    根据您要对数字执行的操作,您可以将其作为字符串返回或立即将其转换为数字。

    【讨论】:

    • 然而,这不是一个非常有效的方法。它不存储任何数字供以后使用,因此当您经常调用它时,您确实应该单独存储它们。
    猜你喜欢
    • 2018-11-07
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2015-05-30
    • 2016-07-02
    • 2013-11-15
    相关资源
    最近更新 更多