Lua类对象?

我是 Lua 的新手,想知道是否有办法创建多个类对象来制作不同的物品,就像在 C# 或 Java 这样的面向对象编程语言中一样。在 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"
}

但在一个主类中,你可以像 C# 中一样创建新的该类对象,如下所示:

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

是否有办法在 Lua 中做到这一点?

点赞
用户470813
用户470813

有很多种方法。这是一个简单的方法。并不是真正的面向对象,没有继承和一些其他东西。但是我认为这种方法可以在你的情况下使用。

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
2013-08-23 06:34:50
用户1009479
用户1009479

Lua是面向对象的,但它不像Java/C++/C#/Ruby等其他语言,没有原生的类(class)机制,创建新对象的唯一方法是克隆现有对象。这就是为什么它被称为原型语言(例如JavaScript)的原因。

阅读《Lua编程》第16章,你可以使用元表模拟普通的面向对象编程。

2013-08-23 06:36:46
用户87021
用户87021

因为你标记了 love2d,你可以看一下 middleclass。它有相应的 文档。除此之外,它还有一些像 stateful 这样的插件,它们主要用于游戏和 love2d

2013-08-25 11:29:39
用户2780643
用户2780643

另一种方法是使用表格编写代码(以汽车为例):

    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

它创建了一个名为“Car”的表,这相当于类而不是实例,然后在Car类中定义了一个“new”方法,该方法返回一个具有变量和函数的汽车实例。以下是使用此实现的示例:

    local myCar = Car.new()
    print(myCar.health)
    myCar.damage(148)
    print(myCar.health)
    myCar.repair(42)
    print(myCar.health)
2013-09-15 05:50:42