Log In  


I'm trying to write a function to switch negative to positive and vise-versa. I've got:

foot=3

function switch(f)
 f*=-1
end

when I call switch(foot) it returns the original value but if at the command prompt I type "foot*=-1 it preforms as expected.

Thanks for any help and sorry for these remedial questions.

--
-john

1


Try this:

foot=3

function switch(f)
 return f*-1
end

foot=switch(foot)

print(foot)

You can also write -foot without any multiplication.


Why not just:

foot = 3
print(-foot)

and to "switch":

foot = -foot

Thanks for all the feedback, I'm still unclear as to why my original snippet didn't work. I was under the impression that pico8(lua) was a "pass by reference" language. Here is a non math version that also doesn't do what I expect it to:

foot="foo"

function switch(f)
 f="bar"
end

switch(foot)

print(foot)

returns foo


Strings and numbers are not passed as a reference, no. Only tables are. Strings aren't even moddable in-place, you can only construct new string values.


ahh, thank you @JTE


Its a tricky but important distinction, xyzzy. In pretty much any language, saying a = x makes 'a' hold the contents of 'x', whether x is a reference or a bare value.

a = 1
b = a
b = 2
-- a is still 1 now

This code evaluates '1', and puts that value or reference in a. Then, it evaluates 'a', and puts either the value 1 or a reference to 1 in 'b'. So when we change what a was, b is unaffected.



[Please log in to post a comment]