Lua中的选择函数总是返回nil

在过去,这段代码确实起作用,然后突然函数将变量结果变为nil。

function choose(n1,n2)
    local r = math.random(1,2)
    if not n1 or not n2 then error("选择一个数字或字符串将导致nil。") end -- 如果为nil,则出现错误
    if r<1.5 then
        return n1
    else
        return n2
    end
end
function choose(v1,v2,v3)
    local r = math.random(1,3)
    if not v1 or not v2 or not v3 then error("选择一个数字或字符串将导致nil。") end --如果为nil,则出错
    if r==1 then
        return v1
    elseif r==2 then
        return v2
    else
        return v3
    end
end

local Red,Yellow=2,12
choose(Red,Yellow)

我得到的错误是;

文件:"C:\Users\My Computer\Desktop\test.lua"3行,
    选择一个数字或字符串将导致nil
点赞
用户14803024
用户14803024

Lua 不支持函数重载。它会默认你是在更新函数并且总是调用最近定义的。

在你的例子中,会引发错误,因为 v3 没有被定义。

2020-12-23 14:55:33