【发布时间】:2016-01-30 22:59:20
【问题描述】:
我正在尝试使用一个表并通过使用变量的名称作为键向它添加新数据(另一个表),并将该键添加到表中。我的第一个方法是:
local table
var = read()
print(var.." "..type(var))
table[var] = {name = var, foo = bar}
不幸的是,这会导致错误(预期索引,结果为零)。如果我输入一个字符串值,表格前面的打印行会打印一个值以及类型字符串,但它说它在表格的行中得到一个 nil。来自实际代码的更大代码 sn-p(来自 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
有没有办法找到解决这个问题的方法?代码在一个函数中被针刺,用于将多个数据条目分配给表,然后可以使用代表名称的键访问这些条目。
【问题讨论】:
-
read函数是什么?