Call a function from inside a table that is inside another table in lua
I am trying to create my first game using love2D, I got into a problem.
The game is a bubble game, I want to assign a bubble for each letter on the keyboard so that when the letter is pressed, the bubble appears.
I have an external file called "bubble.lua" which I tried to make a bubble object. To do this, I created a bubble table in bubble.lua that contains functions and variables. Now this file works when called from main.lua using only one bubble, however I need 26 bubbles, so I thought it would be best to store each bubble in a different table. In order to try this out, I simply saved one bubble using 1 as a key. This is where I have problems.
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
First, I know that the for loop is love.draw()
not working and the line "bubble [key] .bubble.pop" seems to also returnnil
In the for loop I can find a solution on my own on the net, my main problem is "bubble [key] .bubble.pop ()", I can't figure out what's wrong or how to fix it.
Can anyone help me?
You can also look at this:
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
Edit:
Following the answer below, I now have the following error when I press "a":
main.lua: 14: Attempt to index a nil value
updated code below
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
any thoughts?
source to share
Several problems arise with this code. First, you are indexing by number when you initialize bubbles ( bubbles[1]
), but accessing them with key
as index ( bubbles[key]
), which is NOT a number. You need to rely on one mechanism to index the bubbles. Let's say you choose to use a key as an index (instead of a number).
This loop:
for bubble in bubbles do
bubble.draw()
end
should be written as:
for key, bubble in pairs(bubbles) do
bubble.draw()
end
and instead bubbles[key].bubble.pop()
you can just do bubbles[key].pop()
as it bubbles[key]
already returns a bubble that you can place.
For initialization, instead bubbles[1]
you need to do bubbles['a']
(or whatever value is used key
in love.keypressed(key)
).
source to share