Jump to content




OOP in Lua


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

#41 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 13 January 2013 - 12:49 AM

Now back to topic of OO in Lua... I have a question. Does anyone know if there is a way to do something to the effect of
object.__type
or is there anyway to add in so the following would work
local myObj = object:new()

print( type( myObj ) )
would print something like say "object"

EDIT: I do know about __tostring but was just wondering if support can be added for type

Edited by TheOriginalBIT, 13 January 2013 - 12:51 AM.


#42 Orwell

    Self-Destructive

  • Members
  • 1,091 posts

Posted 13 January 2013 - 02:22 AM

I searched thoroughly accross the internet, and type won't check for the __type metafield, or any other. Many suggestions were made to do this though. Depending on the situation, you could redefine type (I found some examples of that), or just plainly use the __type metafield?

#43 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 13 January 2013 - 02:27 AM

View PostOrwell, on 13 January 2013 - 02:22 AM, said:

I searched thoroughly accross the internet, and type won't check for the __type metafield, or any other. Many suggestions were made to do this though. Depending on the situation, you could redefine type (I found some examples of that), or just plainly use the __type metafield?

I wasn't even aware a __type metafield existed, I just meant something like it... I tried redefining and it didn't quite work how I wanted it to... I have another way to get to the desired outcome, just using type would have been nicer... oh well... thanks for the help :)

#44 Orwell

    Self-Destructive

  • Members
  • 1,091 posts

Posted 13 January 2013 - 02:30 AM

View PostTheOriginalBIT, on 13 January 2013 - 02:27 AM, said:

View PostOrwell, on 13 January 2013 - 02:22 AM, said:

I searched thoroughly accross the internet, and type won't check for the __type metafield, or any other. Many suggestions were made to do this though. Depending on the situation, you could redefine type (I found some examples of that), or just plainly use the __type metafield?

I wasn't even aware a __type metafield existed, I just meant something like it... I tried redefining and it didn't quite work how I wanted it to... I have another way to get to the desired outcome, just using type would have been nicer... oh well... thanks for the help :)
__type is only mentioned in some documents, I suppose that the functionality has been planned on earlier. Kaos had a nice type function in the other thread..

#45 Eric

  • Members
  • 92 posts
  • LocationUK

Posted 14 January 2013 - 12:39 PM

You can take the python approach, where most builtin functions look for a magic method first. For example:

local rawtype = type
local function metamethod(object, name)
    if rawtype(x) ~= "table" then return end
    local mt = getmetatable(x)
    if not mt or rawtype(mt) ~= "table" then return end
    return rawget(mt, '__'..name)
end
local function improve(name)
    local old = _G[name]
    _G[name] = function(x, ...)
        return (metamethod(x, name) or old)(x, ...)
    end
end
improve('type')
improve('next')
improve('unpack')
function repr(x)
    -- do stringification of tables and strings
end
improve('repr')


#46 BigSHinyToys

  • Members
  • 1,001 posts

Posted 23 January 2013 - 07:57 AM

View PostChunLing, on 09 January 2013 - 12:09 AM, said:

I have to admit, I'm...I've never really understood the point of object oriented programming. I mean, I totally get having different data types, but I don't get packing them into objects and then only interacting with those objects according to certain methods.

Perhaps it's because that's not at all how I approach real world objects. I'm totally comfortable taking them apart and arranging their basic elements to suit my current needs, and totally uncomfortable with things that are made to be difficult to disassemble and modify according to the situation. Of course, it's a two steps forward one step back kinda process. I guess that for every thousand dollars of time, effort, and money I save, I gotta blow at least a couple hundred somewhere by tinkering with something I shouldn't have tampered with. But usually that's because some idiot tried to make it tamper-proof.

That's what programming objects feel like to me, tamper-proofing. Tamper-proofing is for bombs and other front-end weapons, so that the enemy doesn't disarm them and use the components against you somehow.

Does that make me weird? Probably a little.
I only know lua and have little understanding of OOP I can see how objects could be useful in some contexts making code cleaner and allowing reuse. I made this before I learn about OOP as it isn't really OOP but I think (could be wrong) shares some characteristics.

net api
http://pastebin.com/rBNb2vnq
test script
http://pastebin.com/0Dav7ga5

having simple components that react in predictable ways while being self contained allows programing of higher lever code not worrying about the lower lever work example calling a object to draw its self vs making a function to draw based from data in tables and other locations.

This tutorial has explained a lot of things I was having a hard time understanding. Thanks it is a great tutorial and I can see OOP being very helpful in future projects I work on.

#47 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 02 May 2013 - 08:44 AM

I alway get an error:
Attemptbto call nil...

But I use the code of the OP.

Code:to be sure that I do it right
Person = {}
Person_mt = {}
Person_mt.__index = Person

function Person.new()
Local personObject = { name =""}
setmetatable(personObject, Person_mt)
return personObject
end

function Person.getName(self)
return self.name
end

function Person.setName(self, newName)
self.name = newName
end

function Person.toString(self)
return "Person Object. Name =" .. self.name
end

P1 = Person:new()
P1:setName("John")
print(P1:toString())

What did I do wrong?

#48 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 02 May 2013 - 08:49 AM

View PostFreack100, on 02 May 2013 - 08:44 AM, said:

-snip-
local does not have a capital L...

also as it was stated at some point you may as well remove the Person_mt table and just do this
Person = {}
Person.__index = Person

function Person.new()
  local personObject = { name = "" }
  setmetatable(personObject, Person)
  return personObject
end

function Person.getName(self)
  return self.name
end

function Person.setName(self, newName)
  self.name = newName
end

function Person.toString(self)
  return "Person Object. Name = " .. self.name
end

P1 = Person:new()
P1:setName("John")
print(P1:toString())
There was no point to create a table, just so it could point to itself.

#49 GammaPaladin

  • Members
  • 10 posts

Posted 05 October 2013 - 02:33 PM

View PostRunasSudo-AWOLindefinitely, on 12 January 2013 - 01:15 PM, said:

View PostChunLing, on 12 January 2013 - 04:03 AM, said:

why the heck can't I get/set this value?
If something is set as "private" or "protected", there's usually a good reason for it (validation, need to keep track of stuff, etc) and you can usually get it in some form or another through some method. But, if you reealllly want to...
If his experience is mainly coding minecraft mods, I could understand frustration with what variables are set private or protected. Notch's code is largely irrational, and seems to have had little thought put into what might need to be accessed externally (External to the class/object, not necessarily the net.minecraft.* package, but that too). Forge helps significantly, but yeah... Reflection is something you're going to probably need to become friends with if you want to mod minecraft in significant ways.

View PostOrwell, on 12 January 2013 - 02:12 PM, said:

Not that many languages support something like reflection. I sure as hell know that C++ doesn't. :P But well, you just make a getter and/or a setter where needed and only where needed. :P
It depends on your definition of reflection. Technically, Java's access control manipulation isn't reflection per-se. It uses reflection, but it's a separate subject. Reflection is simply accessing classes/functions based on mapping string data to code names, which both C and C++ can do, though you don't see it that often.

But if in C I were to, say, create an enum storing a set of functions as pointers, and then read a string from a user's input and pull a matching entry from the enum, and call the pointer as a function, this would technically be reflection.

#50 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 05 October 2013 - 03:48 PM

View Posttheoriginalbit, on 02 May 2013 - 08:49 AM, said:

View PostFreack100, on 02 May 2013 - 08:44 AM, said:

-snip-
local does not have a capital L...

also as it was stated at some point you may as well remove the Person_mt table and just do this

There was no point to create a table, just so it could point to itself.
I hate writing "self".

function Person:getName()
  return self.name
end

function Person:setName(newName)
  self.name = newName
end

function Person:toString()
  return "Person Object. Name = " .. self.name
end

Also, it'd be neat bind the table's __call metamethod to its .new() method:
setmetatable(Person, { __call = Person.new })
But then you'd need to do that for every class, and at that point I'd just use a function to create new classes, so it does this for me.

#51 jay5476

  • Members
  • 289 posts

Posted 05 October 2013 - 08:42 PM

to write something like minecraft you need OOP
every block has its
-hardness
-sound when stepped on
-data
you couldnt literally do seperate programming for each block especially with world gen
you can then count on OOP by making it so that every block is create from one main block with different parametres
so all grass blocks are made by this for example
--block file
public static final BlockGrass grass = (BlockGrass)(new BlockGrass(2)).setHardness(0.6F).setStepSound(soundGrassFootstep).setUnlocalizedName("grass").func_111022_d("grass");
creates a new block of grass wherever there needs to be

another example of OOP is C.O.D.B.O.2.
say theres an 5 exploding barrels they need to know how much damage they take before exploding if you try to handle them all at once as 1 thing then you damage 1 barrel enough all 5 explode but as objects they have their own damage values
OOP is used to distinguish each 'objects' feature

#52 AgentE382

  • Members
  • 119 posts

Posted 06 October 2013 - 07:08 AM

You are misinformed. OOP is not needed to make something like Minecraft. It could be argued that OOP makes creating things like Minecraft easier, but it's certainly not necessary.

For example, there's a Minecraft server written in C, which is a procedural language. Also, LWJGL, which Minecraft uses for various tasks, including rendering, is a Java OOP wrapper around C procedural APIs.

I've also seen a First Person Shooter programmed in a strict functional language.

In case you didn't know, there are whole Operating Systems written in C. GNU/Linux is almost entirely C, the Mac OS X darwin kernel is written in C, and parts of Windows are still written in C.

You don't need OOP to do anything. Study the history of programming if you don't believe that claim. Or, you can look around and see that many games are still programmed without OOP, even though most games are programmed in C++ (an OO language) nowadays.

Note: This post is not attacking OOP, just pointing out a flaw in reasoning. Also note that it is technically possible to do OOP in C, because it's a general-purpose programming language. Also note that it is possible to program using the procedural paradigm in OOP languages, which is what many amateur Java programmers end up doing.

#53 blm768

  • Members
  • 6 posts
  • LocationUnited States

Posted 12 October 2013 - 04:22 PM

I use OOP as a tool. If it's the right tool to model a system, I'll use it. If not, I'll use another coding style, and I'll freely mix paradigms. OOP is limited, but I find it to be a useful tool in specific situations.

As for implementing OOP in Lua, here's the code I use:
function class(super)
	local cls = {}
	local instance_mt = {__index = cls}
	function cls.new(...)
		local instance = {}
		setmetatable(instance, instance_mt)
		local initializer = instance.init
		if initializer then
			initializer(instance, ...)
		end
		return instance
	end
	if super then
		setmetatable(cls, {__index = super})
	end
	return cls
end

And to use the function:
local Shape = class()

function Shape:init()
	self.x = 0
	self.y = 0
end

local Circle = class(Shape)

function circle:init(radius)
	--Superclass constructors must be called explicitly:
	Shape.init(self)
	self.radius = radius
end

function Circle:draw()
	--Some code here...
end

local c = Circle.new(3)


#54 ElvishJerricco

  • Members
  • 803 posts

Posted 14 October 2013 - 08:14 PM

View PostKingdaro, on 05 October 2013 - 03:48 PM, said:

I hate writing "self".

Completely agree. This is why I dislike metatable based OOP so much. I greatly prefer using closures and setting their environments for instantiation. There's a tutorial somewhere around here about that. It's how LuaLua implements OOP.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users