Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I change a string into a table?

Asked by 5 years ago
Edited 5 years ago

So I have a string that when I print it the output is: {1, 3}. However when I try to loop through that table it outputs this error: (table expected, got string). Is there any way to change that string back into a table? I tried tonumber but it didnt work. Could someone help me out here? Thanks!

Edit 1.

local function dumpTable(tableToDump)
    local tbl = {}
    if type(tableToDump) == "table" then
        for i,v in pairs(tableToDump) do
            table.insert(tbl, tostring(v))
        end
        return "{" .. table.concat(tbl, ", ") .. "}"
    else
        return nil
    end
end

I did this because of the help of another scripting helper. Here is the link to that question. Here is the place I try to loop through the table:

local function findAMatch(savedItemsTable, item)

    --if type(savedItemsTable) == "table" then
        print("is a table")
        for i,v in pairs(savedItemsTable) do

            if v == item.ItemNumber.Value then

                return true

            else 

                return false

            end
        end

    --else

        --return false

    --end
end

certain things are commented out just because it wasnt working and I wanted to see what was wrong. The if statement if it isnt commented out will not let the code continue because the type() of savedItemsTable is a string. Hope you guys can help. Thanks!

0
Can you include the scripts you used. User#5423 17 — 5y

1 answer

Log in to vote
0
Answered by
nilVector 812 Moderation Voter
5 years ago
Edited 5 years ago

So you have a string, and in that string, you want to retrieve only the integers from it. This is a perfect example of matching through string patterns.

In your case, you have the following string: "{1, 3}"

...and you want only the integers to construct the following table: {1, 3}

Since you want all instances of integers that are found within the string, the string.gmatch function will be of great use. It will return an iterator function containing the series of substrings in our string that matche our specified pattern. In our case, our pattern will be %d+, because that will capture the series of continuous digits found in our string.

local s = "{1, 3}"
local newTable = {}
for int in string.gmatch(s, "%d+") do
    table.insert(newTable, tonumber(int))
end

-- now, newTable = {1, 3}
0
Thanks I will try out your solution. User#21908 42 — 5y
0
It worked! Thank you so much! User#21908 42 — 5y
0
You're welcome. nilVector 812 — 5y
Ad

Answer this question