LUA: Classes and Instanciations

If, like me, you tend to be a bottom up learner you usually never read the manuals except when you need to. And this is, for once, one of these times. Only reading the class parts of the manuals/wikis (IE: http://lua-users.org/wiki/SimpleLuaClasses and http://www.lua.org/pil/16.1.html ) is actually not really enough to be able to make classes always work as you want them to.
If you also tend to adapt examples to your requirements (no need to reinvent the wheel), here it might actually go wrong. In the examples given in the two previous link, the writers tended to forget about the differences between metatables and tables completely confounding me :) .
In the example below:

function Account:new (o)
o = o or {} — create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end

self equals Account and the metatable of Account is also Account which creates an infinite loop which needs to be treated if you try to save / dump the instanced variables.
To solve this, use instead the following syntax:

function Account:new (o)
o = o or {} — create object if user does not provide one
setmetatable(o, {__index = self})
return o
end

When you retrieve the saved variables don’t forget to set the metatables to what they should be too :)

And if I am totally wrong in what I just posted, I ll be glad to be corrected. I really do have a hard time with the Lua OOP model, guess I still have lots to read / learn.

Tags:

Leave a Reply

You must be logged in to post a comment.