lua监听内存释放

lua代码:

local dog = Dog.New()
dog:eat();

dog=nil;
collectgarbage()


c代码:

#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

#define MAX_PATH 260
 
class dog
{
public:
    dog()
    {
        printf("constroctor\n");
        memset(sName,0,MAX_PATH);
        strcpy(sName,"Kaer");
    }

    void init()
    {
        printf("init\n");
        memset(sName,0,MAX_PATH);
        strcpy(sName,"Kaer");
    }

    void  eat()
    {
        printf("%s eat\n",sName);
    }

    static int eat_api(lua_State *L)
    {
        dog *pDog = (dog*)lua_touserdata(L,-1);
        pDog->eat();
        return 0;
    }

    static int delete_dog(lua_State * L)
    {
        printf("dog is going to be deleted\n");
        return 0;
    }

    static int NewDog(lua_State * L)
    {
        void *pMemory = lua_newuserdata(L,sizeof(dog));
    //    new(pMemory)dog;

        //上面申请内存不会调用构造函数,因此我们这里给他调用初始化函数
        dog *pDog = (dog*)pMemory;
        pDog->init();

        luaL_getmetatable(L,"Dog_Metetable");
        lua_setmetatable(L,-2);
        return 1;
    }

    static int Export(lua_State * L)
    {
        luaL_Reg api_c[] = {
              {"New",NewDog},     //可以只是将new放在这个里面,其他的注册在元表中
            {NULL,NULL}
        };
        luaL_register(L,"Dog",api_c);

 
        //设置元表

        luaL_newmetatable(L,"Dog_Metetable");
        //将申请的在栈顶的metatable复制一份放在栈顶
    
        lua_pushvalue(L,-1);
        //将值设置到table中,并将上面的value出栈
        lua_setfield(L,-2,"__index");
        luaL_Reg  api_m[] = {
             {"eat", eat_api},
            {NULL,NULL}
        };

        //这个NULL,表示栈顶的元表
        luaL_register(L,NULL,api_m);

        //设置垃圾回收提示
        lua_pushcfunction(L, delete_dog);
        lua_setfield(L,-2,"__gc");
 
        return 0;
    }

public:
    char sName[MAX_PATH];
};
 
int _tmain(int argc, _TCHAR* argv[])
{
     lua_State *L =  luaL_newstate();
     luaL_openlibs(L);
 

     //注册导出类
     lua_pushcfunction(L,dog::Export);
     lua_pcall(L,0,0,0);
        
     if(0 != luaL_dofile(L,"helloworld.lua"))
     {
         printf("%s",lua_tostring(L,-1));
     }


    system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值