This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
blipman17's profile picture

OO Lua

Started by blipman17, 07 January 2015 - 10:59 PM
blipman17 #1
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
  1. 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]
  2. how do you define an object? [answered]
  3. how do you properly use metatables?
  4. are there any important convensions regarding objects and lua?
the things I do know (just checking) are:
  1. instance variables are stored in an arraylist, passed back by the constructor.
  2. inheritance uses metatables.
  3. ":" is used instead of the "." in java.
  4. "self" is used instead of "this" from java.
Edited on 07 January 2015 - 11:26 PM
KingofGamesYami #2
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.
blipman17 #3
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
KingofGamesYami #4
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 on 07 January 2015 - 11:23 PM
blipman17 #5
Posted 08 January 2015 - 12:26 AM
forum makes it harder sometimes :P/>

thank you!