ROBLOX LUA(u)函数参数检查

我有一个函数。 如你所见,我定义了fn来执行给定的参数的函数,如何检查fn函数接收的参数数量是否足够函数v所需的数量?例如,如果用户提供了2个参数,但需要3个参数,则抛出错误。

ModuleScript:

-- 变量
local dss = game:GetService("DataStoreService")
local db = dss:GetDataStore("greenwich")

-- 表
local greenwich = {}
local dbFunctions = {}

-- 函数
function greenwich:GetDB(name)
    local new = {}
    new.name = name
    coroutine.resume(coroutine.create(function()
        for k, v in pairs(dbFunctions) do
            local fn = function(...)
                local args = {...}
                return v(unpack(new), unpack(args))
            end
            new[k] = fn
            new[string.lower(k)] = fn
        end
    end))
    return new
end

function dbFunctions:Set(store, key, value)
    store = store.name
    db:SetAsync(store .. key, value)
    return value
end

function dbFunctions:Get(store, key)
    store = store.name
    return db:GetAsync(store .. key)
end

function dbFunctions:Delete(store, key)
    store = store.name
    local success, val = pcall(function()
        return db:RemoveAsync(store .. key)
    end)
    if val and success then
        return true
    else
        return false
    end
end

function dbFunctions:Has(store, key)
    store = store.name
    return not not db:GetAsync(store .. key)
end

-- 返回所有内容。
return greenwich
点赞
用户2860267
用户2860267

在 Lua 5.3.5 的标准库中,你可以使用 debug.getInfo() 函数来检查函数。返回的表包含一个名为 nparams 的字段,它会告诉你函数期望的参数数量。

local example = {}
function example.func(a, b, c)
    print(a, b, c)
end
local info = debug.getinfo(example.func)
print(info.nparams) -- 3

在基于 Lua 5.1 的自定义版本 Roblox Lua 中,debug 库被大量修改,你需要使用 debug.info() 函数。当你传入一个函数和参数 "a" 时,它会返回函数的元数。

local example = {}
function example.funcA(a, b, c)
    print(a, b, c)
end
function example:funcB(a, b, c)
    print(a, b, c)
end
function example:funcC(a, b, c, ...)
    print(a, b, c)
end

-- 输出参数数量以及是否有可变参数
print(debug.info(example.funcA, "a")) -- 3 false
print(debug.info(example.funcB, "a")) -- 4 false
print(debug.info(example.funcC, "a")) -- 4 true
2021-07-24 20:16:03