【问题标题】:'attempt to index field 'Colors' (a nil value)' When accessing an array in LUA'尝试索引字段'颜色'(一个零值)'当访问LUA中的数组时
【发布时间】:2018-06-09 12:20:29
【问题描述】:

所以我决定在 forums.roblox.com 死后尝试为 roblox 获取 LUA,如果有更好的地方可以询问,请告诉我。

无论如何,我试图让一个块在几种预定义的颜色之间随机变化。我尝试这样做的方法是使用颜色创建一个数组,然后使用 math.random 在数组中选择一个位置以设置为颜色,所有这些都在每 1 秒重复一次的 while 1==1 循环内。

这是我的代码

Colors = {'Red', 'Orange', 'Yellow', 'Camo', 'Blue', 'Pink', 'Purple'}

while(1 == 1)
do
    script.Parent.BrickColor = BrickColor.Colors[math.random(1,7)]
    wait(1)
end

每当我运行它时,我都会收到错误“Workspace.Part.Script:5:尝试索引字段“颜色”(零值)”

但如果我尝试

Colors = {'Red', 'Orange', 'Yellow', 'Camo', 'Blue', 'Pink', 'Purple'}

while(1 == 1)
do
    --script.Parent.BrickColor = BrickColor.Colors[math.random(1,7)]
    Colors[math.random(1,7)]
    wait(1)
end

它会每秒打印出其中一种颜色。

就像我说的那样,我才刚刚开始,所以这可能是一些愚蠢的事情。

【问题讨论】:

  • 第二段代码没有编译。
  • 好的,你知道我可以做些什么来解决它吗?

标签: arrays lua null roblox


【解决方案1】:

script.Parent.BrickColor = BrickColor.Colors[math.random(1,7)]

您在BrickColor 中引用字段Colors,而您应该只引用您之前创建的变量Colors

script.Parent.BrickColor = Colors[math.random(1,7)]

【讨论】:

  • 好吧,这是有道理的。我现在遇到的问题是它输出 'bad argument #3 to 'BrickColor' (BrickColor expected, got string)' 或者如果我删除了单引号,所以数组读取颜色 = {Red, Orange, Yellow, Camo, Blue,粉红色,紫色} 我得到 'BrickColor' 的错误参数 #3(预期为 BrickColor,结果为零)'
【解决方案2】:

好的,在尝试了 Pauls 的建议后,将砖色线更改为

script.Parent.BrickColor = Colors[math.random(1,7)]

我收到了错误

bad argument #3 to 'BrickColor' (BrickColor expected, got string)

经过一番搜索后,我发现我需要使用 BrickColor.new(color) 来更改颜色。这就是代码最终的样子

Colors = {'Red', 'Orange', 'Yellow', 'Camo', 'Blue', 'Pink', 'Purple'}

while(1 == 1)
do
    script.Parent.BrickColor = BrickColor.new(Colors[math.random(1,7)])
    wait(1)
end

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 2016-09-19
    • 2011-11-05
    • 1970-01-01
    • 2014-04-04
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多