Search code examples
lualuajit

Converting a string to an array in Lua


Why does this syntax work:

if ({A=1,B=1,C=1})["A"]  then print("hello") end

while this does not:

local m = {string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)}

if (m)["A"]  then print("hello") end

???

I think it's because a string is not an array, but how can I convert a string ("a,b,c") to an array ({a=1,b=1,c=1})?


Solution

  • This line

    local m = {string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)}
    

    is equivalent to this

    local v = string.sub(string.gsub("A,B,C,", ",", "=1,"),1,-2)
    local m = {v}
    

    which, I hope you agree, would clearly not have the behavior of assigning multiple values in the m table.

    To "parse" simple a=1,b=1,c=1 type strings into a table the second example of string.gmatch from the manual is helpful:

    The next example collects all pairs key=value from the given string into a table:

    t = {}
    s = "from=world, to=Lua"
    for k, v in string.gmatch(s, "(%w+)=(%w+)") do
      t[k] = v
    end