gpt4 book ai didi

lua - 《Programming in Lua》第 108 页对 Lua 元表感到困惑

转载 作者:行者123 更新时间:2023-12-01 18:08:58 26 4
gpt4 key购买 nike

我正在学习 Lua,使用Lua 编程,第一版这本书。我无法理解元表。

这是第 108 页上出现的代码和说明:

Set = {}

function Set.new (t)
local set = {}
for _, l in ipairs(t) do set[l] = true end
return set
end

function Set.union (a,b)
local res = Set.new{}
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end

function Set.intersection (a,b)
local res = Set.new{}
for k in pairs(a) do
res[k] = b[k]
end
return res
end

To help checking our examples, we also define a function to print sets:

function Set.tostring (set)
local s = "{"
local sep = ""
for e in pairs(set) do
s = s .. sep .. e
sep = ", "
end
return s .. "}"
end

function Set.print (s)
print(Set.tostring(s))
end

Now, we want to make the addition operator (+) compute the union of two sets. For that, we will arrange that all tables representing sets share a metatable and this metatable will define how they react to the addition operator. Our first step is to create a regular table that we will use as the metatable for sets. To avoid polluting our namespace, we will store it in the Set table:

Set.mt = {}    -- metatable for sets

The next step is to modify the Set.new function, which creates sets. The new version has only one extra line, which sets mt as the metatable for the tables that it creates:

function Set.new (t)   -- 2nd version
local set = {}
setmetatable(set, Set.mt)
for _, l in ipairs(t) do set[l] = true end
return set
end

After that, every set we create with Set.new will have that same table as its metatable:

s1 = Set.new{10, 20, 30, 50}
s2 = Set.new{30, 1}
print(getmetatable(s1)) --> table: 00672B60
print(getmetatable(s2)) --> table: 00672B60

Finally, we add to the metatable the so-called metamethod, a field __add that describes how to perform the union:

Set.mt.__add = Set.union

Whenever Lua tries to add two sets, it will call this function, with the two operands as arguments.

With the metamethod in place, we can use the addition operator to do set unions:

s3 = s1 + s2
Set.print(s3) --> {1, 10, 20, 30, 50}

当我尝试运行它时,我得到了结果:{ union, mt, junction, tostring, new, print} 而不是 s3 中的数字。看来我已经打印了元表的内容。有人可以解释这里发生了什么吗?书上描述的是5.0版本,我使用的是Lua 5.1。这可能是造成这种情况的原因吗?

最佳答案

the code you ran 中存在错误,不在您在问题中发布的代码中:

Set.tostring 第 28 行,您将 for e inpairs(set) 更改为 for e inpairs(Set) 并且因此它始终显示 Set 的内容,而不是给定集合的内容。

关于lua - 《Programming in Lua》第 108 页对 Lua 元表感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com