This was bugging me, so I hope the following helps someone (I am relatively new to Corona/LUA so this may not come as news to most people on the forum, but this one had me stumped for a while).
I start with a basic module ‘person.lua’ that I want to use as a class:
-- person.lua
function new(name)
print("New person named " .. name);
this = { name = name }
function this:hello() print("Hello, my name is " .. this.name); end
return this
That looks sound, so now I create multiple ‘instances’ of the above ‘class’ and put them in a table:
-- main.lua
local people = {}
table.insert(people, 1, require('person.lua').new('Andrew'))
-- New person named Andrew
table.insert(people, 2, require('person.lua').new('Catherine'))
-- New person named Catherine
table.insert(people, 3, require('person.lua').new('Henry'))
-- New person named Henry
So far so good, but then I call on them:
-- main.lua
people[1]:hello();
-- Hello, my name is Henry
people[2]:hello();
-- Hello, my name is Henry
Huh?
Turns out I need to forward reference all of my ‘class’ properties:
-- person.lua
function new(name)
print("New person named " .. name);
this = {}
local name = name
function this:hello() print("Hello, my name is " .. name); end
return this
This seems bizarre, because while the function definitions are attached to the returned table, the values in this are not. No matter how many times I instantiate ‘person.lua’, this.name will always be equal to the value set in the latest new call.
[import]uid: 66490 topic_id: 30853 reply_id: 330853[/import]