[Resolved] metatable location restriction?

Basic Problem : I can’t seem to get metatables to work unless called through main.lua.
So I thoroughly trudged through Beebe’s awesome Tutorial: Modular Classes article and decided it would probably be a good idea. My code is a mess and this might help organize the functions a bit.

However, this code throws an error (“attempt to index a nil value”) unless I call it in main.lua. (Which defeats the entire point of the object since I’d have to make it global for use anywhere else.)

The called code (say, from another lua file like “somewhere.lua”)

local shop = require ("shop") local shop1 = shop.new() -- throws an error

The shop.lua file:

[code]local shop = {}
local shop_mt = { __index = shop }

function shop.new()
local newShop = { level=1, name=“Temp” }
return setmetatable(newShop, shop_mt)
end

return shop[/code]

50/50 that I’ve just made some sort of obvious mistake…? [import]uid: 41884 topic_id: 22915 reply_id: 322915[/import]

Replying to myself since nobody has piped up yet. :slight_smile:

If I add a number to the constructor, that is, I specify that .new() needs some kind of value, and then add a value, I get a new error message:

bad argument #2 to 'setmetatable' (nil or table expected)

Which basically means that the return line within the constructor is where the problem is.

 return setmetatable(newShop, shop\_mt) 

Unfortunately it’s almost ad verbatim of every sample I can find, which leads me to believe that 758 does not support the setmetatable command. So my next task is to upgrade/downgrade Corona and see if other versions work…(and probably to also build a fresh project and see what happens there…?)

(EDIT: On a brand new project it works. But even replacing 100% of the code I can’t get it to work here. It is not seeing the metatable. At all.) [import]uid: 41884 topic_id: 22915 reply_id: 91599[/import]

Hi,

I’m putting this into a new project and not seeing any errors as your last post explains. Can you show the file that it is breaking in?

(EDIT): It shouldn’t be an issue of Corona because this is a function in basic lua and wouldn’t make much sense being possible to be taken out. Though we would need to more core information of Corona to confirm that.
[import]uid: 49520 topic_id: 22915 reply_id: 91624[/import]

Yeah, solved it with some brute force work. Unsurprisingly all my fault - it was the proverbial “needle in the haystack” - because I found another “shop” variable midway through the lua file.

>_<

As you can imagine, once the var gets into a conflict, there goes the meta table.

(Ironically, this is even more fuel to switch to this class/metatables - my code is almost a rat’s nest right now!)

Thanks for giving it a try though, james :slight_smile: [import]uid: 41884 topic_id: 22915 reply_id: 91627[/import]

No worries. Glad to hear it’s solved! [import]uid: 49520 topic_id: 22915 reply_id: 91629[/import]