使用变量将键添加到表中
2015-10-30 14:58:36
收藏:0
阅读:112
评论:2
我尝试使用表格并通过使用变量名作为键添加新数据(另一个表)来添加到表格中。我的第一个尝试是:
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
有没有办法找到解决这个问题的方法?代码需要在函数内分配多个数据条目到表格中,然后可以使用表示名称的键访问它们。
点赞
用户3979429
为了在 Lua 中给表格赋新的键/值,你要用 [] 把键括起来,并使用赋值 (=) 运算符将值赋给它。示例:
local tab = {}
local index = 5
local value = 10
tab[index] = value
你的错误告诉我你正在尝试给一个空值的索引赋值(这是不可能的)。所以 read 函数很可能返回了一个空值。
如果没有更多信息,我很遗憾无法提供更多帮助。
2015-10-30 23:14:03
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你从未创建
table表,因此无法对其进行赋值。你需要使用
local table = {}或table = {var = {name = var, foo = bar}}。另外,不要使用
table作为变量名。它会遮蔽/隐藏table模块。