Create the is() operator to test an object type

On TI-Nspire, Lua lets you work easily with classes with class() function, that is also used to create inherited classes, based on the mother class. Sadly, since this class concept is purely superficial, there is neither function nor syntax to work with specific kind of classes. In this tutorial, we’re going to see how to reproduce the “is” feature that we meet in C# for example.

The is() operator lets you distinguish between an object created with one class and another object created with another class. We are going to create the is() operator specific to Lua because it doesn’t support inherited classes tests.

Here is an example of what we are trying to do :

function is(obj, class)
  -- we are going to create it
A = class()
function A:init(x)
  self.x = x
B = class(A)
function B:init(x)
  self.x = x * 2
t = { A(1),  B(1) }
for k, v in pairs(t) do
  if is(v, A) then
    print("A class, value = "..v.x)
  elseif is(v, B) then
    print("B class, value = "..(v.x / 2))

The goal is here obvious : if we store in a table objects from different classes we some common fields, we d’like to be able to distinguish objects from a particular class.

But how write such a function in that case ? Add a specific field ? No need !
Indeed, the class() function does half of the work. It stores something in the __index field of your object (in reality a table). This one contains a reference to the mother class. When you do a = A(), a.__index is equal to A.__index (by reference) !

As simple as you guessed :

function is(obj, class)
  return obj.__index == class.__index

NB : Since the edge between classes and object is not so far big in Lua (contrary to other OOP langages where an object is created by a class), it is possible to test whether or not two objects have the same mother class with one test less :

A = class()
function A:init() end
a = A()
b = A()
is(a, b) -- returns true


Leave a Reply