Howdy, Stranger!

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

Metatable function names *Solved*

edited January 2015 in Questions Posts: 82

Hello all,

I'm dealing with quite a strange problem here. I'm trying to add a function to vec4(), but Codea's giving me a hard time with naming the function. Here is an example:

function setup()
    m = getmetatable(vec4())
    m.rotate = function(v,n)
        return n*(v.x+v.y+v.z+v.w)
    end

    p = vec4(1,2,3,4)
    print(p:rotate(5))
end

This gives the error "attempt to call method 'rotate' (a number value)". But when I try the name 'trace', it works fine. Other names that give the same error are 'gaga', 'rot' and 'rotplane', while the names 'haha' and my own name 'kjell' both work fine. This seems like random behavior to me, am I overseeing something? All these function names should work, shouldn't they?

Comments

  • Posts: 1,976

    I don't think you need to fiddle with the metatable values for this. Have you tried something like this?

    vec4.rotate = function(v,n)
        return n*(v.x+v.y+v.z+v.w)
    end
    
  • edited January 2015 Posts: 502

    @SkyTheCoder actually @Kjell is right in his assumption to use getmetatable Here's a similar question and an answer: http://codea.io/talk/discussion/comment/19708/#Comment_19708

  • Posts: 447

    You can't use a method name beginning with an r for a vec4. Nor b, g, or a. It's because vec4s are also colors so r,g,b, and a are reserved for the four components of the vec4 when thought of as a color. Due to how they are implemented underneath, any method that simply begins with an r is interpreted as r. I guess it's a speed thing.

  • edited January 2015 Posts: 502

    @LoopSpace nice observation and good point

  • Posts: 82

    @LoopSpace Ah, wow, I never thought of that, although I read about it in the reference a couple of days ago. It's supposed to double as a color vector, right? Anyway, thank you very much for making this clear!

Sign In or Register to comment.