Lua 多维表创建

我在 Lua 中有一个多维表,但似乎无法创建它以便在 Lua 中使用?

表格

items :: = {

{["category"] = "工具",["name"] = "锤子",["price"] = 10,["quantity"] = 5},
{["category"] = "工具",["name"] = "锯子",["price"] = 15,["quantity"] = 4},
{["category"] = "工具",["name"] = "螺丝刀",["price"] = 4,["quantity"] = 12},
{["category"] = "工具",["name"] = "卷尺",["price"] = 9,["quantity"] = 3},
{["category"] = "工具",["name"] = "钳子",["price"] = 10,["quantity"] = 5},
{["category"] = "工具",["name"] = "扳手",["price"] = 10,["quantity"] = 5},

{["category"] = "紧固件",["name"] = "钉子",["price"] = .1,["quantity"] = 1500},
{["category"] = "紧固件",["name"] = "螺丝",["price"] = .2,["quantity"] = 1200},
{["category"] = "紧固件",["name"] = "订书钉",["price"] = .05,["quantity"] = 2000},

}

错误:'<name>' expect near ':'

原文链接 https://stackoverflow.com/questions/5691160

点赞
stackoverflow用户282658
stackoverflow用户282658

那个 ::= 有点奇怪。那看起来更像是 ASN.1 而不是 Lua。

尝试使用以下代码:

items = {

        {["category"]="tools", ["name"]="hammer", ["price"]=10,  ["quantity"]=5 },
        {["category"]="tools", ["name"]="saw", ["price"]=15,  ["quantity"]=4 },
        {["category"]="tools", ["name"]="screwdriver", ["price"]=4,  ["quantity"]=12 },
        {["category"]="tools", ["name"]="measuring tape", ["price"]=9,  ["quantity"]=3 },
        {["category"]="tools", ["name"]="pliers", ["price"]=10,  ["quantity"]=5 },
        {["category"]="tools", ["name"]="wrench", ["price"]=10,  ["quantity"]=5 },

        {["category"]="fasteners", ["name"]="nails", ["price"]=.1,  ["quantity"]=1500 },
        {["category"]="fasteners", ["name"]="screws", ["price"]=.2,  ["quantity"]=1200 },
        {["category"]="fasteners", ["name"]="staples", ["price"]=.05,  ["quantity"]=2000 },

}

当我在 Lua shell 中使用它时,我得到以下结果:

for k,v in pairs(items) do for k1,v1 in pairs(v) do print(k1,v1) end end
price   10
quantity    5
name    hammer
category    tools
price   15
quantity    4
name    saw
category    tools
price   4
quantity    12
name    screwdriver
category    tools
price   9
quantity    3
name    measuring tape
c    ategory    tools
price   10
quantity    5
name    pliers
category    tools
price   10
quantity    5
name    wrench
category    tools
price   0.1
quantity    1500
name    nails
category    fasteners
price   0.2
quantity    1200
name    screws
category    fasteners
price   0.05
quantity    2000
name    staples
category    fasteners
2011-04-17 03:14:34
stackoverflow用户2751792
stackoverflow用户2751792

function create_table() local l = {} -- 初始化表。 l[0] = [[]] -- 将索引 0 的值清空为 nil。 return l end

t = create_table() print(t) -- 打印存储在内存中的表。 --[[ 如果您不想每天创建表格,可以使用此矩阵。 ]]-- m = {{ ["id"] = 1 }, { ["id"] = 2, ["name"] = "Mr. Anon", ["leet"] = 1337 }}

print(m[1]["id"] .. ", " .. m[2]["id"] .. ", " .. m[2]["name"] .. ", " .. m[2]["leet"] .. ".")

创建表格

介绍

操作指南

```

2013-09-05 18:05:29