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
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
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
.