Lua 未覆盖 # 元方法

好吧,我已经搜索了一段时间,但没有得到答案。我想象有人有这个问题,但我无法解决这个问题。我是 Lua 的新手,对 Python 有一些经验,但不是程序员:S。

所以我正在做一个元表来处理复数,遵循这里的教程:http://www.dcc.ufrj.br/~fabiom/lua/

所以我实现了创建、加法、打印和相等比较:

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

然后我进行了一些小测试:

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))

结果是:

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

那么,我做错了什么?在其他情况下调试时调用 #,程序进入函数中但操作被忽略。模长函数是可用的,并且可以在模块中调用...对于这样一个非常长且明显的问题,我感到抱歉,但我已经尝试了我能找到的所有方法。谢谢

点赞
用户1979882
用户1979882

也许问题出在 Lua 版本上。

http://www.lua.org/manual/5.2/manual.html#2.4

"len": # 操作符

在 Lua 5.2 及以上版本中可用,且只能用于表格。

2016-09-02 14:34:32
用户6787899
用户6787899

所以,谢谢你,你说得对。我本以为我选择的是5.2,但是解释器中运行的是5.1 :S。现在我这样做:

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))

然后我得到了:

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

一切都没问题^^,至少代码按照预期工作了xD

2016-09-05 07:52:32