Go Back

Broadening my horizons - Object oriented Lua

I decided the other weekend to learn a new language, not because i had the 'hankering' to get sick with frustration of syntax and memorization all over again, but because dangit... i like Warhammer Age of Reckoning and they use a Lua scripting engine to power their user interface.

So I drug out the notepad++ and tried to muttle around.

I was frustrated with the 'lack of' build in object orientism, so i explored some more in the documentation

Here's a little sample of what i put together as a start to 'object oriented' in lua.

 

--Begin Person.lua

Person =

{         

            lastName = "",

            firstName = ""

}

 

--constructor   

 function Person:new()

      o = {}

      setmetatable(o, self)

      self.__index = self

     return o

end

 

function Person:SetFirstName(firstname)

            self.firstName = firstname

end

 

function Person:GetName()

            return (self.firstName .. " " .. self.lastName)

end

 

function Person:SetLastName(lastname)

            self.lastName = lastname

end

 --It's a script so now i'll use the object above in a little test

local a = Person:new()

a:SetLastName("Peckham")

a:SetFirstName("James")

print(a:GetName())

print(Person:GetName())

--end Person.lua

------------

and then i thought, that's nice but what about inheritence and overriding methods?

so i did this little number

--Inherited class now with an override in it for GetName
Male = Person:new()
function Male:new()
     o = {}
     setmetatable(o, self)
     self.__index = self
     return o
end

function Male:GetName()
 return "Mr. "..Person.GetName(self)
end

--now run the objects again, note we're using Male now instead of Person

local a = Male:new()
a:SetLastName("Peckham")
a:SetFirstName("James")
print(a:GetName())
print(Person:GetName())

Facebook DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Furl it!

Post a comment!
  1. Formatting options