假设我想创建一个between
运算符,例如
if (a) '<' (b) '<' (c) then
这可能吗?我希望这能行得通,但是不行
debug.setmetatable(0, {
__call = function(a, firstOperator)
if firstOperator == '<' then
return function(b, secondOperator)
if secondOperator == '<' then
return function(c)
return a < b and b < c
end
end
end
end
end
})
答案 0 :(得分:5)
debug.setmetatable(0, {
__call = function(a, firstOperator)
if firstOperator == '<' or firstOperator == '<=' then
return function(b)
return function(secondOperator)
if secondOperator == '<' or secondOperator == '<=' then
local loadstring = loadstring or load
local dynamic_code = [[
local a, b = ...
return function(c)
return a ]]..firstOperator..[[ b and b ]]..secondOperator..[[ c
end
]]
return loadstring(dynamic_code)(a, b)
else
error("Wrong syntax", 2)
end
end
end
else
error("Wrong syntax", 2)
end
end
})
print((1) '<' (2) '<' (3)) --> true
print((1) '<='(1) '<='(1)) --> true
print((1) '<' (2) '<' (0)) --> false
print((4) '<' (2) '<' (3)) --> false
print((1) '<' (0) '<' (3)) --> false
print((1) '<' (4) '<' (3)) --> false