2

我在使用元表为游戏创建新怪物时遇到问题,我可以创建一个精确的副本,但我无法生成新的老鼠或蜥蜴,例如使用新的 id。

local monsters = {
  rat = {
   name = "a rat",
   id = 1,
   health = 5,
   }
  lizard = {
   name = "a lizard",
   id = 1,
   health = 8,
   }
 }

local metamonsters = {__index = monsters}
setmetatable(monsters, metamonsters)

function monsters:new(o)
 setmetatable(o, metamonsters)
 return o
end 

local testrat = monsters:new({rat})         
print(testrat.name, testrat.id)

这会在变量 testrat 下创建一个新老鼠,控制台会打印“a rat”和“1”。我不知道如何在创建老鼠时为其指定新的 ID 号。任何帮助将不胜感激,元表让我疯狂!

4

1 回答 1

1

您需要从 Lua 中的类如何工作的基础知识开始:

一个实例object有一个元表meta,其中包含所有元方法,特别是__index.

当查找未能找到查找键__index时,总是调用元方法。 实际上,它不必是一个函数,另一个表也是可以接受的,我们有一个理想的候选者:.object
meta

__index可以重复这个查看元表中是否有键条目的游戏:
因此,一个泛型monster可以是元表到rat,它可以是所有老鼠的元表。

如果需要,可以进行更多和更深的继承。

protos = {}
monsters = {}
protos.monster = {
    name = 'generic monster',
    bp = 'monster',
    health = 1,
    __call = function(self, new, proto)
        if proto then
            proto = protos
            protos[new.bp] = new
            protos[new.name] = new
        else
            proto = monsters
        end
        table.insert(proto, new)
        new.id = #protos
        return setmetatable(new, self)
    end
}
protos.monster.__call(nil, protos.monster, true)

protos.monster({
    name = "a rat",
    short = 'rat',
    health = 5,
}, true)
protos.rat({
    name = "a black rat",
    short = 'blackrat',
    health = 7,
}, true)

创建一个新的怪物

protos[type] { --[[ some stats here ]] }

创建一个新的原型

protos[type]({ --[[ some stats here ]] }, true)

Lua 手册:http
: //www.lua.org/manual/5.2/ Lua-users wiki(示例代码): http: //lua-users.org/wiki/SampleCode

于 2014-10-02T19:17:36.330 回答