lua - 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
解决方案
在 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
推荐阅读
- parallel-processing - GNU Parallel 不会在所有文件上运行
- javascript - 使用 swipper.js 引导 4 张卡片
- c# - 从 JsonConvert 反序列化 JSON 对象返回 null
- java - while 语句没有在 if 语句中执行?
- javascript - NextJS 中的环境变量未定义
- google-chrome-extension - 为什么在 MacOS 上的 Greasemonkey/Tampermonkey 上的本地脚本,@require 总是给我错误“无法从禁止的 URL 加载 @require”
- python - 在 Jupyterhub 中安装 R
- angular - 为什么服务获取 id 总是“未定义”?
- python - python和jupyter笔记本中的模块位置不一致
- sitecore - 目录的克隆不显示任何用于 sitecore 电子商务的产品。如何解决?