gpt4 book ai didi

Lua运算符重载

转载 作者:行者123 更新时间:2023-12-04 03:09:58 24 4
gpt4 key购买 nike

我在网上发现了一些地方,说Lua中的运算符是可重载的,但我似乎找不到任何示例。

有人可以提供一个例子,例如,重载+运算符以使其像..运算符那样工作以进行字符串连接吗?

编辑1:亚历山大·格拉迪什和RBerteig:
如果运算符重载仅在两个操作数为相同类型时才起作用,并且更改此行为并不容易,那么以下代码如何起作用? (我不是故意冒犯,我才刚开始学习这种语言):

printf = function(fmt, ...)
io.write(string.format(fmt, ...))
end

Set = {}
Set.mt = {} -- metatable for sets

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


function Set.union (a,b)
-- THIS IS THE PART THAT MANAGES OPERATOR OVERLOADING WITH OPERANDS OF DIFFERENT TYPES
-- if user built new set using: new_set = some_set + some_number
if type(a) == "table" and type(b) == "number" then
print("building set...")
local mixedset = Set.new{}
for k in pairs(a) do mixedset[k] = true end
mixedset[b] = true
return mixedset
-- elseif user built new set using: new_set = some_number + some_set
elseif type(b) == "table" and type(a) == "number" then
print("building set...")
local mixedset = Set.new{}
for k in pairs(b) do mixedset[k] = true end
mixedset[a] = true
return mixedset
end

if getmetatable(a) ~= Set.mt or
getmetatable(b) ~= Set.mt then
error("attempt to 'add' a set with a non-set value that is also not a number", 2)
end

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.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

s1 = Set.new{10, 20, 30, 50}
s2 = Set.new{30, 1}

Set.mt.__add = Set.union

-- now try to make a new set by unioning a set plus a number:
s3 = s1 + 8
Set.print(s3) --> {1, 10, 20, 30, 50}

最佳答案

metatable函数仅适用于表,但是您可以使用debug.metatable设置字符串metatable ...

> mt = {}
> debug.setmetatable("",mt)
> mt.__add = function (op1, op2) return op1 .. op2 end
> ="foo"+"bar"
foobar
>

另一种方法是使用 debug.getmetatable来增强内置字符串的元表(在下面的评论中回答问题):
~ e$ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> debug.getmetatable("").__add = function (op1, op2) return op1 .. op2 end
> ="foo"+"bar"
foobar
>

关于Lua运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2810545/

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