oop - How can one implement OO in Lua? -
lua not have build in support oo, allows build yourself. please share of ways 1 can implement oo?
please write 1 example per answer. if have more examples, post answer.
i think of oop being encapsulation of data inside container (the object) coupled subset of operations can done data. there lot more it, let's assume simple definition , build in lua (also familiarity other oo implementations can nice boost reader).
as little exposure lua may know, tables neat way store key-value pairs , in combination strings, things start become interesting:
local obj = {} -- new table obj["name"] = "john" obj["age"] = 20 -- there's shortcut! print("a person: " .. obj.name .. " of age " .. obj.age)
string values keys in table can accessed in way alike members of struct in c or public members of object in c++/java , similar languages.
and cool magic trick: let's combine anonymous functions.
-- assume obj last example obj.hello = function () print("hello!") end obj.goodbye = function () print("i must going.") end obj.hello() obj.goodbye()
awesome right? have means of having functions stored inside our tables, , again can see resembles how methods used in other oop languages. missing. how can access data belongs our object inside our method definitions? addressed changing signature of functions in table this:
-- assume obj last example obj.inspect = function (self) print("a person: " .. self.name .. " of age " .. self.age) end obj.hello = function (self) print(self.name .. ": hello! i'm " .. self.name) end obj.goodbye = function (self) print(self.name .. ": must going.") end -- receives calling object first parameter obj.inspect(obj) -- person: john of age 20 obj.hello(obj) -- john: hello! i'm john obj.goodbye(obj) -- john: must going
that solves in simple manner. maybe drawing parallel way things work in python (methods explicit self) can aid in learning how works in lua. boy, isn't inconvenient passing these objects explicitly in our method calls? yeah bothers me too, there's shortcut aid in use of oop:
obj:hello() -- same obj.hello(obj)
finally, have scratched surface of how can done. has been noted in kevin vermeer's comment, lua users wiki excellent source of information topic , there can learn how implement important aspects of oop have been neglected in answer (private members, how construct objects, inheritance, ...). have in mind way of doing things little part of lua philosophy, giving simple orthogonal tools capable of building more advanced constructs.
Comments
Post a Comment