kikito / middleclass

Object-orientation for Lua
https://github.com/kikito/middleclass
MIT License
1.77k stars 190 forks source link

Maybe somekind offtop, but how to generally determine if variable is any class (and not primitive etc) before checking if it's instance of class? #55

Closed idchlife closed 6 years ago

idchlife commented 6 years ago

Thank you for this fantastic library!

kikito commented 6 years ago

Normally you would do this:

if x:isInstanceOf(MyClass) then ...

But of course this will fail if x is something like a number.

The nice thing is that isInstanceOf does not make assumptions about the first parameter you pass to it. You can use it this way:

if MyClass.isInstanceOf(x, MyClass) then ...

Notice that we're using . instead of : between MyClass and isInstanceOf. This is uglier than the previous example, but it will work, even if x is a number or nil. If you are doing this a lot, consider localizing the function:

local isInstanceOf = MyClass.isInstanceOf
...
if isInstanceOf(x, MyClass) then ...

Also, notice that you should not be using this a lot in the first place. Often you can replace these ifs by a call to a method, which returns true by default and false on instances of MyClass (for example).

idchlife commented 6 years ago

Thanks!

idchlife commented 6 years ago

@kikito unfortunately, it does not work :(

local class = require "middleclass"

local Product = class("Product")

local b = Product:new()
local c = 23

assert(Product.isInstanceOf(c, Product), "nope")

gives:

lua: /Users/igorandreev/.luarocks/share/lua/5.2/middleclass.lua:114: attempt to index local 'self' (a number value)
stack traceback:
    /Users/igorandreev/.luarocks/share/lua/5.2/middleclass.lua:114: in function 'isInstanceOf'
    tests/common.lua:8: in main chunk
    [C]: in ?
kikito commented 6 years ago

Ok. That might actually be a bug - apologies. I will try to give this a look during the weekend.

For now you should be able to "walk around the issue" by making sure that c is a table:

assert(type(c) == "table" and Product.isInstanceOf(c, Product), "nope")

What version of middleclass are you running? Line 114 should not be raising that error.

idchlife commented 6 years ago

@kikito middleclass 4.1-0 installed via luarocks

kikito commented 6 years ago

Hi there, I just pushed a change to master which should fix this issue. I have not released the a new version of middleclass because I want to fix a different issue first, so if you want it you'll have to download the middleclass.lua file from master. Apologies for the delay!

idchlife commented 6 years ago

@kikito no apologies needed! Thank you for this wonderful library and resolved issue!