Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Cant set table values with a function?

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

2 comments

0

Well, you're passing the value of 'tabledifference[2]' not the table itself.

0

But isnt it supposed to update that value? How would pass the table through it?

2 answers

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

1 comment

0

I understand, but doesnt table[1]=5 work too?

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.

2 comments

0

how would I set only the second value of the table as i? Just replace i with 2?

0

Yes, and also eliminate the loop.

This discussion is preserved as it was. New answers, comments, and votes are closed.