Annotate custom check function as assert #3418
-
|
It is sometimes nice to do some checks on variables such as: ---@param notoptional table?
local function foobar(notoptional)
assert(notoptional, "notoptional is not optional")
return notoptional.foobar
endNote the separation of those two lines, in real code those might be much further apart. Also local utils = require 'utils'
---@param notoptional table?
local function foobar(notoptional)
utils.check(notoptional, "notoptional is not optional")
return notoptional.foobar
endThis does no longer work. The annotation for ---@generic T
---@param cond T?
---@param err string?
---@return T
function utils.check(cond, err)
if not cond then
error(setmetatable({ err = err }, Error))
end
return cond
endThis works fine for assignments, but assert delivers more information, i.e. implicit casting of variables. It would be nice if there were something like |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use But there is a caveat, if your code is something like: local utils = require "utils"
local check = utils.check
check(...) -- this won't work, because runtime special is pure token text matching
require "utils".check(...) -- this won't work either
local u = require "utils"
u.check(...) -- wont work ... |
Beta Was this translation helpful? Give feedback.
You can use
"runtime.special": { "utils.check": "assert" }then you dont need to make it global.AFAIK it is pure string / token text matching.
But there is a caveat, if your code is something like: