Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Would be nice if there's some method to check if the instance inherits from some class #132

Closed
wolf81 opened this issue Feb 13, 2024 · 2 comments

Comments

@wolf81
Copy link

wolf81 commented Feb 13, 2024

A bit like classic, which includes a instance:is(T) method.

The implementation in classic is as follows:

function Object:is(T)
  local mt = getmetatable(self)
  while mt do
    if mt == T then
      return true
    end
    mt = getmetatable(mt)
  end
  return false
end

It's probably possible to do the same here (will check soon and make PR if possible).

Source: https://github.com/rxi/classic/blob/master/classic.lua

@vrld
Copy link
Owner

vrld commented Feb 13, 2024

This won't work as in classic, because hump does not really do inheritance. Instead, class:include(other) copies entries from other. So class:is(other) would have to check the meta table and if it does not match it would have to check whether all entries of other are also in class and (have the same type). I imagine this can be quite expensive.

I am also not a fan of such a method, because it encourages bad code:tm:. In most cases you should rely on polymorphism instead. If you really, really need to, you can use duck typing instead. Though really, one should try to use composition over inheritance.

Feel free to convince me otherwise.

@wolf81
Copy link
Author

wolf81 commented Jun 5, 2024

@vrld Sorry for late response and thanks for your answer. Your answer makes sense.

With regards to hump.class, I decided to use a different approach now, a little bit based on ECS. I have an entity and at can include various components which will be added to an array inside the class. This way, I can check types of components in a clean way (using getmetatable check).

@wolf81 wolf81 closed this as completed Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants