I am having trouble using a metatable to create new monsters for a game, I can create an exact copy but I can't generate a new rat or lizard for example with a new 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)
This creates a new rat under the variable testrat, and the console prints "a rat" and "1". I can't work out how to specify a new id number for the rat when its created. Any help would be appreciated, metatables are confusing me like mad!
testrat
anywhere in that code. You are printing out the singletonmonsters.rat
on that last line. That being said testrat is going to be a weird object. Not just the rat table but a table containing a rat table at index1
. Not that none of that has anything to do with metatables in the slightest. – Etan Reisnernew
function and not hard-code it into the rat singleton (you could use the rat singleton as the current id counter if you wanted to keep a counter for each monster type individually though I suppose). – Etan Reisnerlocal testrat = monsters:new({rat})
is equivalent tolocal testrat = monsters:new {}
, because there is no global or localrat
. – Deduplicator