Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Class variables not working inside class functions

edited July 2013 in Bugs Posts: 3

When I use the function "haha()" it does not work, but just calling the variable "str" returns the proper value.

Code: (just defined one of these in main and then tried to use the "haha()" function)

TouchHandler = class()
function TouchHandler:init()
    self.touches = {}
    self.touchstate = {}
    self.str = "stupid computer......"
function TouchHandler:touched(touch)
    self.touches[] = touch
    self.touchstate[] = touch.state
function TouchHandler:count()
    local t = 0
    for k,touch in pairs(self.touches) do
        if self.touchstate[] == BEGAN or self.touchstate[] == MOVING then
            t = t + 1
    return t
function TouchHandler:haha()
    return self.str


  • just using:
    :works, but using:

  • error: [string "TouchHandler = class()..."]:16: attempt to index local 'self' (a nil value)

  • edited July 2013 Posts: 391

    Looks fine to me. I added your class in a blank project and then added:

    function setup()
        th = TouchHandler()

    It displays the correct text in the output.

  • Jmv38Jmv38 Mod
    edited July 2013 Posts: 3,297

    That's a classical one: 99% of times when i get this error message, i have written object.method() instead of object:method()!

  • Posts: 391

    In order to use those class functions you first must declare an object that utilizes that class.

    touchHandler = TouchHandler()

    Then you can use touchHandler:haha()

  • IgnatzIgnatz Mod
    Posts: 5,396

    @99MarioSuper - the "self" thing is really confusing, so I wrote about it here
    (see Class section)

  • Posts: 2,161

    @Slashin8r is right. You haven't defined an instance of the TouchHandler class but are calling the class function directly.

  • Posts: 157

    yup... somewhere in your init() you need to write:


    and then you access the methods with

       print handler:haha()

    It's a common and easy mistake to make. It doesn't help that Lua's typing isn't very strong, so you can do stuff by accident that requires specific declarations in other languages.

    In c#, for example, you'd never get away with calling TouchHandler.haha(), unless haha() was declared as a static method. And if you did declare haha() as static, it wouldn't compile because .str isn't static. And if you declared .str as static... well, everything would work, and .str would be shared across all instances of your class.

    That's one of the things I don't like about scripting languages: when you get away from strong typing, you entirely lose the compiler's ability to smack you upside the head and tell you're being an idiot.

    And trust me, I need that particular bit of assistance. I make a lot of dumb mistakes when coding, and the compiler is very busy telling me "hey stupid. You can't do that!"

Sign In or Register to comment.