lua - main.lua:18: 预期 'end' (在第12行的'function'结束)附近出现了'elseif'。

我来自Java,正在尝试使用lua和love2d编写iPad应用程序。 我相当新,经常会出现以下错误:

语法错误:main.lua:18'end' expected(在第12行关闭'function')附近的'elseif'

这是我的代码:

function setup()
i = 0
end

function draw()
if i == 0
then
background(0, 0, 0, 0)
i = i + 1
end
elseif i == 1
then
background(255, 0, 0, 0)
i = i + 1

elseif i == 2
then
background(0, 255, 0, 0)
i = i + 1

elseif i == 3
then
background(0, 0, 255, 0)
i = i + 1

elseif i == 4
then
background(255, 255, 0, 0)
i = i + 1

elseif i == 5
then
background(255, 255, 255, 0)
i = i + 1

elseif i == 6
then
background(0, 255, 255, 0)
i = i + 1

elseif i == 7
then
background(255, 0, 255, 0)
i = 0
end

问题是什么?我该如何修复它并避免未来出现类似问题?谢谢。

点赞
用户4323
用户4323

你有if...then...end...elseif...end不属于那里。

2013-02-20 12:56:48
用户204011
用户204011

John的答案是正确的,但是因为你是初学者,我想给你一点建议:更好的方法是用数据驱动的方式来编写这种代码。这意味着例如将你的draw()函数改写成以下方式:

backgrounds = {
  {  0,   0,   0, 0},
  {255,   0,   0, 0},
  {  0, 255,   0, 0},
  {  0,   0, 255, 0},
  {255, 255,   0, 0},
  {255, 255, 255, 0},
  {  0, 255, 255, 0},
  {255,   0, 255, 0}
}

function draw()
  background(unpack(backgrounds[i+1]))
  i = (i+1) % 8
end

希望你能享受使用Lua的过程!

2013-02-20 14:03:38