freemann098
freemann098

Reputation: 284

Lua class objects?

I'm new to Lua and I'm wondering if there's a way to make many class objects to make different items in my case like in a OOP language like C# or Java. An example of what I'm saying is a class like this in Lua...

weapon = {}

function weapon.load()
{
    weapon.name = "CHASE'S BUG"
    weapon.damage = 1
    weapon.rare = "Diet Valley Cheez"
    weapon.hottexture = love.graphics.newImage("/ledata/invalid.png")
    weapong.playtexture = love.graphics.newImage("/ledata/invalid.png")
    weapon.dura = 1
    weapon.type = "swing"
}

But in a main class you could make new objects of that class which would be done like so in something like C#

weapon Dagger = new weapon();
Dagger.name = "Dagger of Some Mountain"
...

Is there a way to do that in Lua?

Upvotes: 3

Views: 6621

Answers (4)

user2780643
user2780643

Reputation: 21

Another way to go about it is to use a table like so (using the example of a car):

    Car = {}
    Car.new = function(miles,gas,health)
        local self = {}

        self.miles = miles or 0
        self.gas = gas or 0
        self.health = health or 100

        self.repair = function(amt)
            self.health = self.health + amt
            if self.health > 100 then self.health = 100 end
        end

        self.damage = function(amt)
            self.health = self.health - amt
            if self.health < 0 then self.health = 0 end
        end

        return self
    end

It creates a table called 'Car' which would be the equivalent of a class, not an instance, then it defines a method "new" in the Car class which returns an instance of a car with variables and functions. An example to using this implementation:

    local myCar = Car.new()
    print(myCar.health)
    myCar.damage(148)
    print(myCar.health)
    myCar.repair(42)
    print(myCar.health)

Upvotes: 2

xpol
xpol

Reputation: 172

since you tagged with love2d, you may have a look at middleclass. It have docs there. And more it have addon like stateful which is mainly for game and love2d.

Upvotes: 0

Huy Le
Huy Le

Reputation: 667

There're many ways. This is a simple one. Not really much OOP, you don't have inheritance and some other stuff. But I think this will work in your case.

function weaponFire ()
    print "BANG BANG"
end

function newWeapon (opts)
    local weaponInstance = {}

    weaponInstance.name = opts.name
    weaponInstance.damage = opts.damage

    weapon.fire = weaponFire

    return weaponInstance
end

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

Lua is object oriented, but it's not like Java/C++/C#/Ruby, etc, there's no native class, the only way to create new object is to clone an existing object. That's why it's called prototype language(like JavaScript).

Read Programming in Lua Chapter 16. You can mock normal OOP using metatable.

Upvotes: 1

Related Questions