使用变量将键添加到表中

时间:2015-10-30 13:36:26

标签: lua lua-table

我正在尝试使用表并使用变量名称作为键添加新数据(另一个表),并将该键添加到表中。我的第一个方法是:

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

不幸的是,这会导致错误(预期索引,为零)。如果我输入一个字符串值,表格前面的打印行会打印一个值和类型字符串,但它表示它在表格的行中得到一个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 = {}
 --end of variable declaration part, start of function declarations

function write(text,x,y,cl,bg) --custom writing function
  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} -- Line that causes the error
  term.setCursorPos(1,8)
  printRecipe(temp_recipe["name"],item) -- irrelevant function to display the entered data
end

有没有办法找到解决这个问题的方法?代码在函数内部,用于为表分配多个数据,然后可以使用表示名称的键访问该表。

2 个答案:

答案 0 :(得分:1)

您永远不会创建table表。所以你不能分配到它。

您需要local table = {}table = {var = {name = var, foo = bar}}

另请勿将table用作变量名称。它会隐藏/隐藏table模块。

答案 1 :(得分:0)

To assign new key/values to a table in Lua, you surround the key with [] and assign a value to it with the assignment (=) operator. Example:

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

Your error tells me you're assigning to a nil index (which isn't directly possible). So read must be returning a nil value.

Without any further information I am afraid I cannot help.