如何访问这样的表中的数据?

发布于 2025-01-06 14:41:14 字数 597 浏览 0 评论 0原文

我正在用lua写一个程序。我的数据按以下方式组织:

t= {
    i1 = {
        p1 = { value = "i1p1" },
        p2 = { value = "i1p2" }, 
        -- etc
        pm = { value = "i1pm" }
    },
    i2 = {
        p1 = { value = "i2p1" },
        p2 = { value = "i2p2" },
        -- etc
        pm = { value = "i2pm" }
    },
    im = {
        p1 = { value = "imp1" },
        p2 = { value = "imp2" },
         -- etc
        pm = { value = "impm" }
    }
} --(inner tables)

以另一种方式,每组数据由两个变量 i&p 索引,我确信数据保存正确,但我想要一种从表中打印数据的方法,因为我赢了不知道 i 和 p 的值来迭代它们,甚至不知道数字 n 和 p 。有人知道如何用 lua 做到这一点吗?

I'm writing a program with lua. I have data that organized in the following way:

t= {
    i1 = {
        p1 = { value = "i1p1" },
        p2 = { value = "i1p2" }, 
        -- etc
        pm = { value = "i1pm" }
    },
    i2 = {
        p1 = { value = "i2p1" },
        p2 = { value = "i2p2" },
        -- etc
        pm = { value = "i2pm" }
    },
    im = {
        p1 = { value = "imp1" },
        p2 = { value = "imp2" },
         -- etc
        pm = { value = "impm" }
    }
} --(inner tables)

In another way each group of data is indexed by two variables i&p,I am sure that the data is kept correctly but I want a way to print the data from their tables because I won't know the values of i and p to iterate over them or even the numbers n & m any body know how to do this with lua?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蛮可爱 2025-01-13 14:41:14

如果您知道嵌套(内部)表的深度,则可以显式迭代到该深度:

for k1,v1 in pairs(t) do
    for k2,v2 in pairs(v1) do
        for k3, v3 in pairs(v2) do
            print(k3, ":", v3)
        end
    end
end

或者,您可以递归地迭代到嵌套结构:

function print_tbl(tbl)
    if type(tbl) == "table" then
        for _,v in pairs(tbl) do
            print_tbl(v)
        end
    else
        print(tbl)
    end
end

print_tbl(t)

这只是一个示例。如果您的表包含函数、包含用户数据或者您的嵌套有循环,则您将需要不同的方法。查看 Lua 用户 wiki 上的表序列化。序列化需要合理地处理具有嵌套、函数、循环等的表。您也许可以利用从数据中学到的经验教训。

If you know the depth of your nested (inner) tables, you can iterate explicitly to that depth:

for k1,v1 in pairs(t) do
    for k2,v2 in pairs(v1) do
        for k3, v3 in pairs(v2) do
            print(k3, ":", v3)
        end
    end
end

Alternatively, you can recursively iterate into your nested structure:

function print_tbl(tbl)
    if type(tbl) == "table" then
        for _,v in pairs(tbl) do
            print_tbl(v)
        end
    else
        print(tbl)
    end
end

print_tbl(t)

This is just an example. If your tables contain functions, contains userdata, or your nesting has cycles, you'll need a different approach. Take a look at table serialization on the Lua user wiki. Serialization requires sensible handling of tables with nesting, functions, cycles, etc. You may be able to use lessons learned on your data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文