【问题标题】:call a function from inside a table that's inside another table in lua从 lua 中另一个表内的表内调用函数
【发布时间】:2015-02-26 19:31:39
【问题描述】:

我正在尝试使用 love2D 构建我的第一个游戏,但遇到了问题。

这个游戏是一个泡泡游戏,我想给键盘上的每个字母分配一个泡泡,这样当按下一个字母时泡泡就会弹出。

我有一个名为“bubble.lua”的外部文件,我试图用它来制作一个对象“bubble”。 为此,我在bubble.lua 中创建了一个表“bubble”,其中包含函数和变量。现在,从 main.lua 调用这个文件时只使用一个气泡,但是我需要 26 个气泡,所以我认为最好将每个气泡存储在另一个表中。为了尝试这个,我只使用 1 作为密钥存储了一个气泡。这就是我遇到问题的地方。

require "bubble"
local bubbles = {}
function love.load()
    bubbles[1] = bubble.load(100, 100)
end
function love.draw()
    for bubble in bubbles do
        bubble.draw()
    end
end

function love.keypressed(key)
    bubbles[key].bubble.pop()
end

首先,我知道love.draw() 中的for 循环不起作用,并且“bubble[key].bubble.pop”行似乎也返回了nil

for 循环我可能自己在网上可以找到解决方案,我的主要问题是“bubble[key].bubble.pop()”行,我无法找出问题所在或如何解决。

谁能帮帮我?

你可能也想看看这个:

bubble.lua

bubble = {}
function bubble.load(posX, posY)
    bubble.x = posX
    bubble.y = posY
    bubble.popped = false
end

function bubble.draw()

    if not bubble.popped then
        love.graphics.rectangle("line", bubble.x, bubble.y, 37, 37)
    else
        love.graphics.rectangle("line", bubble.x, bubble.y, 37, 100)
    end
end

function bubble.pop()
    bubble.popped = true
end

编辑:

按照下面答案的建议,当我按“a”时,现在出现以下错误:

main.lua:14: 尝试索引一个 nil 值

更新的代码如下

main.lua

require "bubble"
local bubbles = {}
function love.load()
    bubbles["a"] = bubble.load(100, 100)
end
function love.draw()
    for key, bubble in pairs(bubbles) do
       bubble.draw()
    end
end

function love.keypressed(key)
    bubbles[key].pop()
end

有什么想法吗?

【问题讨论】:

  • love.keypressed 的参数是字符串还是数字?键[1] 是第一。字符串"1" 不会加载该索引1 处的值。您需要 tonumber 进行转换或类似操作。此外,您的 bubble.pop 函数将 popped 设置在全局 bubble 表上,而不是在任何特定的气泡“对象”上。同样,bubble.draw 在全局 bubble 表上运行,而不是在气泡“对象”上运行。
  • bubble.load 不返回任何值,因此您没有在表中存储任何内容。此外,您似乎没有正确使用 OO,因为您没有创建不同的气泡实例;您只是将所有内容存储在完全相同的实例中,这是行不通的。
  • 如何创建一个新的气泡实例?我应该从bubble.load 中返回什么气泡表?
  • 阅读OOPclasses 的章节应该会有所帮助。

标签: lua lua-table love2d


【解决方案1】:

这段代码有几个问题。首先,在初始化气泡 (bubbles[1]) 时按数字索引,但使用 key 作为索引 (bubbles[key]) 访问它们,这不是数字。您需要确定一种机制来索引气泡。假设您选择使用键作为索引(而不是数字)。

这个循环:

for bubble in bubbles do
    bubble.draw()
end

应该写成:

for key, bubble in pairs(bubbles) do
    bubble.draw()
end

而不是bubbles[key].bubble.pop(),您可以简单地执行bubbles[key].pop(),因为bubbles[key] 已经返回了您可以弹出的气泡。

要初始化,您需要使用bubbles['a'](或keylove.keypressed(key) 中使用的任何其他值)而不是bubbles[1]

【讨论】:

  • 谢谢,我想知道您是否知道我可以给每个字母分配一个气泡的方法?而不是做 "bubbles['a'] = bubble.load() bubbles['b']=bubble.load()" 等等。
  • 你可以试试for k = string.ord('a'), string.ord('z') do bubbles[string.char(k)] = bubble.load() end
  • 我已编辑问题以显示我的新代码。我在“bubbles[key].pop()”处收到“尝试索引 nil 值”错误
  • 我刚刚检查了调试器,当按下a 时,love.keypressedkey 的值是a。问题出在其他地方。
  • @JamieMcAllister,您的 bubble.load 没有返回任何值,因此您没有在表中存储任何内容。
猜你喜欢
  • 1970-01-01
  • 2015-07-14
  • 2014-01-01
  • 2017-02-09
  • 2017-05-08
  • 2016-01-04
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多