您的位置:首页 > 编程语言 > Lua

lua监听内存释放

2016-12-13 17:44 225 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: