Proto-Lua: Lua Types and Helpers For Prototypal-Based Design

Hey Corona Community,

I've been a Lua user for about a year now and I truly love the language but, as a professional ActipScript and JavaScript developer I too wish it were a little easier to 'type' tables and extend those types much like JavaScripts prototypes and ActionScript classes offer. So, I decided to experiment by implementing a prototypal API for Lua.

This API follows the preferred module design pattern and anyone who knows a bit about JavaScript constructors and prototypes will be able to create 'typed' tables in no time.

Take a look at it in use: https://github.com/dschnare/Proto-Lua/blob/master/src/example.lua

Here's the source for those who just want to know how it works: https://github.com/dschnare/Proto-Lua/blob/master/src/proto.lua

The source file is fully documented and also contains a few other functions you can take advantage of mixin/adheresTo/instanceof and the is__ functions.

It's opensource so download it, use it, fork it, let me know if you like it or don't like it.

If you come from a JavaScript background you might find my Purejs API a useful starting ground since Proto-Lua was inspired by the Purejs API.

I am naive. What is the purpose of this?

Just to offer a design pattern for Lua developers to use to help make "custom types" in Lua. It's useful since Lua only really offers tables for use as complex datatypes (that and only the C++ types exposed by the Corona API developers).

Check out the links for better examples and documentation.

Simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
-- Create our Animal constructor.
local Animal = proto.constructor.create({
  init = function(self, name)
    self.name = name
  end,
  -- Copy method that facilitates our copy constructor.
  -- Up to us to initialize the instance properly.
  copy = function(self, other)
    self:init(other:getName())
  end
})
 
-- 'manually' add a new prototype method for all Animals.
function Animal.prototype:getName()
  return self.name
end
 
 
-- Create our Cat constructor that inherits from Animal's prototype.
local Cat = proto.constructor.create(Animal, {
  init = function(self, name)
    Animal.prototype.init(self, name .. ' the cat')
  end
})
 
 
-- Usage:
local felix = Cat('felix')
print('felix\'s name is: ', felix:getName()) -- felix
print('is animal a Cat: ', felix:instanceof(Cat)) -- true
views:1979 update:2011/12/30 9:10:41
corona forums © 2003-2011