Wednesday, 16 February 2011

No classes and objects in Lua. So...



So let's use old-C structs :D
How?
Image a struct to define a 2d point. It will looks like

struct Point2DStruct{
    double x;
    double y;
};

typedef struct Point2DStruct Point2D;

Point2D* new_Point2D(double x, double y){
    Point2D* result;
    result=(Point2D*)malloc(sizeof(Point2D));
    result->x=x;
    result->y=y;
    return result;
}

How we can do something similiar in Lua? With a table!

function new_Point2D(newx,newy)
    result={x=newx,y=newy};
    return result;
end

Easy, fast, and good looking. Well, you can also implement objects and classes using metatables. But I prefer using this "structured" way, because it's easier to read a to write.

No comments: