I create an empty table, t. I then try to set it nil by using function destroy. While in function, the table becomes nil, but outside of the function nothing has happened to it until I explicitly set it to nil
Is there any way to set a table to nil via using a function in Lua?
local t = {}
local function destroy(input)
print("in function",input)
input = nil
print("in function",input)
end
print(t)
destroy(t)
print(t)
t = nil
print(t)
There is no such thing as "setting a table to nil
". You can set one of the values within a table to nil
. You can set a variable to nil
. But you cannot set a table to nil
. Just like you cannot set an integer to nil
or set a string to nil
.
The only way to set a variable is to actually set that variable. input
and t
are two separate variables. They may both be holding the same table, but modifications to one variable will not magically affect the other variable.
If you want destroy
to be able to generally change the place where the caller of destroy
stored the table being passed in... you can't. A function generally cannot affect the variables used to call it. A function's parameters contain the values taken from the arguments passed to it; they do not contain the variables themselves, if for no other reason than the fact that you don't have to pass variables to a function (you can pass the result of expressions and so forth, which don't have to be stored in "variables").
There are specific instances where a function might be able to do that. In your very specific code, because local t
is visible to the destroy
function, it can actually perform t = nil
. However, that only works in this specific code; move t
's declaration below destroy
, and now it can't reach it.
Overall, what you want cannot be done.