How to create class with public methods?

How can I create a class which has public functions? (Or something close to this, in Lua-style…)

Follow-up question: How can I then put this class in its own file and include it?

Thanks! [import]uid: 10284 topic_id: 3733 reply_id: 303733[/import]

Uh-uh! :slight_smile:
I suppose you should read through the Lua programming manual first. A couple of hours of it at least.

Your “classes” can be implemented using tables. (not “real classes”, but quite close…) Tables are basically associative arrays, where you can use anything as a “key”.

Simple example:

[lua]local myObject = {} – simplest table constructor
myObject.data = 0 – a member

function myObject:printData() – a method. the “:” syntax passes the hidden argument “self”, which is the myObject table itself. Similar to “this” in Java.
print(self.data) – will print “0”
end

– at some point…

myObject:printData() – method called! prints “0”[/lua]

More info:

http://www.lua.org/pil/16.html

[import]uid: 5750 topic_id: 3733 reply_id: 11357[/import]

Thanks, yeah, I knew about Lua’s tables/ associative arrays, but had a problem buried elsewhere in my code – I actually did use a structure similar to what you point out, albeit all wrapped in big function… my next goal will be to outsource that to its own file and perhaps take it out of the big function wrapper. Thanks for the link to the Lua.org chapter, that should come in very handy!! [import]uid: 10284 topic_id: 3733 reply_id: 11359[/import]

you’ll find that even in the Ansca team’s code there are a variety of methods i think

some use a single function for the “class” / constructor, and then nest functions within that
some use the prototype method eg MyClass:new MyClass:doSomething etc

compare their MovieClip.lua example to their Facebook.lua example … i think they are slightly different in structure

it’s worth digging around the example code and deciding which suits you best.

altho it would be better if we were all doing it the same way :wink:

[import]uid: 6645 topic_id: 3733 reply_id: 11365[/import]