Is there a condition to check whether an argument is undefined? Usually, from what I remember, NaN/undefined values are not equal to themselves, however the following function is not demonstrating that behavior.
local function func(arg)
print(arg, arg == arg)
end
func() --> nil, true
Could there have been a recent update that changed this behavior? Or does my memory strike me incorrect?
To specify, I’m trying to differentiate undefined values, and nil values. In my book, calling a function while explicitly setting nil in the argument, counts it as an “existing” argument.
I don’t think undefined is value type in Lua, and if it is this I found a quote in The Developer Hub that could help you:
If you call a Lua function with more parameters than it’s expecting, the excess ones will be ignored. Conversely, if the function expects more parameters than you provide, the value nil will be used for all missing parameters.
There’s no “undefined” value in Lua. When you call a function, each arguments (including the nil argument) gets pushed to the stack so when you pass no arguments (so f()), no values gets pushed to the stack.
You can do this by getting subtracting the top by the base in lua_State (which the function lua_gettop does).
Here’s an example
static int luaB_func (lua_State *L) {
int n = lua_gettop(L);
if (n == 0) {
/* your code here if argument #1 is "undefined" */
} else {
/* your code here if argument #1 exist (including argument #1 being nil) */
}
}
If you can’t cross the | boundary in the Lua | C boundary then this is only possible with varargs. You can then use select("#", ...) or table.pack(...).n as both of these call lua_gettop under the hood.
local function func(...)
print(select("#", ...), table.pack(...).n)
end
print(func()) --> 0, 0
print(func(nil)) --> 1, 1
I don’t think the Luau team will silently change semantics like this. One feature of Luau is compatibility with Lua 5.1.