3
votes

Ok so I've been searching for a while and didn't get the answer. I imagine someone has this same problem but I was not able to solve this problem. I'm new to Lua, having some experience with Python but not being a programmer :S.

So I'm doing a metatable to handle complex numbers, following the tutorials here: http://www.dcc.ufrj.br/~fabiom/lua/

so I implement creation, addition, printing and equal comparison:

local mt={}

local function new(r,i)
  return setmetatable({real = r or 0, im = i or 0},mt)
end

local function is_complex (v)
  return getmetatable(v)==mt
end
local function add (c1,c2)
  if not is_complex(c1) then
    return new(c1+c2.real,c2.im)
  end
  if not is_complex(c2) then
    return new(c1.real+c2,c1.im) 
  end
    return new(c1.real + c2.real,c1.im + c2.im)
end
local function eq(c1,c2)
  return (c1.real==c2.real) and (c1.im==c2.im)
end

local function modulus(c)
  return (math.sqrt(c.real^2 + c.im^2))
end

local function tos(c)
  return tostring(c.real).."+"..tostring(c.im).."i"
end


mt.new=new
mt.__add=add
mt.__tostring=tos
mt.__eq=eq
mt.__len=modulus



return mt

Then I make a small tests:

complex2=require "complex2"

print (complex2)

c1=complex2.new(3,2)
c2=complex2.new(3,4)

print (c1)
print (c2)
print(#{1,2})
print(#c2)
print(complex2.__len(c2))
print(#complex2.new(4,3))

and I get:

table: 0000000003EADBC0
3+2i
3+4i
2
0
5
0

So, What am I dong wrong? is something with calling the #, when i try to debug in the other cases the program goes to the module into the function but the # operand gets like ignored. Modulus function is working and can be called in the module... I'm sorry for such a long and I'm sure obvious question but I tried everything I could already. Thank you

2

2 Answers

3
votes

May be the problem is about Lua version. http://www.lua.org/manual/5.2/manual.html#2.4

"len": the # operation

works since Lua 5.2

and it works only with tables

0
votes

So, Thank you, and you are right. I thought I had selected 5.2 but in the interpreter it was running 5.1 :S. Now i did:

complex2=require "complex2"

print (complex2)

c1=complex2.new(3,2)
c2=complex2.new(3,4)

print (c1)
print (c2)
print (c1+c2)
print(#{1,2})
print(#c2)
print(complex2.__len(c2))
print(complex2.__len(complex2.new(3,3)))
print(#complex2.new(4,3))
print(getmetatable(c2))

And i got:

table: 000000000047E1C0
3+2i
3+4i
6+6i
2
5
5
4.2426406871193
5
table: 000000000047E1C0

Everything under control ^^, at least the code was working as supposed xD