Reputation: 1
I'm making an enemy that shoot bullets.
I have a enemy.lua
file.
Inside it, I have a list of bullets:
local bullets = {}
The problem comes when I create two of them in main.lua
, only one of them will shoot. I think both of them are sharing the same list.
For example, Enemy 1 and Enemy 2 shoot a bullet each, but Enemy 2's bullet is not shown. However both of their lists return 1. After that I remove Enemy 1's bullet, both of their lists return 0.
How do I do to make it work like a class (like in other programming language). It should not have worked this way as far as I know.
Thank you!
Edit 1: I have an enemy.lua. Unlike the answer, I coded like this
local enemy = {} -- at the start
local bullet= {} -- it is another list
-- in between I have functions
-- for examples
function enemy.new()
function enemy:shoot()
function enemy:update()
return enemy -- at the end
Upvotes: 0
Views: 560
Reputation: 3982
I think you try to use enemy as a class and try to change object specific "bullet". When you try to do that, lua changes the variable in the module, not in the object. That's why enemies only manupulate one list. To avoid that I recommend you to use something like this:
-- enemy.lua file :
function createEnemy()
local newEnemy = {}
-- Add some fields
newEnemy.image = display.newImage(....)
newEnemy.bullets = 3
-- Add some methods if necessary
newEnemy:shoot = function()
newEnemy.bullets = newEnemy.bullets - 1
end
return newEnemy
end
Methods and fields are only examples. You should change them as needed. In this way, you'll create an enemy object with its own fields and methods. Just like in any other oop design.
Keep coding^^
--- Addition:
You should use these kind of structure in an object oriented manner. You should have some array to reach your objects. And methods to manupulate them. For example you can use something like this:
-- game.lua file :
require("enemy")
-- Array to hold enemies.
local enemies = {}
for i=1, 10 do
enemies[#enemies+1] = enemy.createEnemy()
end
If you still have some problems, I recommend you to study object oriented logic.
Upvotes: 1