Jump to content




OO Lua


  • You cannot reply to this topic
4 replies to this topic

#1 blipman17

  • Members
  • 92 posts

Posted 07 January 2015 - 11:59 PM

After returning from learning java at scool, I started to look at Lua again.
Good old lua.
And now I want to get around object-oriented programming in lua
  • but I don't get if there is something like a standard constructor, or if you just have to make one and call it something like new()? [answered]
  • how do you define an object? [answered]
  • how do you properly use metatables?
  • are there any important convensions regarding objects and lua?
the things I do know (just checking) are:
  • instance variables are stored in an arraylist, passed back by the constructor.
  • inheritance uses metatables.
  • ":" is used instead of the "." in java.
  • "self" is used instead of "this" from java.

Edited by blipman17, 08 January 2015 - 12:26 AM.


#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 08 January 2015 - 12:09 AM

Generally, you make a table of functions, then use the __index metamethod with it. Usually you have a function that makes and returns the object. Here is a simply example:

local template = { --#define a table with stuff in it
  say = function( self, message ) --#self is the first argument
    print( self.name .. ": " .. message )
  end,
}

function makePerson( name ) --#global function, because these are usually in APIs
  local person = { name = name } --#define a new table with a key/keys
  return setmetatable( person, { __index = template } ) --#you can directly return setmetatable, but you don't have to use the result.
end

local person = makePerson( "User1" )
person:say( "Hello!" ) --#should print "User1: Hello!"

Metatable Tutorial.
All the metamethods and their uses.

#3 blipman17

  • Members
  • 92 posts

Posted 08 January 2015 - 12:19 AM

I see that "template" is highlighted blue.
Is that because it's a keyword? or is it higlighted because it's a template name?

Will take a look at those tutorials tomorrow, it's late now.

thank you for replying

#4 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 08 January 2015 - 12:22 AM

Its highlighted because the forum thinks it's a keyword. It's not. It also thinks #define is something... I think it's parsing javascript, but I could be wrong.

--This is a valid comment, but the forum doesn't know it
//this is not a valid comment, but the forum thinks it is (Let's stop the "string")
with #also not a keyword, but highlighted
new #again, not a keyword

Edited by KingofGamesYami, 08 January 2015 - 12:23 AM.


#5 blipman17

  • Members
  • 92 posts

Posted 08 January 2015 - 12:26 AM

forum makes it harder sometimes :P

thank you!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users