Closed idchlife closed 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).
Thanks!
@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 ?
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.
@kikito middleclass 4.1-0 installed via luarocks
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!
@kikito no apologies needed! Thank you for this wonderful library and resolved issue!
Thank you for this fantastic library!