Lua中运算符重载为何不生效?

2026-04-01 20:351阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计346个文字,预计阅读时间需要2分钟。

Lua中运算符重载为何不生效?

在Lua中阅读《Programming》时,我尝试了书中给出的运算符重载例子。使用Set类型和+运算符:

luaSet={}mt={}mt.__add=Set.union

function Set.new(l) local set={} setmetatable(set, mt) for _, v in ipairs(l) do set[v]=true endend

在Lua中阅读Programming时,我尝试了本书中给出的运算符重载的例子

Set = {} mt = {} mt.__add = Set.union --create a new set with the values of the given list function Set.new (l) local set = {} setmetatable (set, mt) for _, v in ipairs (l) do set [v] = true end return set end function Set.union (a, b) local result = Set.new {} for k in pairs (a) do result [k] = true end for k in pairs (b) do result [k] = true end return result end function Set.intersection (a, b) local result = Set.new {} for k in pairs (a) do result [k] = b[k] end return result end function Set.tostring (set) local l = {} for e in pairs (set) do l[#l + 1] = e end return "{" .. table.concat (l, ", ") .. "}" end function Set.print (s) print (Set.tostring (s)) end s1 = Set.new {10, 20, 30, 50} s2 = Set.new {30, 1} Set.print (s1) Set.print (s2) s3 = s1 + s2 Set.print (s3)

但是对于Windows的最新lua我收到以下错误

lua: C:\meta.lua:47: attempt to perform arithmetic on global 's1' (a table value) stack traceback: C:\meta.lua:47: in main chunk [C]: ? {30, 10, 20, 50} {1, 30} 你过早地做这个任务:

mt.__add = Set.union

因为Set.union尚未初始化.

Lua中运算符重载为何不生效?

将其移至Set.union下方,它将起作用.

出于同样的原因,如果你指定mt .__ mul,那么它应该低于Set.intersection

本文共计346个文字,预计阅读时间需要2分钟。

Lua中运算符重载为何不生效?

在Lua中阅读《Programming》时,我尝试了书中给出的运算符重载例子。使用Set类型和+运算符:

luaSet={}mt={}mt.__add=Set.union

function Set.new(l) local set={} setmetatable(set, mt) for _, v in ipairs(l) do set[v]=true endend

在Lua中阅读Programming时,我尝试了本书中给出的运算符重载的例子

Set = {} mt = {} mt.__add = Set.union --create a new set with the values of the given list function Set.new (l) local set = {} setmetatable (set, mt) for _, v in ipairs (l) do set [v] = true end return set end function Set.union (a, b) local result = Set.new {} for k in pairs (a) do result [k] = true end for k in pairs (b) do result [k] = true end return result end function Set.intersection (a, b) local result = Set.new {} for k in pairs (a) do result [k] = b[k] end return result end function Set.tostring (set) local l = {} for e in pairs (set) do l[#l + 1] = e end return "{" .. table.concat (l, ", ") .. "}" end function Set.print (s) print (Set.tostring (s)) end s1 = Set.new {10, 20, 30, 50} s2 = Set.new {30, 1} Set.print (s1) Set.print (s2) s3 = s1 + s2 Set.print (s3)

但是对于Windows的最新lua我收到以下错误

lua: C:\meta.lua:47: attempt to perform arithmetic on global 's1' (a table value) stack traceback: C:\meta.lua:47: in main chunk [C]: ? {30, 10, 20, 50} {1, 30} 你过早地做这个任务:

mt.__add = Set.union

因为Set.union尚未初始化.

Lua中运算符重载为何不生效?

将其移至Set.union下方,它将起作用.

出于同样的原因,如果你指定mt .__ mul,那么它应该低于Set.intersection