Search code examples
lualua-table

Need help/Clarification in Lua


Yesterday I have seen a code written in Lua using oop method under "Love Framework" so I tried to write the same code by changing some variable to understand it better.

Class = require 'lib/class'-- I'm using Class library https://github.com/vrld/hump/blob/master/class.lua

Bala = Class{__includes = Shubham}

-- here I'm Calling Bala Class

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

-- Here I've initialized Bala Class using 'init' to pass a argument inside it.

function Bala:init(def)
   Shubham.init(self, def)
end

-- Here I've created Shubham class and pass the same argument.
Shubham = Class{}

function Shubham:init(def)
  self.market = def.market
  self.Rashan = def.Rashan
end

print(chawal.market)
The output is table: 00800320

So my question is how to call those argument from Shubham Class by print() and using terminal only and my 2nd question is why are we using 'self' in Shubham.init(self, def) what's the actual meaning of this line.


Solution

  • You have just put your code in the incorrect order.

    when executing a lua file you're going to work down it from top to bottom, so if you reference something from a lower section in the file it will not exist/have been loaded yet.

    the first example would be here:

    chawal = Bala {
               market = "A-Market",
               Rashan = "poha"
            }
    
    -- Here I've initialized Bala Class using 'init' to pass a argument inside it.
    
    function Bala:init(def)
       Shubham.init(self, def)
    end
    

    you are doing an action that would call Bala:init before Bala:init is defined, the class library "saves" you from an error, but that just causes you to think the code "worked"

    This should be the correct order of the sections:

    Class = require 'lib/class'
    
    Shubham = Class{}
    
    function Shubham:init(def)
      self.market = def.market
      self.Rashan = def.Rashan
    end
    
    Bala = Class{__includes = Shubham}
    
    function Bala:init(def)
       Shubham.init(self, def)
    end
    
    chawal = Bala {
               market = "A-Market",
               Rashan = "poha"
            }
    
    print(chawal.market)
    

    Output:

    A-Market