Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
"attempt to index local 'self' (a nil value)" Error — Gideros Forum

"attempt to index local 'self' (a nil value)" Error

dddentdddent Member
edited April 2014 in General questions
Hello,

I'm getting this error in the following code in line 18:

-- Vector2 class: a two dimensional Vector
Vector2 = Core.class()

function Vector2:init()
self.x = 0
self.y = 0
end

function Vector2:create(x,y)
newvec = Vector2.new()
newvec.x = x
newvec.y = y
return newvec
end

function Vector2:toString()
return tostring(self.x)..tostring(self.y) -- << this is where the error occurs

end

myVector = Vector2:create(2,4)
print(myVector.toString())

So, I guess the question is, how do I operate with an objects own properties inside a function that belongs to that object.

Thanks,
David

Comments

  • OZAppsOZApps Guru
    Accepted Answer
    @dddent, David... the issue is quite simple
    function Vector2:toString()
    is actually interpreted as
    function Vector2.toString(self)
    . I think you already know this.

    When you are calling the same in
    print(myVector.toString())
    you are not passing the value to self but the function is expecting self to be present and thereby print the x and y from self.

    all you need to do is either
    1.
    print(myVector:toString())
    OR
    2.
    print(myVector.toString(myVector))(
    cheers,
    twitter: @ozapps | http://www.oz-apps.com | http://howto.oz-apps.com | http://reviewme.oz-apps.com
    Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
    Cool Vizify Profile at https://www.vizify.com/oz-apps
    +1 -1 (+2 / -0 )Share on Facebook
  • @ar2rsawseen, thanks, yeah I knew that, didn't realize I wasnt using ":"
Sign In or Register to comment.