c++ - 使用 C 中的 Lua API 覆盖内置类型的运算符

标签 c++ c lua overloading operator-keyword

我已将 Lua 5.3 集成到我的 C++ 代码中,并且添加了几个可以在两个环境之间互换的数学类。

例如,我有一个具有 C 功能的 vec2 Lua 元表,可将其链接到我的 vec2d 的 C++ 类。

现在,我的 vec2 元表有一个 __mul 运算符,这样我就可以编写如下 Lu​​a 代码:

local vector = vec2.create(1, 1)
local scaledVector = vector * 5
print(tostring(scaledVector)) -- outputs 5, 5

但有时,我只是想反过来​​写,我也希望它能工作:

local vector = vec.create(1, 1)
local scaledVector = 5 * vector -- error: Class metatable function __index called on something else than userdata
print(tostring(scaledVector)) -- I want 5, 5

我明白为什么它不起作用。

这在 Lua 中可能吗?如果是这样……怎么办? (我正在寻找 C/C++ 解决方案,而不是用 Lua 编写的某种构造)

最佳答案

如果乘法的左操作数没有设置 __mul 元方法,Lua 将检查右操作数是否有 __mul 元方法。所以 5 * vec 应该和 vec * 5 一样工作:

function scale_vector(vec, alpha)
  local out = {}
  for i=1,#vec do
    out[i] = vec[i] * alpha
  end
  return out
end

function print_vector(vec)
  for i=1, #vec do
    if i > 1 then
      io.stdout:write("\t")
    end
    io.stdout:write(vec[i])
  end
  io.stdout:write("\n")
end


mt = {
  __mul = function(a, b)
    if type(b) == "number" then
      print("Case 1")
      return scale_vector(a, b)
    elseif type(a) == "number" then
      print("Case 2")
      return scale_vector(b, a)
    else
      error("Cannot scale by non-number factor")
    end
  end
}

vec = {1,2,3}
setmetatable(vec, mt)

print_vector( vec * 5 )
print_vector( 5 * vec )

运行此脚本会产生

Case 1
5       10      15
Case 2
5       10      15

您可能出错的部分是,在 __mul 元方法内,您需要进行一些测试以确定您的 vector 是第一个参数还是第二个参数。我的猜测是,您的代码当前假设 __mul 元方法的第一个参数始终是 vector 对象。

关于c++ - 使用 C 中的 Lua API 覆盖内置类型的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980571/

相关文章:

c - 使用 C 连接两个字符串的数据结构程序中的错误

c - 如何从 C 的 shell 脚本执行函数

lua - 在lua源代码中,为什么他们使用double而不是更通用的lua_Number?

c++ - 尝试将队列打印为数组

c++ - 隐藏不应该在只允许 const 访问的基类中改变的成员变量,这样就可以保留赋值运算符

c - 错误 : expected expression before ';' token char

c++ - 在 C++ 中获取指向 Lua 对象实例的指针

c++ - C++中的循环链表的析构函数?

c++ - MediaFoundation,位图数组到 mp4

lua - 求一个 Lua 数字的字符串长度?