使用变量将键添加到表中

我尝试使用表格并通过使用变量名作为键添加新数据(另一个表)来添加到表格中。我的第一个尝试是:

local table
var = read()
print(var.." "..type(var))
table[var] = {name = var, foo = bar}

不幸的是,这会导致错误(预期索引,得到nil)。前面的print行如果我输入字符串值,确实打印出一个值和类型字符串,但它在表格的行中得到了nil。来自minecraft ComputerCraft mod的实际代码的更大代码片段:

m = peripheral.wrap("right")
m.clear()
m.setCursorPos(1,1)

mline = 1

bgcolor = colors.white
txtcolor = colors.black

debugbg = colors.green
debugtxt = colors.lightGreen

mainscreen = true
searchscreen = false
newitemscreen = false
newitemconfirmation = false
running = true

recipes = {}
temp_recipe = {}
 --变量声明部分结束,函数声明开始

function write(text,x,y,cl,bg) --自定义编写函数
  term.setCursorPos(x,y)
  term.setBackgroundColor(bg)
  term.setTextColor(cl)
  term.write(text)
  term.setBackgroundColor(bgcolor)
  term.setTextColor(txtcolor)
end

...

function newItem()
  temp_recipe = {}
  write("Name of the item: ",1,3,txtcolor,bgcolor)
  local item = read()
  write("Amount of items: ",1,4,txtcolor,bgcolor)
  local itemAmount = read()
  write("Amount of items types needet for crafting: ",1,5,txtcolor,bgcolor)
  local ingredientCount = read()
  local ingredientList = {}
  for iC = 1,ingredientCount,1 do
    write("Name of crafting component "..iC..": ",1,6,txtcolor,bgcolor)
    ingredient = read()
    write("Amount of crafting component "..iC..": ",1,7,txtcolor,bgcolor)
   ingredientAmount = read()
   ingredientList[ingredient] = {name = ingredient, amount = ingredientAmount}
  end
>>>>>   temp_recipe[item] = {name = item, amount = itemAmount, ingredients = ingredientList} -- 导致错误的行
  term.setCursorPos(1,8)
  printRecipe(temp_recipe["name"],item) -- 与显示输入数据无关的函数
end

有没有办法找到解决这个问题的方法?代码需要在函数内分配多个数据条目到表格中,然后可以使用表示名称的键访问它们。

点赞
用户258523
用户258523

你从未创建table表,因此无法对其进行赋值。

你需要使用local table = {}table = {var = {name = var, foo = bar}}

另外,不要使用table作为变量名。它会遮蔽/隐藏table模块。

2015-10-30 13:45:35
用户3979429
用户3979429

为了在 Lua 中给表格赋新的键/值,你要用 [] 把键括起来,并使用赋值 (=) 运算符将值赋给它。示例:

local tab = {}
local index = 5
local value = 10
tab[index] = value

你的错误告诉我你正在尝试给一个空值的索引赋值(这是不可能的)。所以 read 函数很可能返回了一个空值。

如果没有更多信息,我很遗憾无法提供更多帮助。

2015-10-30 23:14:03