【问题标题】:Insert Additional data into Lua table at index在索引处将附加数据插入 Lua 表
【发布时间】:2018-08-22 00:20:32
【问题描述】:

我有一个名为“inventory”的表,初始化如下:

inventory = {}

inventory[1] = { qty = 0 }

我想在此表中添加更多数据,在索引 1 处,例如:

val = { id = "example" }

inventory[1] = inventory[1], val

有没有一种方法可以做到这一点,同时保留此表中已在此索引中的数据?

最终的结果应该是这样的:

inventory[1] = { qty = 0, id = "example" }

但是,如果我在尝试此代码后尝试打印 id,我会得到:

print(inventory[1].id) == Nil

【问题讨论】:

标签: lua


【解决方案1】:
inventory[1].id = "example"

inventory[1]["id"] = "example"

this other SO answer 其中first_tableinventory[1]second_tableval

FWIW,您需要表达式左侧的 2 个变量才能使 inventory[1] = inventory[1], val 起作用:a, b = x, y

【讨论】:

  • 感谢您的回答!有没有办法做到这一点,而不必专门说库存[1] .id? val = { id = "example" } 中的数据实际上可能不叫id,并且可能有多个不同名称的条目!
  • 这将是另一个 SO 答案的来源。该答案包含循环通过 val 表并应用键值对而不管键名的代码。
【解决方案2】:

您需要取出表格中的第一个键并使用它:

local inventory = {}
inventory[1] = { qty = 0 }
local val = { id = "example" }

-- 

local KeyName = next(val)

inventory[1][KeyName] = val[KeyName]

print(inventory[1][KeyName]) 
-- or 
print(inventory[1].id) 

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2022-01-05
    • 2015-08-19
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    相关资源
    最近更新 更多