2

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)

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A function argument is a value derived from an expression. It is only happenstance if an expression is simply a variable.
You cannot set a table to nil but you can effectively delete a table by setting the variable storing it to nil! Okay I'm done talking like you now. All you are doing is creating more confusion in a convoluted condescending manner. Stop speaking to people like that. You CAN redefine table entries (t.x=55) within that destroy function, you skipped that part among others in your supposedly concise answer. And oh you can also provide a solution to the problem too. You don't deserve any of your points. b={} function a() return nil end print(b) b=a() print(b)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.