Lua : self.array becomes NIL after using it to assign members of other object

Viewed 92

I had this class variable hash_tuples. When I am using that same variable to initialize member of other class Utils. The value somehow is becoming nil.

Posting minimal reproducible example of my problem. Check lines with comments one of the print works while the other gives me error, the variable I just printed has become nil.

Utils = { list_tuples = {} }

function Utils:new(hash_tuples)
        o = o or {}
        setmetatable(o, self)
        self.__index = self

        self.list_tuples = hash_tuples
        return o
end


ConsistentHashing = { num_machines = 0, num_replicas = 0, hash_tuples = {}}

function ConsistentHashing:new(num_machines, num_replicas)
        -- check docs for these 3 lines
        o = o or {}
        setmetatable(o, self)
        self.__index = self

        self.num_machines = num_machines or 0
        self.num_replicas = num_replicas or 0

        for j = 1, self.num_machines, 1
        do
                for k = 1, self.num_replicas, 1
                do
                        table.insert(self.hash_tuples, {j,k, "hash_value"})

                end
        end
        return o
end

function ConsistentHashing:getMachine(key)
        print(#self.hash_tuples,table.concat(self.hash_tuples[12], ", ")) -- Works
        local ubu = Utils:new(self.hash_tuples)
        print(#self.hash_tuples,table.concat(self.hash_tuples[12], ", ")) -- Same line gives error

        return self.hash_tuples[index][1]
end

cs = ConsistentHashing:new(4, 3)
while(1)
do
        io.write("Please enter the key\n")
        local key = io.read()
        print (cs:getMachine(key))
end

Output :

Please enter the key
123
12      4, 3, hash_value
lua: temp.lua:37: attempt to get length of a nil value (field 'hash_tuples')
stack traceback:
        temp.lua:37: in method 'getMachine'
        temp.lua:47: in main chunk
        [C]: in ?

How is this possible? What going behind the scenes?

EDIT : If I remove the index meta method I get another error

Please enter the key
54
lua: temp.lua:45: attempt to call a nil value (method 'getMachine')
stack traceback:
        temp.lua:45: in main chunk
        [C]: in ?
1 Answers

Your o is a global that never actually contained a hash_tuples field. On the line where the print works, it was accessing that field through the __index metamethod and actually getting it from ConsistentHashing. Calling Utils:new broke it, because it changed the metatable on o to be Utils, which doesn't provide a field that way.

I'm also pretty sure you got self and o backwards in a few places.

Related