Lua - convert string to table

Learn lua - convert string to table with practical examples, diagrams, and best practices. Covers string, lua, lua-table development techniques with visual explanations.

Converting Strings to Tables in Lua: A Comprehensive Guide

Hero image for Lua - convert string to table

Learn various techniques to parse and transform string data into structured Lua tables, from simple splitting to complex deserialization.

Lua, known for its simplicity and power, often requires manipulating data in various formats. A common task is converting string data into structured tables, which are Lua's primary data structure. This article explores several methods to achieve this, catering to different string formats and complexity levels. Whether you're parsing CSV-like data, JSON, or custom delimited strings, understanding these techniques is crucial for effective Lua programming.

Basic String Splitting into a Table

The most fundamental conversion involves splitting a string by a delimiter and storing each segment as an element in a new table. Lua's standard library doesn't provide a direct split function, but it's straightforward to implement using string.gmatch or string.find.

function split(inputstr, sep)
    if sep == nil then
        sep = "%s"
    end
    local t={}
    for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
        table.insert(t, str)
    end
    return t
end

local myString = "apple,banana,orange"
local fruitTable = split(myString, ",")

for i, v in ipairs(fruitTable) do
    print(i, v)
end

-- Output:
-- 1\tapple
-- 2\tbanana
-- 3\torange

Implementing a basic string split function using string.gmatch.

flowchart TD
    A[Input String] --> B{Define Delimiter}
    B --> C{Iterate with string.gmatch}
    C --> D{Extract Substring}
    D --> E[Add to Table]
    E -- Loop until end --> C
    C --> F[Return Table]
    F --> G[Output Table]

Flowchart of the basic string splitting process.

Parsing Key-Value Pairs from a String

Often, strings contain data in a key-value format, such as configuration settings or query parameters. Parsing these into a table where keys are strings and values are their corresponding data requires a slightly more complex approach, typically involving string.gmatch with more specific patterns.

function parseKeyValueString(inputstr, pair_sep, kv_sep)
    pair_sep = pair_sep or ";"
    kv_sep = kv_sep or "="
    local t = {}
    for pair in string.gmatch(inputstr, "([^"..pair_sep.."]+)") do
        local key, value = string.match(pair, "(.-)" .. kv_sep .. "(.*)")
        if key and value then
            t[key:gsub("^%s*(.-)%s*$", "%1")] = value:gsub("^%s*(.-)%s*$", "%1") -- Trim whitespace
        end
    end
    return t
end

local configString = "name=John Doe;age=30;city=New York"
local configTable = parseKeyValueString(configString, ";", "=")

for k, v in pairs(configTable) do
    print(k, v)
end

-- Output:
-- name\tJohn Doe
-- age\t30
-- city\tNew York

Parsing a string of semicolon-separated key-value pairs into a Lua table.

Deserializing JSON Strings to Tables

For more complex, structured data, JSON (JavaScript Object Notation) is a widely used format. Lua does not have built-in JSON parsing, but several excellent third-party libraries are available. dkjson is a popular choice for its simplicity and robustness.

-- Assuming dkjson library is available (e.g., installed via LuaRocks)
-- local json = require("dkjson")

-- For demonstration, we'll simulate a simple JSON parser
-- In a real application, use a library like dkjson or cjson

function simpleJsonParse(jsonString)
    -- This is a highly simplified example and will not handle all JSON cases.
    -- It's meant to illustrate the concept of deserialization.
    -- For production, use a robust JSON library.
    local t = {}
    -- Remove outer braces and split by comma for key-value pairs
    local content = string.match(jsonString, "^%s*\{(.*)\}%s*$")
    if not content then return nil end

    for pair in string.gmatch(content, "([^{}]+)") do -- Simplified split, needs refinement for nested structures
        local key_match, value_match = string.match(pair, '^%s*"([^"]+)"%s*:%s*(.*)$')
        if key_match and value_match then
            local key = key_match
            local value = value_match
            -- Attempt to convert value to number or boolean if possible
            if value:match("^%d+$") then
                value = tonumber(value)
            elseif value == "true" then
                value = true
            elseif value == "false" then
                value = false
            elseif value:match('^"(.*)"$') then
                value = value:match('^"(.*)"$') -- Remove quotes for string values
            end
            t[key] = value
        end
    end
    return t
end

local jsonString = '{"name": "Alice", "age": 25, "isStudent": true}'
local dataTable = simpleJsonParse(jsonString)

if dataTable then
    for k, v in pairs(dataTable) do
        print(k, type(v), v)
    end
end

-- Expected (with a real JSON parser):
-- name\tstring\tAlice
-- age\tnumber\t25
-- isStudent\tboolean\ttrue

A highly simplified, illustrative example of parsing a flat JSON string. Use a library for real-world JSON.

1. Install a JSON Library (e.g., dkjson)

If you don't have LuaRocks, install it first. Then, open your terminal or command prompt and run: luarocks install dkjson

2. Require the Library in Your Lua Script

At the top of your Lua file, add local json = require("dkjson") to make the library's functions available.

3. Deserialize the JSON String

Use local dataTable = json.decode(jsonString) to convert your JSON string into a Lua table. The library handles all the complexities of JSON syntax.

4. Access Data in the Table

You can now access your data using standard Lua table indexing, e.g., print(dataTable.name) or print(dataTable["age"]).