Lua string to table

2020-04-18 06:03发布

问题:

I have a string that I need to read as a table

    notes = "0,5,10,16"

so if I need the 3rd value of the current notes that is 10

    value = notes[3]

回答1:

For the example string, you can just do

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


回答2:

We can change the __index metamethod of all strings to return the nth element separated by commas. Doing this, however, gives the problem that we cannot do something like notes:gmatch(",?1,?") anymore. See this old StackOverflow post. It can be solved, by checking whether the __index is called with a string or other value.

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 returns a function over which we can iterate, so calling this n times will result in the nth number being returned.
The for loop makes sure that all the numbers before which we want have been iterated over by the gmatch.
Depending on what you want to do with the numbers you can either return it as a string or convert it to a number immediately.



回答3:

If you trust the strings, you can reuse the Lua parser:

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


标签: string lua