lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 21 May 2013 02:19, Coved Oswald <oswald.coved@outlook.com> wrote:
> I have a program and I was thinking on making it OO so I made a color class
> to start off with, and it doesn't work the way I want it to. I have a
> constructor, and I want to make sure that the r, g, and b values (and
> eventually the a value) will not be able to be over 255. So a simple %
> operator will suffice, right? I have this so far:
>
> Color = {r = 0, g = 0, b = 0}
>
> function Color:new(o)
>      local o = o or {}
>      o.r = o.r % 255
>      o.g = o.g % 255
>      o.b = o.b % 255
>      setmetatable(o, self)
>      self.__index = self
>      return o;
> end
> --other constructors, methods, and implementation not shown
> It gives me an error of "can't perform arrithmictic on table: o.b"
> I wasn't sure if the error is in the love2d runtime, or is it on my bad?

If you call that constructor without an `o` argument, it creates an
empty table and assigns it to a new local variable `o`. This table
doesn't have any values associated with the "r", "g" or "b" keys, so
you're trying to take the modulus of a nil value (which will throw an
error).

You could solve this by defaulting to 0 on each of the three modulo
lines (`o.b % 255` becomes `(o.b or 0) % 255`) or setting the
metatable of the object before performing the modulo operations (so
the table lookups return 0 instead of nil).