有没有办法区分函数中被省略的参数和传递的参数为 nil 之间的区别?

Cho*_*hee 3 lua function

假设我有一个返回布尔值的函数,并且有一个设置覆盖的函数,以便第一个函数始终返回指定的布尔值。第二个函数看起来像这样:

function override(override, bool)
    bool = bool and true or false --convert to pure Boolean
    
    if override then
        boolOverride = bool
    else
        boolOverride = nil
    end
end
Run Code Online (Sandbox Code Playgroud)

但是,我想让它在没有指定 bool 的情况下也可以bool = not boolOverride。所以那就是这样的:

function override(override, bool)
    if type(bool) == "nil" then
        bool = not boolOverride
    else
        bool = bool and true or false --convert to pure Boolean
    end
    
    if override then
        boolOverride = bool
    else
        boolOverride = nil
    end
end
Run Code Online (Sandbox Code Playgroud)

问题是,bool = bool and true or false如果参数明确为零而不是不存在,我希望它运行默认选项。我可以用来实现这一目标的两种情况之间有什么区别吗?

LMD*_*LMD 5

有没有办法区分函数中被省略的参数和传递的参数为 nil 之间的区别?

就在这里!Lua 在堆栈上传递参数并返回值。“堆栈在此处结束”(“无”)和“堆栈上有一个 nil 值”之间存在差异。区分两者的最直接方法是使用select("#", ...),它可以为您提供堆栈上剩余值的计数。让我们编写一个简单的函数,如果调用一个参数,它会执行一件事,如果调用没有参数/“无”(空变量参数),则执行另一件事,否则会出错:

function f(...)
    local n = select("#", ...)
    if n == 0 then print"nothing"
    elseif n == 1 then print(...)
    else error"too many arguments" end
end
f() -- nothing
f(nil) -- nil
f(1, 2) -- errors with "too many arguments"
Run Code Online (Sandbox Code Playgroud)