This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
FredMastro's profile picture

Trying GPS turtorial using vector to print String fails

Started by FredMastro, 10 March 2014 - 01:15 PM
FredMastro #1
Posted 10 March 2014 - 02:15 PM
I just started working on computercraft and going through some of the examples. I've setup a GPS and testing out some of the LUA language. Running into an issue.

From the tutorial I tried this



local home = vector.new(5, 91, 478)
print("Home is "..home.x..", "..home.y..", "..home.z)
local position = vector.new(gps.locate(5))
print("position is "..position.x..", "..position.y..", "..position.z)
local displacement = position - home
print("displacement is "..displacement.x..", "..displacement.y..", "..displacement.z)
print("I am "..displacement.tostring().." away from home!!!")

The last line bombs with attempt to index ? a nil value. So I guess it's null but yet I get values from the other variables if I print them out.

Is the tutorial outdated or did I miss something?
CometWolf #2
Posted 10 March 2014 - 02:45 PM
Oh wow, i wasn't even aware of the vector API. I'm not entirely certain how the vector metatables are set up, but you are calling the tostring function wrong. It should be

displacement:tostring()
or

displacement.tostring(displacement)
Otherwise you aren't passing any arguments to it.
Anavrins #3
Posted 10 March 2014 - 04:53 PM
The "__tostring" metamethod does not get called with displacement.tostring() but with tostring(displacement) or simply by concatenating it with another string.
So in this case, what you need to do is
print("I am "..displacement.." away from home!!!")
And it will print "I am 123,456,789 away from home!!!"
Edited on 10 March 2014 - 03:56 PM
CometWolf #4
Posted 10 March 2014 - 04:58 PM
According to the wiki, a vector should contain the function tostring, so using displacement:tostring() should work aswell. I don't know if this stuff is outdated or what though, since i've never used it myself.
http://computercraft...ectorA:tostring

Using the metamehod is probably the cleanest way however.
Edited on 10 March 2014 - 04:01 PM
Anavrins #5
Posted 10 March 2014 - 11:00 PM
Oh you're right, I've completely went pass over the "tostring" method.
In this case it would indeed be "displacement:tostring()" with a colon instead of a period.
Edited on 10 March 2014 - 10:01 PM