是否存在将lua表(作为字符串)转换为javascript数组的干净方法? (反之亦然)

问题描述 投票:0回答:1

编辑:将lua表作为字符串,然后使用javascript将其转换为javascript数组。 lua中无程序。

所以lua表只是一个不同格式的关联数组。

    --LUA TABLE EXAMPLE
    {
    ["glow"] = true,
    ["xOffset"] = -287.99981689453,
    ["yOffset"] = -227.55575561523,
    ["anchorPoint"] = "CENTER",
    ["cooldownSwipe"] = true,
    ["customTextUpdate"] = "update",
    ["cooldownEdge"] = false,
    ["icon"] = true,
    ["useglowColor"] = false,
    ["internalVersion"] = 24,
    ["keepAspectRatio"] = false,
    ["animation"] = {
        ["start"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
        ["main"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
        ["finish"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
    }

尽管我只遇到过一些lua库将json转换为lua表,但我一直在寻找一些javascript函数或库来做到这一点。 lua表将始终在字符串中。是否存在执行此操作的方法?

javascript arrays lua
1个回答
0
投票

您可以手动将其设为有效的JSON,然后对其进行解析:

const luaStr = `{
    ["glow"] = true,
    ["xOffset"] = -287.99981689453,
    ["yOffset"] = -227.55575561523,
    ["anchorPoint"] = "CENTER",
    ["cooldownSwipe"] = true,
    ["customTextUpdate"] = "update",
    ["cooldownEdge"] = false,
    ["icon"] = true,
    ["useglowColor"] = false,
    ["internalVersion"] = 24,
    ["keepAspectRatio"] = false,
    ["animation"] = {
        ["start"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
        ["main"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
        ["finish"] = {
            ["duration_type"] = "seconds",
            ["type"] = "none",
        },
    }}`;

const result = luaStr
  .replace(/\s/g, '') // get rid of the white spaces
  .replace(/\[|\]/g, '') // remove the brackets
  .replace(/=/g, ':') // replace the = with :
  .replace(/(\,)(?=})/g, ''); // remove trailing commas
  
const parsed = JSON.parse(result);

console.log(parsed);
© www.soinside.com 2019 - 2024. All rights reserved.