Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Cant set table values with a function?

Asked by 10 years ago

How can I change table value 2 with a function? When I print the difference it works, but when I print it after it's still 0.

-----global value------
 tabledifference= {0,0,0}

function differences(new,current,difference)
    difference = new-current
    print(difference)
end

print(tabledifference[2])

differences(tableonenew[2], tablecurrent[2], tabledifference[2])
--lets say tabeonenew[2] is 5, and tablecurrent[2] is 50
0
Well, you're passing the value of 'tabledifference[2]' not the table itself. Tkdriverx 514 — 10y
0
But isnt it supposed to update that value? How would pass the table through it? Orlando777 315 — 10y

2 answers

Log in to vote
0
Answered by 10 years ago

I'm not 100% sure on what you're asking, but I'll give it my best shot. So, if you're asking how to set the value of a table through a function, you could do it like this:

local tab = {};
setmetatable(tab,{__call = function(self,v,i) local i = i or #self+1 rawset(self,i,v) end});

Now, to add to the table, you can do this:

tab(24,1); -- sets index 1 to value 24
0
I understand, but doesnt table[1]=5 work too? Orlando777 315 — 10y
Ad
Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

When you write

differences(tableonenew[2], tablecurrent[2], tabledifference[2])

Lua has to evaluate the arguments. That means it says, "Oh, tableonenew[2] is 5, and tablecurrent[2] is 9 and tabledifference[2] is 4 so let's give differences 5, 9, 4:

differences( 5, 9, 4)

That is, when it's evaluated, you've completely obliterated where it came from -- it doesn't care that you passed it things that were from particular tables.


Instead, you have to pass the tables themselves to allow them to be changed.

-- to = a - b
function differences(a, b, to)
    for i = 1, #a do
        to[i] = a[i] - b[i]
    end
end

Is an example of something that would subtract each element of b from each element of a and store them in to.

0
how would I set only the second value of the table as i? Just replace i with 2? Orlando777 315 — 10y
0
Yes, and also eliminate the loop. BlueTaslem 18071 — 10y

Answer this question