首页 > 解决方案 > ROBLOX LUA(u) 检查函数的参数

问题描述

我有这个功能。如您所见,我定义fn运行一个提供参数的函数,我如何检查fn函数接收的参数数量是否是函数所需的数量v?即,如果用户提供了 2 个 args 但需要 3 个,则抛出错误。

模块脚本:

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

-- Tables
local greenwich = {}
local dbFunctions = {}

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

-- Returning everything.
return greenwich

标签: luaroblox

解决方案


在 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.info()函数。当你传入一个函数和参数“a”时,它返回函数的arity。

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 out the number of args and whether there's a vararg
print(debug.info(example.funcA, "a")) -- 3 false
print(debug.info(example.funcB, "a")) -- 4 false
print(debug.info(example.funcC, "a")) -- 4 true

推荐阅读