【问题标题】:Lua not overriding # metamethodLua 没有覆盖 # 元方法
【发布时间】:2016-09-02 14:19:32
【问题描述】:

好的,所以我已经搜索了一段时间,但没有得到答案。我想有人有同样的问题,但我无法解决这个问题。我是 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

那么,我哪里错了?与调用#有关,当我尝试在其他情况下调试时,程序进入模块进入函数,但#操作数被忽略。模数函数正在工作并且可以在模块中调用......我很抱歉这么长时间,我确信这个问题很明显,但我已经尽我所能尝试了。谢谢

【问题讨论】:

    标签: lua


    【解决方案1】:

    可能是关于 Lua 版本的问题。 http://www.lua.org/manual/5.2/manual.html#2.4

    “len”:#操作

    从 Lua 5.2 开始工作

    它只适用于表格

    【讨论】:

    • 而使用 LuaJIT,您需要使用 -DLUAJIT_ENABLE_LUA52COMPAT 构建它以遵循 __len 元方法。
    【解决方案2】:

    所以,谢谢你,你是对的。我以为我选择了 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 2010-11-29
      相关资源
      最近更新 更多