Why can't I get this metatable setup to work?

Hello nice people of this awesome forum. It’s driving me insane, that I can’t get this to work. Especially because it works in another code of mine. Of must have not seen an crusial error :(. I hope that your wisdom is better than mine!

function Map:new(w, h, size) local newMap = setmetatable({}, self) return newMap end function Map:drawMap() print('test') end

local mapData = Map:new(2,5,30)

mapData:drawMap()

Hi,

Not really sure what is going on in your code as I don’t see where your metatable is declared.

Some working code:

map.lua

local map = {} local map\_mt = { \_\_index = map } function map.new( params ) local p = params or { } local new\_map = {} new\_map.name = p.name or "Unknown" return setmetatable( new\_map , map\_mt ) end function map:drawMap() print("drawMap()", self.name) end return map

main.lua

local map = require("map") local map\_one = map.new( { name = "map1" } ) local map\_two = map.new( { name = "map2" } ) map\_one:drawMap() map\_two:drawMap()

Best regards,

Tomas

Nice, thank you! It works now.

I thought you didn’t have to setup the metatable, since I assumed it was done automatically. 

The funny thing is, that I was sure that I had it to ‘work’ in the other code. I guess I have to take an ekstra look, hehe :). 

Hi,

Not really sure what is going on in your code as I don’t see where your metatable is declared.

Some working code:

map.lua

local map = {} local map\_mt = { \_\_index = map } function map.new( params ) local p = params or { } local new\_map = {} new\_map.name = p.name or "Unknown" return setmetatable( new\_map , map\_mt ) end function map:drawMap() print("drawMap()", self.name) end return map

main.lua

local map = require("map") local map\_one = map.new( { name = "map1" } ) local map\_two = map.new( { name = "map2" } ) map\_one:drawMap() map\_two:drawMap()

Best regards,

Tomas

Nice, thank you! It works now.

I thought you didn’t have to setup the metatable, since I assumed it was done automatically. 

The funny thing is, that I was sure that I had it to ‘work’ in the other code. I guess I have to take an ekstra look, hehe :).