lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all,

First of all please let me know if this list is not appropriate for
newbie questions!

I'm learning lua and I'm stuck in a small example. I'd appreciate your
help on this.

The fact is that I'm building an "object" using metatables, following
the example at http://www.lua.org/pil/16.html

Account = {balance = 0}

function Account:new (o)
	o = o or {}
	setmetatable(o, self)
	self.__index = self
	return o
end

a=Account:new()
print( a.balance ) --> 0

This is correct: a.balance is 0, cool. But now I do this, which I
think it's equivalent:

graph = { nodes={}, edges={} }

function graph:new(o)
	o = o or {}
	setmetatable(o,self)
	self._index = self
	return o
end

a=graph:new()
print( a.nodes ) --> nil

I was expecting that "a.nodes" is an empty table ({}), copied from the
original "graph" variable, but a.nodes is returning "nil" instead.

What am I doing wrong in the example? Why are not the fields "nodes"
and "edges" from the original "graph" being copied in variable "a"?

Thanks in advance,
Antonio