Skip to content

Create instances of C++ classes in Lua 5.1.x #5

@iSLC

Description

@iSLC

I've noticed that the library is able to register C++ classes but you are unable to instantiate them in Lua. I've seen this kind of ability in another project similar to this one called Selene.

Let's say I have the following (test) class:

struct Vec3
{
    // Member variables if possible.
    float x, y, z;
    // Code...

    // Multiple constructors if possible.
    Vec3() : x(0), y(0), z(0)
    {  }
    Vec3(float x, float y, float z) : x(x), y(y), z(z)
    {  }
    Vec3(const Vec3& vec) : x(vec.x), y(vec.y), z(vec.z)
    {  }
    // Code...

    // Operators if possible.
    Vec3 operator+(const Vec3& vec)
    { return Vec3(x + vec.x, y + vec.y, z + vec.z); }
    Vec3 operator-(const Vec3& vec)
    { return Vec3(x - vec.x, y - vec.y, z - vec.z); }
    // Code...

    // Member functions if possible.
    void zero()
    { x = y = z = 0; }
    void negate()
    { x = -x; y = -y; z = -z; }
    // Code...

    // Getters and setters if necessary.
    void set(float x, float y, float z)
    { this->x = x; this->y = y; this->z = z; }

    void setx(float x) { this->x = x; }
    void sety(float y) { this->y = y; }
    void setz(float z) { this->z = z; }

    float getx() { return x; }
    float gety() { return y; }
    float getz() { return z; }
    // Code...
};

And after I register in in Lua I should be able to do:

-- Multiple constructors if possible.
empty = Vec3.new()
specific = Vec3.new(5, 9, 2)
copy = Vec3.new(empty)

-- Operators if possible but NOT! a complete requirement.
copy = copy + specific

-- Member functions if possible.
specific.negate()
copy.empty()

-- Getters and setters if necessary.
copy.set(82, 33, 76)
ex empty.getx();
ey empty.gety();
ez empty.getz();

-- And so on....

But only if it's possible and in Lua 5.1.5 because I need to use it with LuaJit. The current library worked with my small tests however I need to be able to create new objects in Lua.

Selene is for Lua 5.2+ and therefore incompatible with LuaJit which is why is it doesn't fit my needs.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions