1

Referring to the this question, suppose to have a Lua C module structured in the following way:

#include "lauxlib.h"
#include "lua.h"

static int lb_newmatrix(lua_State *L)
{
     (...some code...)
     luaL_getmetatable(L,"lb_basic");
     lua_setmetatable(L,-2);
     return 1;
}

static int lb_SUM(lua_State *L)
{
     (...some code...)
}

static int lb_SUB(lua_State *L)
{
     (...some code...)
}

static int lb_SET(lua_State *L)
{
     (...some code...)
}

static const struct luaL_Reg LuaBasic_f [] = {//
        { "NewMatrix", lb_newmatrix},
        {        NULL,         NULL}};

static const struct luaL_Reg LuaBasic_m [] = {//
        { "__add", lb_SUM},
        { "__sub", lb_SUB},
        {    NULL,   NULL}};

static const struct luaL_Reg LuaBasic_oo [] = {//
        { "set", lb_SET},
        {  NULL,   NULL}};

LUA_API int luaopen_LuaBasic(lua_State *L)
{
    // Insert basic metatable "lb_basic" into the stack
    luaL_newmetatable(L,"lb_basic");

    // Register the metamethods inside "lb_basic"
    luaL_setfuncs(L,LuaBasic_m,0);

    // PROCEDURE TO ADD OO
    // DOES NOT WORK
    //lua_pushvalue(L,-1);
    //lua_setfield(L,-2,"__index");
    //luaL_setfuncs(L,LuaBasic_oo,0);

    luaL_newlib(L,LuaBasic_f);
    return 1;

}

In this code, I have a function to create a matrix which has the "lb_basic" metatable associated. Into this metatable, I register all the functions inside luaL_Reg LuaBasic_m.

Some function (which I want them as object) are collected inside luaL_Reg LuaBasic_oo.

What I want to do is to add some object in ordert to use my matrix as follow:

lb = require("LuaBasic")
A = lb.newmatrix(3,4)
B = A+A-A+A;
B:set(2,3,9999)
print(B[2][3])

How can I add the function lb_SET as an object to my module? Where do I have to register them?

Many Thanks in advance.

Azoun
  • 255
  • 3
  • 14

0 Answers0