【问题标题】:How do you assign multiple values in a key for a table?如何在一个表的键中分配多个值?
【发布时间】:2019-09-06 20:55:29
【问题描述】:

我正在尝试为表中的一个变量分配多个值。一个用于字符串名称,一个用于整数。代码如下:

items = {
potion = "Potion", 100
}

我不知道如何正式写这个,以及如何调用那些特定的值。 (你这样叫吗?)

io.write(item.potion.1) --> Potion
io.write(item.potion.2) --> 100

(或者别的什么?)

请帮忙。 :我

【问题讨论】:

  • 你要找的是像items = { potion = {"Potion", 100 } }这样的嵌套表

标签: arrays lua local-variables


【解决方案1】:

您可以将这些值分配给按数字或标识符索引的表:

-- identifiers
items = {
  potion = {name = "Potion", value = 100},
}
print(items.potion.name, items.potion.value)

-- numeric indexes
items = {
  potion = {"Potion", 100},
}
print(items.potion[1], items.potion[2])

我个人更喜欢前一种方法(因为它更易于维护,尽管有点冗长),但任何一种都应该可行。

【讨论】:

    【解决方案2】:

    Lua 允许对多个变量进行多次赋值。

    像这样:

    potion, value = "Potion", 100
    

    但这不能在表定义中完成。

    items = {
        potion = "Potion", 100
    }
    

    您的代码在这里所做的是将potion 设置为值"Potion",然后, 结束分配。下一个分配是 100,它将分配给默认键,在本例中为 1。

    在表格旁边,您以, 结束每个作业,因此您的表格内容等于:

    items = {
       potion = "Potion",
       [1] = 100
    }
    

    要完成所需的行为,您可以嵌套表格:

    items = {
       potion = {
           "Potion",
           100
       }
    }
    

    这个例子可以像items.potion[1] 那样访问而不是像items.potion.1 这是因为. 符号不能与以数字开头的键一起使用。

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2021-05-12
      • 2020-06-20
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多