Question

I want to add to a table a variable and see the changes made in table in the single variable. I think that the problem ocurrs because when i insert the variable to the table it's passed by value.

Now I set to nil one element in the table but the variable that i want asssociate it's not modified. How I can associate the values to achieve that the next program prints "is nil" and not "is not nil".

tab = {}

x = 2
y = 4

table.insert(tab, x)
table.insert(tab, y)

for i = 1 , #tab do
    tab[i] = nil
end

if x == nil then print("is nil")
else  print("is not nil") end

SOLVED:

This is the solution. Convert the variables to tables. The problem is that the sintax becomes ugly because of the [1] index. I will see if I can hide this because i will be using a lot in my scripts this variables and I don't want to be using all the time the [] index for only one variable.

tab = {}

x = {2}
y = {4}

table.insert(tab, x)
table.insert(tab, y)


for i = 1 , #tab do
    tab[i][1] = nil
end

if x[1] == nil then print("is nil")
else  print("is not nil") end
Was it helpful?

Solution

You can't do this in lua. Not this way. The only things that have reference semantics are tables and userdata.

If you were assigning a table into tab then modifying fields of that table would be visible from the original variable and from tab.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top