如何创建用于计算多项式的类或元表

我正在尝试使用Lua在LuaTeX中计算多项式的程序。 例如。 (2x^2+3xy+4)*(x+2y)=?

所以我想从制作简单的类开始。

下面的代码是没有系数的单变量类。

{"x",2} <--> x^2

do
  ItemS = setmetatable({ -- MetaTable
  __mul = function(a,b)
      if getmetatable(a)==ItemS and getmetatable(b)==ItemS then
        if a.var==b.var then return ItemS(a.var,a.deg + b.deg)end
      end
    end,
  __div = function(a,b)
      if getmetatable(a)==ItemS and getmetatable(b)==ItemS then
        if a.var==b.var then return ItemS(a.var,a.deg-b.deg)end
      end
    end,
  __pow = function(a,b)
      if getmetatable(a)==ItemS and type(b)=="number" then
        return ItemS(a.var,a.deg*b)
      end
    end,
  __eq = function(a,b)
      return(a.var==b.var and a.deg == b.deg)
    end,
  __concat = function(a,b)
      if getmetatable(a)==ItemS then return a.var .. "^{" .. a.deg.."}" .. b end
      return a .. b.var .. "^{" .. b.deg.."}"
    end,
  __tostring = function(a)
      if getmetatable(a)==ItemS then
        return a.var.."^{"..a.deg.."}"
      end
      return a.var.."^{"..a.deg.."}"
    end
    },{
  __call = function(z,a,b)return setmetatable({var = a,deg = b},z)end
  })
end

接下来,我想制作没有系数的多变量类。 但是我不知道如何使用Lua Table制作类...

我想制作类似于表 {{"x",2},{"y",3},...} <--> x^2y^3...

请告诉我如何为表制作类...


点赞